private String getStrToSign(HttpServletRequest request) { try { this.body = GetPostBody( request.getInputStream(), Integer.parseInt(request.getHeader("content-length"))); } catch (IOException e) { log.error(e.getMessage()); return null; } String queryString = request.getQueryString(); String uri = request.getRequestURI(); String decodeUri; try { decodeUri = java.net.URLDecoder.decode(uri, "UTF-8"); } catch (UnsupportedEncodingException e) { log.error(e.getMessage()); return null; } String authStr = decodeUri; if (queryString != null && !queryString.equals("")) { authStr += "?" + queryString; } authStr += "\n" + this.body; return authStr; }
public static String xmlToJson(String xml, boolean formatted) throws XMLStreamException { InputStream input = new ByteArrayInputStream(xml.getBytes()); ByteArrayOutputStream output = new ByteArrayOutputStream(); JsonXMLConfig config = new JsonXMLConfigBuilder() .autoArray(true) .autoPrimitive(true) .prettyPrint(formatted) .build(); try { XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(input); XMLEventWriter writer = new JsonXMLOutputFactory(config).createXMLEventWriter(output); writer.add(reader); reader.close(); writer.close(); try { return output.toString("UTF-8"); } catch (UnsupportedEncodingException e) { throw new XMLStreamException(e.getMessage()); } } finally { // dp nothing } }
private void parseAuth() { errReceiver.info( new SAXParseException(WscompileMessages.WSIMPORT_READING_AUTH_FILE(authFile), null)); BufferedReader in; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(authFile), "UTF-8")); } catch (UnsupportedEncodingException e) { error(new SAXParseException(e.getMessage(), null)); return; } catch (FileNotFoundException e) { error( new SAXParseException( WscompileMessages.WSIMPORT_AUTH_FILE_NOT_FOUND(authFile, defaultAuthfile), null, e)); return; } String text; LocatorImpl locator = new LocatorImpl(); try { int lineno = 1; locator.setSystemId(authFile.getCanonicalPath()); while ((text = in.readLine()) != null) { locator.setLineNumber(lineno++); try { URL url = new URL(text); String authinfo = url.getUserInfo(); if (authinfo != null) { int i = authinfo.indexOf(':'); if (i >= 0) { String user = authinfo.substring(0, i); String password = authinfo.substring(i + 1); authInfo.add(new AuthInfo(new URL(text), user, password)); } else { error( new SAXParseException( WscompileMessages.WSIMPORT_ILLEGAL_AUTH_INFO(url), locator)); } } else { error( new SAXParseException(WscompileMessages.WSIMPORT_ILLEGAL_AUTH_INFO(url), locator)); } } catch (NumberFormatException e) { error(new SAXParseException(WscompileMessages.WSIMPORT_ILLEGAL_AUTH_INFO(text), locator)); } } in.close(); } catch (IOException e) { error( new SAXParseException( WscompileMessages.WSIMPORT_FAILED_TO_PARSE(authFile, e.getMessage()), locator)); } }
private String urlEncode(String s) { try { return URLEncoder.encode(s, "UTF-8"); } catch (UnsupportedEncodingException unsupportedEncodingException) { throw new HipChatNotificationPluginException( "URL encoding error: [" + unsupportedEncodingException.getMessage() + "].", unsupportedEncodingException); } }
/** {@inheritDoc} */ public synchronized Result createConference(String creator, String mucRoomName) { Conference conference = conferenceMap.get(mucRoomName); if (conference == null) { // Create new conference try { ApiResult result = api.createNewConference(creator, mucRoomName); if (result.getError() == null) { conference = result.getConference(); conferenceMap.put(mucRoomName, conference); } else if (result.getStatusCode() == 409 && result.getError().getConflictId() != null) { Number conflictId = result.getError().getConflictId(); // Conference already exists(check if we have it locally) conference = findConferenceForId(conflictId); logger.info("Conference '" + mucRoomName + "' already " + "allocated, id: " + conflictId); // do GET conflict conference if (conference == null) { ApiResult getResult = api.getConference(conflictId); if (getResult.getConference() != null) { conference = getResult.getConference(); // Fill full room name as it is not transferred // over REST API conference.setMucRoomName(mucRoomName); conferenceMap.put(mucRoomName, conference); } else { logger.error("API error: " + result); return new Result(RESULT_INTERNAL_ERROR, result.getError().getMessage()); } } } else { // Other error logger.error("API error: " + result); return new Result(RESULT_INTERNAL_ERROR, result.getError().getMessage()); } } catch (FaultTolerantRESTRequest.RetryExhaustedException e) { logger.error(e, e); return new Result(RESULT_INTERNAL_ERROR, e.getMessage()); } catch (UnsupportedEncodingException e) { logger.error(e, e); return new Result(RESULT_INTERNAL_ERROR, e.getMessage()); } } // Verify owner == creator if (creator.equals(conference.getOwner())) { return new Result(RESULT_OK); } else { logger.error( "Room " + mucRoomName + ", conflict : " + creator + " != " + conference.getOwner()); return new Result(RESULT_CONFLICT); } }
public XMLCleanup() { bytes = new ByteArrayOutputStream(); try { out = new OutputStreamWriter(bytes, "UTF8"); } catch (UnsupportedEncodingException e) { LOG.warn("XMLCleanup() unsupported encoding: " + e.getMessage()); } }
/** * 访问服务器环境 * * @param names 参数名字 * @param values 参数值 */ public static void visitEnvServerByParameters(String[] names, String[] values) { int len = Math.min(ArrayUtils.getLength(names), ArrayUtils.getLength(values)); String[] segs = new String[len]; for (int i = 0; i < len; i++) { try { // 设计器里面据说为了改什么界面统一, 把分隔符统一用File.separator, 意味着在windows里面报表路径变成了\ // 以前的超链, 以及预览url什么的都是/, 产品组的意思就是用到的地方替换下, 真恶心. String value = values[i].replaceAll("\\\\", "/"); segs[i] = URLEncoder.encode(CodeUtils.cjkEncode(names[i]), EncodeConstants.ENCODING_UTF_8) + "=" + URLEncoder.encode(CodeUtils.cjkEncode(value), "UTF-8"); } catch (UnsupportedEncodingException e) { FRContext.getLogger().error(e.getMessage(), e); } } String postfixOfUri = (segs.length > 0 ? "?" + StableUtils.join(segs, "&") : StringUtils.EMPTY); if (FRContext.getCurrentEnv() instanceof RemoteEnv) { try { if (Utils.isEmbeddedParameter(postfixOfUri)) { String time = Calendar.getInstance().getTime().toString().replaceAll(" ", ""); boolean isUserPrivilege = ((RemoteEnv) FRContext.getCurrentEnv()).writePrivilegeMap(time, postfixOfUri); postfixOfUri = isUserPrivilege ? postfixOfUri + "&fr_check_url=" + time + "&id=" + FRContext.getCurrentEnv().getUserID() : postfixOfUri; } String urlPath = getWebBrowserPath(); Desktop.getDesktop().browse(new URI(urlPath + postfixOfUri)); } catch (Exception e) { FRContext.getLogger().error("cannot open the url Successful", e); } } else { try { String web = GeneralContext.getCurrentAppNameOfEnv(); String url = "http://localhost:" + DesignerEnvManager.getEnvManager().getJettyServerPort() + "/" + web + "/" + ConfigManager.getProviderInstance().getServletMapping() + postfixOfUri; StartServer.browerURLWithLocalEnv(url); } catch (Throwable e) { // } } }
private void refreshContent() { if (dirty) { try { this.content = URLEncodedUtils.format(params, charset).getBytes(charset); } catch (UnsupportedEncodingException e) { LogUtils.e(e.getMessage(), e); } dirty = false; } }
/** * Sets a JSON String as a request entity. * * @param httpRequest The request to set entity. * @param json The JSON String to set. */ protected void setEntity(HttpEntityEnclosingRequestBase httpRequest, String json) { try { StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); httpRequest.setEntity(entity); } catch (UnsupportedEncodingException e) { log.error("Error setting request data. " + e.getMessage()); throw new IllegalArgumentException(e); } }
public ErrorInfo listPolicy(String polname, String token) throws IOException, RestException { String realm = "/"; String data = null; ErrorInfo ei = null; InputStreamReader iss = null; BufferedReader br = null; HttpURLConnection urlc = null; InputStream inputStream = null; try { data = "policynames=" + URLEncoder.encode(polname, "UTF-8") + "&realm=" + URLEncoder.encode(realm, "UTF-8") + "&submit=" + URLEncoder.encode("Submit", "UTF-8"); } catch (UnsupportedEncodingException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } if (data != null) { try { r.Connect(new URL(url + ssoadm_list)); } catch (MalformedURLException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } urlc = (HttpURLConnection) r.c; urlc.addRequestProperty("Cookie", "iPlanetDirectoryPro=\"" + token + "\""); r.Send(urlc, data); String answer = null; int status = 0; inputStream = urlc.getInputStream(); iss = new InputStreamReader(inputStream); br = new BufferedReader(iss); answer = BrToString(br); status = urlc.getResponseCode(); if (answer != null) { ei = new ErrorInfo(answer, status); } br.close(); iss.close(); inputStream.close(); urlc.disconnect(); } return ei; }
public ErrorInfo doLogin() throws IOException, RestException { String data = null; ErrorInfo ei = null; InputStreamReader iss = null; BufferedReader br = null; HttpURLConnection urlc = null; InputStream inputStream = null; try { data = "username="******"UTF-8") + "&password="******"UTF-8"); } catch (UnsupportedEncodingException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } if (data != null) { try { r.Connect(new URL(url + authenticate)); } catch (MalformedURLException e) { System.out.println("OpenssoHelper: " + e.getMessage()); e.printStackTrace(); } urlc = (HttpURLConnection) r.c; r.Send(urlc, data); String answer = null; int status = 0; inputStream = urlc.getInputStream(); iss = new InputStreamReader(inputStream); br = new BufferedReader(iss); answer = BrToString(br); status = urlc.getResponseCode(); if (answer != null) { ei = new ErrorInfo(answer, status); } br.close(); iss.close(); inputStream.close(); urlc.disconnect(); } return ei; }
public void parsePyPIList(final List<String> packages, final PyPackageService service) { myPackageNames = null; for (String pyPackage : packages) { try { final Matcher matcher = PYPI_PATTERN.matcher(URLDecoder.decode(pyPackage, "UTF-8")); if (matcher.find()) { final String packageName = matcher.group(1); final String packageVersion = matcher.group(2); if (!packageName.contains(" ")) service.PY_PACKAGES.put(packageName, packageVersion); } } catch (UnsupportedEncodingException e) { LOG.warn(e.getMessage()); } } }
public void printList(Node[] nodes) { PrintWriter pw; try { pw = new PrintWriter("wordCount_Output_HP.txt", "UTF-8"); for (int i = 0; i < nodes.length; i++) { pw.println("(" + nodes[i].data + ", " + nodes[i].count + ")"); } pw.close(); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); e.printStackTrace(); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); e.printStackTrace(); } }
/** * Constructs an instance with the specified output stream, character encoding and indentation. * * @throws MarcException */ public MarcXmlWriter(OutputStream out, String encoding, boolean indent) { this.encoding = encoding; if (out == null) { throw new NullPointerException("null OutputStream"); } if (this.encoding == null) { throw new NullPointerException("null encoding"); } try { setIndent(indent); writer = new OutputStreamWriter(out, encoding); writer = new BufferedWriter(writer); setHandler(new StreamResult(writer), null); } catch (UnsupportedEncodingException e) { throw new MarcException(e.getMessage(), e); } writeStartDocument(); }
/** * Parses the term passed in the parameter and returns a JIPTerm object that wraps the * corresponding prolog term.<br> * If the string passed in the parameter doesn't contains a valid prolog term it raises a * JIPSyntaxErrorException. * * @param strTerm Term to be parsed. If the term doesn't end with a "dot" one is appended to it. * @return a new JIPTerm object. * @exception com.ugos.jiprolog.engine.JIPSyntaxErrorException */ public final JIPTerm parseTerm(String strTerm) throws JIPSyntaxErrorException { try { final byte[] btTerm = strTerm.getBytes(getEncoding()); final ByteArrayInputStream is = new ByteArrayInputStream(btTerm); PrologParser parser = new PrologParser( new ParserReader(new PushbackLineNumberInputStream(is)), m_opManager, m_engine, "user"); m_singletonVars = parser.getSingletonVariables(); final PrologObject term = parser.parseNext(); return JIPTerm.getJIPTerm(term); } catch (UnsupportedEncodingException ex) { throw new JIPRuntimeException(ex.getMessage()); } }
public static boolean convert( String infile, String outfile, String encodingInputFile, String encodingOutputFile) { boolean result = false; try (InputStream in = new FileInputStream(infile); OutputStream out = new FileOutputStream(outfile); Reader r = new BufferedReader(new InputStreamReader(in, encodingInputFile)); Writer w = new BufferedWriter(new OutputStreamWriter(out, encodingOutputFile)); ) { char[] buffer = new char[4096]; int len; while ((len = r.read(buffer)) != -1) w.write(buffer, 0, len); result = true; } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } return result; }
private static String inflateGzip(final byte[] bytes) { log.debug("Decompressing GZIP data"); try { try (final GZIPInputStream stream = new GZIPInputStream(new ByteArrayInputStream(bytes)); final BufferedReader buffer = new BufferedReader(new InputStreamReader(stream, "UTF-8")); ) { String value = ""; String line; while ((line = buffer.readLine()) != null) { value += line; } return value; } } catch (final UnsupportedEncodingException e) { log.warn("Unsupported encoding, using string as is: {}", e.getMessage()); return new String(bytes); } catch (final IOException e) { log.warn("Compression exception, using string as is: {}", e.getMessage()); return new String(bytes); } }
public static void main(String[] args) { try { File fileDir = new File("c:\\temp\\test.txt"); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDir), "UTF8")); out.append("Website UTF-8").append("\r\n"); out.append("想法 - UTF-8").append("\r\n"); out.append("你的还是我的,我的也是我的 - UTF-8").append("\r\n"); out.flush(); out.close(); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } }
public Reader bootstrapInput(ReaderConfig cfg, boolean mainDoc, int xmlVersion) throws IOException, XMLStreamException { String normEnc = null; // First, let's get the buffers... int bufSize = cfg.getInputBufferLength(); if (bufSize < MIN_BUF_SIZE) { bufSize = MIN_BUF_SIZE; } if (mByteBuffer == null) { // non-null if we were passed a buffer mByteBuffer = cfg.allocFullBBuffer(bufSize); } resolveStreamEncoding(); if (hasXmlDecl()) { // note: readXmlDecl will set mXml11Handling too readXmlDecl(mainDoc, xmlVersion); if (mFoundEncoding != null) { normEnc = verifyXmlEncoding(mFoundEncoding); } } else { /* We'll actually then just inherit whatever main doc had... * (or in case there was no parent, just copy the 'unknown') */ mXml11Handling = (XmlConsts.XML_V_11 == xmlVersion); } // Now, have we figured out the encoding? if (normEnc == null) { // not via xml declaration /* 21-Sep-2007, TSa: As with any non-UTF-8 encoding, declaration * isn't optional any more. Besides, we need that information * anyway to know which variant it is. */ if (mEBCDIC) { if (mFoundEncoding == null || mFoundEncoding.length() == 0) { reportXmlProblem( "Missing encoding declaration: underlying encoding looks like an EBCDIC variant, but no xml encoding declaration found"); } // Hmmh. What should be the canonical name? Let's just use found encoding? normEnc = mFoundEncoding; } else if (mBytesPerChar == 2) { // UTF-16, BE/LE normEnc = mBigEndian ? CharsetNames.CS_UTF16BE : CharsetNames.CS_UTF16LE; } else if (mBytesPerChar == 4) { // UCS-4... ? /* 22-Mar-2005, TSa: JDK apparently has no way of dealing * with these encodings... not sure if and how it should * be dealt with, really. Name could be UCS-4xx... or * perhaps UTF-32xx */ normEnc = mBigEndian ? CharsetNames.CS_UTF32BE : CharsetNames.CS_UTF32LE; } else { // Ok, default has to be UTF-8, as per XML specs normEnc = CharsetNames.CS_UTF8; } } mInputEncoding = normEnc; /* And then the reader. Let's figure out if we can use our own fast * implementations first: */ BaseReader r; // Normalized, can thus use straight equality checks now if (normEnc == CharsetNames.CS_UTF8) { r = new UTF8Reader(cfg, mIn, mByteBuffer, mInputPtr, mInputEnd, mRecycleBuffer); } else if (normEnc == CharsetNames.CS_ISO_LATIN1) { r = new ISOLatinReader(cfg, mIn, mByteBuffer, mInputPtr, mInputEnd, mRecycleBuffer); } else if (normEnc == CharsetNames.CS_US_ASCII) { r = new AsciiReader(cfg, mIn, mByteBuffer, mInputPtr, mInputEnd, mRecycleBuffer); } else if (normEnc.startsWith(CharsetNames.CS_UTF32)) { // let's augment with actual endianness info if (normEnc == CharsetNames.CS_UTF32) { mInputEncoding = mBigEndian ? CharsetNames.CS_UTF32BE : CharsetNames.CS_UTF32LE; } r = new UTF32Reader(cfg, mIn, mByteBuffer, mInputPtr, mInputEnd, mRecycleBuffer, mBigEndian); } else { // Nah, JDK needs to try it // Ok; first, do we need to merge stuff back? InputStream in = mIn; if (mInputPtr < mInputEnd) { in = new MergedStream(cfg, in, mByteBuffer, mInputPtr, mInputEnd); } /* 20-Jan-2006, TSa: Ok; although it is possible to declare * stream as 'UTF-16', JDK may need help in figuring out * the right order, so let's be explicit: */ if (normEnc == CharsetNames.CS_UTF16) { mInputEncoding = normEnc = mBigEndian ? CharsetNames.CS_UTF16BE : CharsetNames.CS_UTF16LE; } try { return new InputStreamReader(in, normEnc); } catch (UnsupportedEncodingException usex) { throw new WstxIOException("Unsupported encoding: " + usex.getMessage()); } } if (mXml11Handling) { r.setXmlCompliancy(XmlConsts.XML_V_11); } return r; }
private boolean encodeObject(Object object) throws IOException { if (object instanceof BEncodableObject) { object = ((BEncodableObject) object).toBencodeObject(); } if (object instanceof String || object instanceof Float) { String tempString = (object instanceof String) ? (String) object : String.valueOf((Float) object); // usually this is simpler to encode by hand as chars < 0x80 map directly in UTF-8 boolean simple = true; int char_count = tempString.length(); byte[] encoded = new byte[char_count]; for (int i = 0; i < char_count; i++) { char c = tempString.charAt(i); if (c < 0x80) { encoded[i] = (byte) c; } else { simple = false; break; } } if (simple) { writeInt(char_count); writeChar(':'); writeBytes(encoded); } else { ByteBuffer bb = Constants.DEFAULT_CHARSET.encode(tempString); writeInt(bb.limit()); writeChar(':'); writeByteBuffer(bb); } } else if (object instanceof Map) { Map tempMap = (Map) object; SortedMap tempTree = null; // unfortunately there are some occasions where we want to ensure that // the 'key' of the map is not mangled by assuming its UTF-8 encodable. // In particular the response from a tracker scrape request uses the // torrent hash as the KEY. Hence the introduction of the type below // to allow the constructor of the Map to indicate that the keys should // be extracted using a BYTE_ENCODING boolean byte_keys = object instanceof ByteEncodedKeyHashMap; // write the d writeChar('d'); // are we sorted? if (tempMap instanceof TreeMap) { tempTree = (TreeMap) tempMap; } else { tempTree = new TreeMap(tempMap); } Iterator it = tempTree.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object o_key = entry.getKey(); Object value = entry.getValue(); if (value != null) { if (o_key instanceof byte[]) { encodeObject(o_key); if (!encodeObject(value)) encodeObject(""); } else if (o_key instanceof String) { String key = (String) o_key; if (byte_keys) { try { encodeObject(Constants.BYTE_CHARSET.encode(key)); if (!encodeObject(value)) encodeObject(""); } catch (UnsupportedEncodingException e) { throw (new IOException("BEncoder: unsupport encoding: " + e.getMessage())); } } else { encodeObject(key); // Key goes in as UTF-8 if (!encodeObject(value)) encodeObject(""); } } else Debug.out( "Attempt to encode an unsupported map key type: " + object.getClass() + ";value=" + object); } } writeChar('e'); } else if (object instanceof List) { List tempList = (List) object; // write out the l writeChar('l'); for (int i = 0; i < tempList.size(); i++) { encodeObject(tempList.get(i)); } writeChar('e'); } else if (object instanceof Long) { Long tempLong = (Long) object; // write out the l writeChar('i'); writeLong(tempLong.longValue()); writeChar('e'); } else if (object instanceof Integer) { Integer tempInteger = (Integer) object; // write out the l writeChar('i'); writeInt(tempInteger.intValue()); writeChar('e'); } else if (object instanceof byte[]) { byte[] tempByteArray = (byte[]) object; writeInt(tempByteArray.length); writeChar(':'); if (url_encode) { writeBytes( URLEncoder.encode( new String(tempByteArray, Constants.BYTE_ENCODING), Constants.BYTE_ENCODING) .getBytes()); } else { writeBytes(tempByteArray); } } else if (object instanceof ByteBuffer) { ByteBuffer bb = (ByteBuffer) object; writeInt(bb.limit()); writeChar(':'); writeByteBuffer(bb); } else if (object == null) { // ideally we'd bork here but I don't want to run the risk of breaking existing stuff so just // log Debug.out("Attempt to encode a null value: sofar=" + getEncodedSoFar()); return false; } else { Debug.out( "Attempt to encode an unsupported entry type: " + object.getClass() + ";value=" + object); return false; } return true; }
EncryptedFormInformation( String formId, String formVersion, InstanceMetadata instanceMetadata, PublicKey rsaPublicKey, Base64Wrapper wrapper) { this.formId = formId; this.formVersion = formVersion; this.instanceMetadata = instanceMetadata; this.rsaPublicKey = rsaPublicKey; this.wrapper = wrapper; // generate the symmetric key from random bits... SecureRandom r = new SecureRandom(); byte[] key = new byte[SYMMETRIC_KEY_LENGTH / 8]; r.nextBytes(key); SecretKeySpec sk = new SecretKeySpec(key, SYMMETRIC_ALGORITHM); symmetricKey = sk; // construct the fixed portion of the iv -- the ivSeedArray // this is the md5 hash of the instanceID and the symmetric key try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(instanceMetadata.instanceId.getBytes(UTF_8)); md.update(key); byte[] messageDigest = md.digest(); ivSeedArray = new byte[IV_BYTE_LENGTH]; for (int i = 0; i < IV_BYTE_LENGTH; ++i) { ivSeedArray[i] = messageDigest[(i % messageDigest.length)]; } } catch (NoSuchAlgorithmException e) { Log.e(t, e.toString()); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (UnsupportedEncodingException e) { Log.e(t, e.toString()); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } // construct the base64-encoded RSA-encrypted symmetric key try { Cipher pkCipher; pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM); // write AES key pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey); byte[] pkEncryptedKey = pkCipher.doFinal(key); String alg = pkCipher.getAlgorithm(); Log.i(t, "AlgorithmUsed: " + alg); base64RsaEncryptedSymmetricKey = wrapper.encodeToString(pkEncryptedKey); } catch (NoSuchAlgorithmException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (NoSuchPaddingException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (InvalidKeyException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (IllegalBlockSizeException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (BadPaddingException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } // start building elementSignatureSource... appendElementSignatureSource(formId); if (formVersion != null) { appendElementSignatureSource(formVersion.toString()); } appendElementSignatureSource(base64RsaEncryptedSymmetricKey); appendElementSignatureSource(instanceMetadata.instanceId); }
public String getBase64EncryptedElementSignature() { // Step 0: construct the text of the elements in elementSignatureSource (done) // Where... // * Elements are separated by newline characters. // * Filename is the unencrypted filename (no .enc suffix). // * Md5 hashes of the unencrypted files' contents are converted // to zero-padded 32-character strings before concatenation. // Assumes this is in the order: // formId // version (omitted if null) // base64RsaEncryptedSymmetricKey // instanceId // for each media file { filename "::" md5Hash } // submission.xml "::" md5Hash // Step 1: construct the (raw) md5 hash of Step 0. byte[] messageDigest; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(elementSignatureSource.toString().getBytes(UTF_8)); messageDigest = md.digest(); } catch (NoSuchAlgorithmException e) { Log.e(t, e.toString()); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (UnsupportedEncodingException e) { Log.e(t, e.toString()); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } // Step 2: construct the base64-encoded RSA-encrypted md5 try { Cipher pkCipher; pkCipher = Cipher.getInstance(ASYMMETRIC_ALGORITHM); // write AES key pkCipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey); byte[] pkEncryptedKey = pkCipher.doFinal(messageDigest); return wrapper.encodeToString(pkEncryptedKey); } catch (NoSuchAlgorithmException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (NoSuchPaddingException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (InvalidKeyException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (IllegalBlockSizeException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } catch (BadPaddingException e) { Log.e(t, "Unable to encrypt the symmetric key"); e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } }
/** * Parse the content of a purported HTML stream digital object and store the results in RepInfo. * * @param stream An InputStream, positioned at its beginning, which is generated from the object * to be parsed. If multiple calls to <code>parse</code> are made on the basis of a nonzero * value being returned, a new InputStream must be provided each time. * @param info A fresh (on the first call) RepInfo object which will be modified to reflect the * results of the parsing If multiple calls to <code>parse</code> are made on the basis of a * nonzero value being returned, the same RepInfo object should be passed with each call. * @param parseIndex Must be 0 in first call to <code>parse</code>. If <code>parse</code> returns * a nonzero value, it must be called again with <code>parseIndex</code> equal to that return * value. */ public int parse(InputStream stream, RepInfo info, int parseIndex) throws IOException { if (parseIndex != 0) { // Coming in with parseIndex = 1 indicates that we've determined // this is XHTML; so we invoke the XML module to parse it. // If parseIndex is 100, this is the first invocation of the // XML module, so we call it with 0; otherwise we call it with // the value of parseIndex. if (isXmlAvailable()) { edu.harvard.hul.ois.jhove.module.XmlModule xmlMod = new edu.harvard.hul.ois.jhove.module.XmlModule(); if (parseIndex == 100) { parseIndex = 0; } xmlMod.setApp(_app); xmlMod.setBase(_je); xmlMod.setDefaultParams(_defaultParams); try { xmlMod.applyDefaultParams(); } catch (Exception e) { // really shouldn't happen } xmlMod.setXhtmlDoctype(_doctype); return xmlMod.parse(stream, info, parseIndex); } else { // The XML module shouldn't be missing from any installation, // but someone who really wanted to could remove it. In // that case, you deserve what you get. info.setMessage(new ErrorMessage("XML-HUL module required to validate XHTML documents")); info.setWellFormed(false); // Treat it as completely wrong return 0; } } else { /* parseIndex = 0, first call only */ _doctype = null; } // Test if textMD is to be generated if (_defaultParams != null) { Iterator iter = _defaultParams.iterator(); while (iter.hasNext()) { String param = (String) iter.next(); if (param.toLowerCase().equals("withtextmd=true")) { _withTextMD = true; } } } initParse(); info.setFormat(_format[0]); info.setMimeType(_mimeType[0]); info.setModule(this); if (_textMD == null || parseIndex == 0) { _textMD = new TextMDMetadata(); } /* We may have already done the checksums while converting a temporary file. */ Checksummer ckSummer = null; if (_je != null && _je.getChecksumFlag() && info.getChecksum().size() == 0) { ckSummer = new Checksummer(); _cstream = new ChecksumInputStream(stream, ckSummer); _dstream = getBufferedDataStream(_cstream, _je != null ? _je.getBufferSize() : 0); } else { _dstream = getBufferedDataStream(stream, _je != null ? _je.getBufferSize() : 0); } ParseHtml parser = null; HtmlMetadata metadata = null; HtmlCharStream cstream = null; try { cstream = new HtmlCharStream(_dstream, "ISO-8859-1"); parser = new ParseHtml(cstream); } catch (UnsupportedEncodingException e) { info.setMessage(new ErrorMessage("Internal error: " + e.getMessage())); info.setWellFormed(false); return 0; // shouldn't happen! } int type = 0; try { List elements = parser.HtmlDoc(); if (elements.isEmpty()) { // Consider an empty document bad info.setWellFormed(false); info.setMessage(new ErrorMessage("Document is empty")); return 0; } type = checkDoctype(elements); if (type < 0) { info.setWellFormed(false); info.setMessage(new ErrorMessage("DOCTYPE is not HTML")); return 0; } /* Check if there is at least one html, head, body or title tag. * A plain text document * might be interpreted as a single PCDATA, which is in some * ethereal sense well-formed HTML, but it's pointless to consider * it such. It might also use angle brackets as a text delimiter, * and that shouldn't count as HTML either. */ boolean hasElements = false; Iterator iter = elements.iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof JHOpenTag) { String name = ((JHOpenTag) o).getName(); if ("html".equals(name) || "head".equals(name) || "body".equals(name) || "title".equals(name)) { hasElements = true; } break; } } if (!hasElements) { info.setMessage(new ErrorMessage("Document contains no html, head, body or title tags")); info.setWellFormed(false); return 0; } // CRLF from HtmlCharStream ... String lineEnd = cstream.getKindOfLineEnd(); if (lineEnd == null) { info.setMessage(new InfoMessage("Not able to determine type of end of line")); _textMD.setLinebreak(TextMDMetadata.NILL); } else if (lineEnd.equalsIgnoreCase("CR")) { _textMD.setLinebreak(TextMDMetadata.LINEBREAK_CR); } else if (lineEnd.equalsIgnoreCase("LF")) { _textMD.setLinebreak(TextMDMetadata.LINEBREAK_LF); } else if (lineEnd.equalsIgnoreCase("CRLF")) { _textMD.setLinebreak(TextMDMetadata.LINEBREAK_CRLF); } if (type == 0) { /* If we can't find a doctype, it still might be XHTML * if the elements start with an XML declaration and * the root element is "html" */ switch (seemsToBeXHTML(elements)) { case 0: // Not XML break; // fall through case 1: // XML but not HTML info.setMessage( new ErrorMessage( "Document has XML declaration but no DOCTYPE; " + "probably XML rather than HTML")); info.setWellFormed(false); return 0; case 2: // probably XHTML return 100; } info.setMessage( new ErrorMessage( "Unrecognized or missing DOCTYPE declaration; " + "validation continuing as HTML 3.2")); info.setValid(false); // But keep going } HtmlDocDesc docDesc = null; switch (type) { case HTML_3_2: default: docDesc = new Html3_2DocDesc(); _textMD.setMarkup_basis("HTML"); _textMD.setMarkup_basis_version("3.2"); break; case HTML_4_0_FRAMESET: docDesc = new Html4_0FrameDocDesc(); _textMD.setMarkup_basis("HTML"); _textMD.setMarkup_basis_version("4.0"); break; case HTML_4_0_TRANSITIONAL: docDesc = new Html4_0TransDocDesc(); _textMD.setMarkup_basis("HTML"); _textMD.setMarkup_basis_version("4.0"); break; case HTML_4_0_STRICT: docDesc = new Html4_0StrictDocDesc(); _textMD.setMarkup_basis("HTML"); _textMD.setMarkup_basis_version("4.0"); break; case HTML_4_01_FRAMESET: docDesc = new Html4_01FrameDocDesc(); _textMD.setMarkup_basis("HTML"); _textMD.setMarkup_basis_version("4.01"); break; case HTML_4_01_TRANSITIONAL: docDesc = new Html4_01TransDocDesc(); _textMD.setMarkup_basis("HTML"); _textMD.setMarkup_basis_version("4.01"); break; case HTML_4_01_STRICT: docDesc = new Html4_01StrictDocDesc(); _textMD.setMarkup_basis("HTML"); _textMD.setMarkup_basis_version("4.01"); break; case XHTML_1_0_STRICT: case XHTML_1_0_TRANSITIONAL: case XHTML_1_0_FRAMESET: case XHTML_1_1: // Force a second call to parse as XML. 100 is a // magic code for the first XML call. return 100; } _textMD.setMarkup_language(_doctype); if (docDesc == null) { info.setMessage( new InfoMessage( "Code for appropriate HTML version not available yet:" + "substituting HTML 3.2")); docDesc = new Html3_2DocDesc(); } docDesc.validate(elements, info); metadata = docDesc.getMetadata(); // Try to get the charset from the meta Content if (metadata.getCharset() != null) { _textMD.setCharset(metadata.getCharset()); } else { _textMD.setCharset(TextMDMetadata.CHARSET_ISO8859_1); } String textMDEncoding = _textMD.getCharset(); if (textMDEncoding.indexOf("UTF") != -1) { _textMD.setByte_order( _bigEndian ? TextMDMetadata.BYTE_ORDER_BIG : TextMDMetadata.BYTE_ORDER_LITTLE); _textMD.setByte_size("8"); _textMD.setCharacter_size("variable"); } else { _textMD.setByte_order( _bigEndian ? TextMDMetadata.BYTE_ORDER_BIG : TextMDMetadata.BYTE_ORDER_LITTLE); _textMD.setByte_size("8"); _textMD.setCharacter_size("1"); } } catch (ParseException e) { Token t = e.currentToken; info.setMessage( new ErrorMessage("Parse error", "Line = " + t.beginLine + ", column = " + t.beginColumn)); info.setWellFormed(false); } catch (TokenMgrError f) { info.setMessage(new ErrorMessage("TokenMgrError: " + f.getLocalizedMessage())); info.setWellFormed(false); } if (info.getWellFormed() == RepInfo.FALSE) { return 0; } if (type != 0) { if (profileNames[type] != null) { info.setProfile(profileNames[type]); } info.setVersion(versionNames[type]); } if (metadata != null) { Property property = metadata.toProperty(_withTextMD ? _textMD : null); if (property != null) { info.setProperty(property); } } if (ckSummer != null) { info.setSize(_cstream.getNBytes()); info.setChecksum(new Checksum(ckSummer.getCRC32(), ChecksumType.CRC32)); String value = ckSummer.getMD5(); if (value != null) { info.setChecksum(new Checksum(value, ChecksumType.MD5)); } if ((value = ckSummer.getSHA1()) != null) { info.setChecksum(new Checksum(value, ChecksumType.SHA1)); } } return 0; }