/** * Created primary key using openssl. * * <p>openssl req -x509 -nodes -days 365 -newkey rsa:1024 -sha1 -subj * '/C=GB/ST=/L=Manchester/CN=www.example.com' -keyout myrsakey.pem -out /tmp/myrsacert.pem * openssl pkcs8 -in myrsakey.pem -topk8 -nocrypt -out myrsakey.pk8 */ private static PrivateKey getPrivateKey() { String str = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMPQ5BCMxlUq2TYy\n" + "iRIoEUsz6HGTJhHuasS2nx1Se4Co3lxwxyubVdFj8AuhHNJSmJvjlpbTsGOjLZpr\n" + "HyDEDdJmf1Fensh1MhUnBZ4a7uLrZrKzFHHJdamX9pxapB89vLeHlCot9hVXdrZH\n" + "nNtg6FdmRKH/8gbs8iDyIayFvzYDAgMBAAECgYA+c9MpTBy9cQsR9BAvkEPjvkx2\n" + "XL4ZnfbDgpNA4Nuu7yzsQrPjPomiXMNkkiAFHH67yVxwAlgRjyuuQlgNNTpKvyQt\n" + "XcHxffnU0820VmE23M+L7jg2TlB3+rUnEDmDvCoyjlwGDR6lNb7t7Fgg2iR+iaov\n" + "0iVzz+l9w0slRlyGsQJBAPWXW2m3NmFgqfDxtw8fsKC2y8o17/cnPjozRGtWb8LQ\n" + "g3VCb8kbOFHOYNGazq3M7+wD1qILF2h/HecgK9eQrZ0CQQDMHXoJMfKKbrFrTKgE\n" + "zyggO1gtuT5OXYeFewMEb5AbDI2FfSc2YP7SHij8iQ2HdukBrbTmi6qxh3HmIR58\n" + "I/AfAkEA0Y9vr0tombsUB8cZv0v5OYoBZvCTbMANtzfb4AOHpiKqqbohDOevLQ7/\n" + "SpvgVCmVaDz2PptcRAyEBZ5MCssneQJAB2pmvaDH7Ambfod5bztLfOhLCtY5EkXJ\n" + "n6rZcDbRaHorRhdG7m3VtDKOUKZ2DF7glkQGV33phKukErVPUzlHBwJAScD9TqaG\n" + "wJ3juUsVtujV23SnH43iMggXT7m82STpPGam1hPfmqu2Z0niePFo927ogQ7H1EMJ\n" + "UHgqXmuvk2X/Ww=="; try { KeyFactory fac = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(DatatypeConverter.parseBase64Binary(str)); return fac.generatePrivate(privKeySpec); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Changes hexadecimal to base 64 * * @param hex the hexadecimal value to convert * @return the base64 value */ public String HexToBase64(String hex) { byte[] byteArray = DatatypeConverter.parseHexBinary(hex); String base64String = DatatypeConverter.printBase64Binary(byteArray); return base64String; }
void loadFromXml(Element rootElement) { // Parse XML file if (StringUtils.equals(rootElement.getLocalName(), "row")) { name = rootElement.getAttribute("ows_LinkFilename"); url = rootElement.getAttribute("ows_FileRef"); if (StringUtils.isNotBlank(rootElement.getAttribute("ows_ID"))) { id = Integer.valueOf(rootElement.getAttribute("ows_ID")); } if (StringUtils.isNotBlank(rootElement.getAttribute("ows__Level"))) { level = Integer.valueOf(rootElement.getAttribute("ows__Level")); } if (StringUtils.isNotBlank(rootElement.getAttribute("ows_Created_x0020_Date"))) { String[] strArray = rootElement.getAttribute("ows_Created_x0020_Date").split(";#"); if (strArray.length > 1) { Calendar calendar = DatatypeConverter.parseDateTime(strArray[1]); created = calendar.getTime(); } } if (StringUtils.isNotBlank(rootElement.getAttribute("ows_Modified"))) { String[] strArray = rootElement.getAttribute("ows_Modified").split(";#"); if (strArray.length > 1) { Calendar calendar = DatatypeConverter.parseDateTime(strArray[1]); modified = calendar.getTime(); } } } }
@SneakyThrows(NoSuchAlgorithmException.class) public DependencyLoader downloadDependencies(DependencySet dependencySet) throws IOException { initDependencyStore(); for (Dependency dependency : dependencySet.getDependencies()) { URL cached = dependencyStore.getCachedDependency(dependency); if (cached == null) { logger.info("Downloading " + dependency.getUrl()); MessageDigest digest = MessageDigest.getInstance("SHA-512"); @SuppressWarnings("resource") ByteArrayOutputStream memoryStream = new ByteArrayOutputStream(); try (InputStream stream = dependency.getUrl().openStream()) { byte[] buf = new byte[4096]; int len; while ((len = stream.read(buf)) >= 0) { digest.update(buf, 0, len); memoryStream.write(buf, 0, len); } } byte[] hash = digest.digest(); if (!Arrays.equals(hash, dependency.getSha512sum())) { throw new IOException( "Mismatched hash on " + dependency.getUrl() + ": expected " + DatatypeConverter.printHexBinary(dependency.getSha512sum()) + " but got " + DatatypeConverter.printHexBinary(hash)); } cached = dependencyStore.saveDependency(dependency, memoryStream.toByteArray()); } urls.add(cached); } logger.info("Added " + dependencySet.getDependencies().size() + " dependencies."); return this; }
// parses a datetime string that adhears to the given pattern and returns a java.util.Date object public static java.util.Calendar parse(String input, String pattern) throws IllegalArgumentException { if (pattern == null) pattern = DEFAULT_DATETIME_PATTERN; java.util.Calendar output = null; if (input != null) { if (pattern.equals("datetime")) { output = javax.xml.bind.DatatypeConverter.parseDateTime(input); } else if (pattern.equals("date")) { output = javax.xml.bind.DatatypeConverter.parseDate(input); } else if (pattern.equals("time")) { output = javax.xml.bind.DatatypeConverter.parseTime(input); } else if (pattern.equals("milliseconds")) { output = java.util.Calendar.getInstance(); output.setTimeInMillis(Long.parseLong(input)); } else { java.text.DateFormat formatter = new java.text.SimpleDateFormat(pattern); formatter.setLenient(false); output = java.util.Calendar.getInstance(); try { output.setTime(formatter.parse(input)); } catch (java.text.ParseException ex) { throw new IllegalArgumentException(tundra.exception.message(ex)); } } } return output; }
/** * Import users * * @param nodes list of users nodes (wrapper node, thus only one) * @return */ private Boolean processUsers(NodeList nodes) { NodeList users = nodes.item(0).getChildNodes(); for (int i = 0; i < users.getLength(); i++) { if (users.item(i).getNodeType() == Node.ELEMENT_NODE) { Element userNode = (Element) users.item(i); User user = new User(); user.setIduser(Integer.parseInt(getTagValue("iduser", userNode))); user.setForename(getTagValue("forename", userNode)); user.setSurname(getTagValue("surname", userNode)); user.setPermitNumber(getTagValue("permitNumber", userNode)); user.setAddress(getTagValue("address", userNode)); user.setEmail(getTagValue("email", userNode)); user.setRegistered( DatatypeConverter.parseDateTime(getTagValue("registered", userNode)).getTime()); user.setExpire(DatatypeConverter.parseDateTime(getTagValue("expire", userNode)).getTime()); user.setPassword(getTagValue("password", userNode)); user.setLevel(getTagValue("level", userNode)); try { userMgr.Save(user); } catch (EJBException ex) { ex.printStackTrace(System.out); } } } return true; }
@Test public void testCborSerialize() throws Exception { CBORAccessRequestMac instance = new CBORAccessRequestMac(this.publisherId, this.ifMapTimestamp); CborBuilder cb = new CborBuilder(); ArrayBuilder ab = cb.addArray(); instance.cborSerialize(ab); ab.end(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); CborEncoder ce = new CborEncoder(bos); ce.encode(cb.build()); log.info("CBOR serialize:"); log.info(DatatypeConverter.printHexBinary(bos.toByteArray())); byte[] expResult = DatatypeConverter.parseHexBinary( "847839687474703A2F2F7777772E74727573746564636F6D707574696E6767726F75702E6F72672F32303130" + "2F49464D41504D455441444154412F32726163636573732D726571756573742D6D6163887269666D61702D7075626C69736865722D69646F6D792D7075626C6973" + "6865722D69646F69666D61702D74696D657374616D70C11A4ED9E8B2781869666D61702D74696D657374616D702D6672616374696F6EC482281A075BCA00716966" + "6D61702D63617264696E616C6974796B73696E676C6556616C756580"); assertTrue(Arrays.equals(expResult, bos.toByteArray())); }
@Test public void test_generate_ARPA() { // NetworkInBytes networkInBytes = IpUtil.parseArpa("f.f.ip6.arpa"); NetworkInBytes networkInBytes = ArpaUtil.parseArpa("1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa"); String hex1 = DatatypeConverter.printHexBinary(networkInBytes.getStartAddress()); // System.err.println("0x" + hex1); String hex2 = DatatypeConverter.printHexBinary(networkInBytes.getEndAddress()); // System.err.println("0x" + hex2); }
public String disassemble8080p(byte[] codeBuffer, int progCounter, int end, boolean hexDump) { int pc = progCounter; String all = ""; while (pc <= end) { byte c = codeBuffer[pc]; OPEntry op = getOPDataFromCode(c); String finalLine = String.format("%04X ", pc); if (op.bytes == 1) finalLine += DatatypeConverter.printHexBinary(new byte[] {codeBuffer[pc]}) + " "; else if (op.bytes == 2) finalLine += DatatypeConverter.printHexBinary(new byte[] {codeBuffer[pc]}) + " " + DatatypeConverter.printHexBinary(new byte[] {codeBuffer[pc + 1]}) + " "; else if (op.bytes == 3) finalLine += DatatypeConverter.printHexBinary(new byte[] {codeBuffer[pc]}) + " " + DatatypeConverter.printHexBinary(new byte[] {codeBuffer[pc + 1]}) + " " + DatatypeConverter.printHexBinary(new byte[] {codeBuffer[pc + 2]}) + " "; finalLine += op.name; if (op.bytes == 2) finalLine += "#0x" + DatatypeConverter.printHexBinary(new byte[] {codeBuffer[pc + 1]}); else if (op.bytes == 3) finalLine += "$" + DatatypeConverter.printHexBinary( new byte[] {codeBuffer[pc + 2], codeBuffer[pc + 1]}); all += finalLine + ((pc + op.bytes <= end || hexDump) ? "\n" : ""); pc += op.bytes; } if (hexDump) { int lines = (int) Math.ceil((end - progCounter) / 0x10); if (lines == 0) lines++; for (int i = 0; i <= lines; i++) { all += String.format("%08X ", progCounter + i * 0x10); for (int j = 0; j < 0x10; j++) all += " " + DatatypeConverter.printHexBinary( new byte[] {codeBuffer[progCounter + i * 0x10 + j]}); all += "\n"; } } return all; }
private static String asString(final Object primitive) { // TODO: improve 'string' conversion; maybe consider only String properties if (primitive instanceof String) { return (String) primitive; } else if (primitive instanceof Calendar) { return DatatypeConverter.printDateTime((Calendar) primitive); } else if (primitive instanceof byte[]) { return DatatypeConverter.printBase64Binary((byte[]) primitive); } else { return primitive.toString(); } }
static void writeAsBase64ToFile(Path filename, int numKeys, int numValuesPerKeys) throws IOException { BufferedWriter bw = Files.newBufferedWriter(filename, Charset.defaultCharset()); for (int i = 0; i < numKeys; ++i) { bw.write(DatatypeConverter.printBase64Binary(makeKey(i))); for (int j = 0; j < numValuesPerKeys; ++j) { bw.append(' ').write(DatatypeConverter.printBase64Binary(makeValue(j))); } bw.newLine(); } bw.close(); }
public void serializeBody( com.sun.identity.saml2.jaxb.assertion.impl.runtime.XMLSerializer context) throws org.xml.sax.SAXException { context.startElement("urn:oasis:names:tc:SAML:2.0:assertion", "AttributeValue"); if (_Nil) { context .getNamespaceContext() .declareNamespace("http://www.w3.org/2001/XMLSchema-instance", null, true); } else { super.serializeURIs(context); } context.endNamespaceDecls(); if (_Nil) { context.startAttribute("http://www.w3.org/2001/XMLSchema-instance", "nil"); try { context.text(javax.xml.bind.DatatypeConverter.printBoolean(((boolean) _Nil)), "Nil"); } catch (java.lang.Exception e) { com.sun.identity.saml2.jaxb.assertion.impl.runtime.Util.handlePrintConversionException( this, e, context); } context.endAttribute(); } else { super.serializeAttributes(context); } context.endAttributes(); if (!_Nil) { super.serializeBody(context); } context.endElement(); }
/** * Constructor. The raw message body will be Base64-encoded because some bytes are unsafe to use * with the IoT Hub HTTPS batch message format. * * @param body the raw message body. * @throws IllegalArgumentException if body is null. * @throws SizeLimitExceededException if body has a size of more than 255 kb. */ public IotHubServiceboundMessage(byte[] body) throws SizeLimitExceededException { // Codes_SRS_IOTHUBSERVICEBOUNDMESSAGE_11_017: [If body is null, the constructor shall throw an // IllegalArgumentException.] if (body == null) { throw new IllegalArgumentException("Message body cannot be 'null'."); } // Codes_SRS_IOTHUBSERVICEBOUNDMESSAGE_11_001: [The constructor shall Base64-encode the // message.] byte[] base64EncodedBody = DatatypeConverter.printBase64Binary(body) .getBytes(IotHubMessage.IOTHUB_MESSAGE_DEFAULT_CHARSET); // Codes_SRS_IOTHUBSERVICEBOUNDMESSAGE_11_007: [If the body length is greater than 255 kb after // Base64-encoding it, the constructor shall throw a SizeLimitExceededException.] if (base64EncodedBody.length > SERVICEBOUND_MESSAGE_MAX_SIZE_BYTES) { String errMsg = String.format( "Service-bound message body " + "cannot exceed %d bytes after being " + "Base64-encoded.\n", SERVICEBOUND_MESSAGE_MAX_SIZE_BYTES); throw new SizeLimitExceededException(errMsg); } // Codes_SRS_IOTHUBSERVICEBOUNDMESSAGE_11_006: [The constructor shall save the content-type as // 'application/octet-stream'.] this.msg = new IotHubMessage(base64EncodedBody); this.base64Encoded = true; }
/** * Import books * * @param nodes * @return */ private Boolean processBooks(NodeList nodes) { NodeList books = nodes.item(0).getChildNodes(); for (int i = 0; i < books.getLength(); i++) { if (books.item(i).getNodeType() == Node.ELEMENT_NODE) { Element bookNode = (Element) books.item(i); Book book = new Book(); book.setIdbook(Integer.parseInt(getTagValue("idbook", bookNode))); book.setCode(getTagValue("code", bookNode)); book.setEdition(Integer.parseInt(getTagValue("edition", bookNode))); book.setPages(Integer.parseInt(getTagValue("pages", bookNode))); book.setPlace(getTagValue("place", bookNode)); book.setYear(DatatypeConverter.parseDateTime(getTagValue("year", bookNode)).getTime()); book.setType(getTagValue("type", bookNode)); book.setName(getTagValue("name", bookNode)); // find and set publisher Publisher publisher = publisherMgr.findByIdpublisher(Integer.parseInt(getTagValue("publisher", bookNode))); if (publisher == null) { continue; } book.setPublisher(publisher); // find and set genre Genre genre = genreMgr.findByIdgenre(Integer.parseInt(getTagValue("genre", bookNode))); if (genre == null) { continue; } book.setGenre(genre); // setup book authors List<String> authors = getTagsValues("authorCollection", bookNode); if (book.getAuthorCollection() == null) { book.setAuthorCollection(new ArrayList<Author>()); } for (String authorId : authors) { Author author = authorMgr.findByIdauthor(Integer.parseInt(authorId)); if (author != null) { // book.getAuthorCollection().add(author); author.getBooksCollection().add(book); authorMgr.save(author); } } try { bookMgr.save(book); } catch (EJBException ex) { ex.printStackTrace(System.out); } } } return true; }
/** * Returns the contents of an attachment * * @param assetId The ID of the asset owning the attachment * @param attachmentId The ID of the attachment * @return The input stream for the attachment * @throws IOException * @throws RequestFailureException */ public InputStream getAttachment(String assetId, String attachmentId) throws IOException, BadVersionException, RequestFailureException { // Get the URL for the attachment Attachment attachment = getAttachmentMetaData(assetId, attachmentId); // accept license for type CONTENT HttpURLConnection connection; if (attachment.getType() == Attachment.Type.CONTENT) { connection = createHttpURLConnection(attachment.getUrl() + "?license=agree"); } else { connection = createHttpURLConnection(attachment.getUrl()); } // If the attachment was a link and we have a basic auth userid + password specified // we are attempting to access the files staged from a protected site so authorise for it if (attachment.getLinkType() == LinkType.DIRECT) { if ((loginInfo.getAttachmentBasicAuthUserId() != null) && (loginInfo.getAttachmentBasicAuthPassword() != null)) { String userpass = loginInfo.getAttachmentBasicAuthUserId() + ":" + loginInfo.getAttachmentBasicAuthPassword(); String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary( userpass.getBytes(Charset.forName("UTF-8"))); connection.setRequestProperty("Authorization", basicAuth); } } connection.setRequestMethod("GET"); testResponseCode(connection); return connection.getInputStream(); }
public static void main(String[] args) throws IOException { File file = new File( "/var/folders/ty/d50nfg8x1vvg04kcvl9yclqm0000gn/T/clasebase64-3618308815743157502.txt"); FileInputStream fis = new FileInputStream(file); // fis sería mi fuente de datos. Un archivo, la red, etc… // fis está cifrado InputStreamReader isr = new InputStreamReader(fis); BufferedReader in = new BufferedReader(isr); ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream out = new BufferedOutputStream(baos); char[] buffer = new char[4]; // Uso un mútiplo de 4 int read = 0; while ((read = in.read(buffer)) >= 0) { char[] readchars = Arrays.copyOfRange(buffer, 0, read); String base64 = new String(readchars); byte[] bytes = DatatypeConverter.parseBase64Binary(base64); out.write(bytes); } in.close(); out.close(); String parsedString = new String(baos.toByteArray()); System.out.println("Leído: " + parsedString); }
public LocationInfo(String parse, String text) throws IllegalArgumentException { this.base64 = parse; this.text = text; try { String[] args = new String(DatatypeConverter.parseBase64Binary(parse), "UTF-8").split("&"); for (String s : args) { String[] data = s.split("="); if (data[0].equalsIgnoreCase("cp")) { String[] coords = data[1].split("~"); latitude = Double.parseDouble(coords[0]); longitude = Double.parseDouble(coords[1]); } else if (data[0].equalsIgnoreCase("lvl")) { zoomLevel = Integer.parseInt(data[1]); } else if (data[0].equalsIgnoreCase("sty")) { sty = data[1]; } else if (data[0].equalsIgnoreCase("ss")) { ss = data[1]; } else { throw new IllegalArgumentException("Unknown argument type " + data[0]); } } if (Double.isNaN(latitude) || Double.isNaN(longitude) || zoomLevel == -1 || sty == null || ss == null) { throw new IllegalArgumentException("Missing certain parameters in args"); } } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("UTF-8 is not supported by your Java installation"); } }
@Override protected Object parseDate(String value, boolean richDate) { return (richDate ? new TimestampWritable( new Timestamp(DatatypeConverter.parseDateTime(value).getTimeInMillis())) : parseString(value)); }
/** * Decompress a compressed event string. * * @param str Compressed string * @return Decompressed string */ private String decompress(String str) { ByteArrayInputStream byteInputStream = null; GZIPInputStream gzipInputStream = null; BufferedReader br = null; try { byteInputStream = new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(str)); gzipInputStream = new GZIPInputStream(byteInputStream); br = new BufferedReader(new InputStreamReader(gzipInputStream, CharEncoding.UTF_8)); StringBuilder jsonStringBuilder = new StringBuilder(); String line; while ((line = br.readLine()) != null) { jsonStringBuilder.append(line); } return jsonStringBuilder.toString(); } catch (IOException e) { throw new RuntimeException( "Error occured while decompressing events string: " + e.getMessage(), e); } finally { try { if (byteInputStream != null) { byteInputStream.close(); } if (gzipInputStream != null) { gzipInputStream.close(); } if (br != null) { br.close(); } } catch (IOException e) { log.error("Error occured while closing streams: " + e.getMessage(), e); } } }
@Override @NotNull(message = "input stream is never NULL") public InputStream raw() throws IOException { return new ByteArrayInputStream( DatatypeConverter.parseBase64Binary( this.storage.xml().xpath(String.format("%s/content/text()", this.xpath())).get(0))); }
public void serializeBody( mx.com.prudential.lps.core.parsers.command.jaxb.impl.runtime.XMLSerializer context) throws org.xml.sax.SAXException { context.startElement("", "field_mapping"); if (_Nil) { context .getNamespaceContext() .declareNamespace("http://www.w3.org/2001/XMLSchema-instance", null, true); } else { super.serializeURIs(context); } context.endNamespaceDecls(); if (_Nil) { context.startAttribute("http://www.w3.org/2001/XMLSchema-instance", "nil"); try { context.text(javax.xml.bind.DatatypeConverter.printBoolean(((boolean) _Nil)), "Nil"); } catch (java.lang.Exception e) { mx.com.prudential.lps.core.parsers.command.jaxb.impl.runtime.Util .handlePrintConversionException(this, e, context); } context.endAttribute(); } else { super.serializeAttributes(context); } context.endAttributes(); if (!_Nil) { super.serializeBody(context); } context.endElement(); }
public static void main(String[] args) { try { String s = "H4sIAAAAAAAAANVYy46jOBT9F9aM5BcGZzdSb6bV8wWtCDngUFbxEpi0qkv172MbzCNJJZCe6ppRbcpg7rm2z7n3OK9e14rmry8x9HaYBAHw7YP4IMrkydt9f/XUSy3ihKeN8Hb6bcoLnvX/PvE2rnP+IlJvd+R5K/RbkXHVxrI85jITrZ3W1lXZVo0evHoyjcuq8HYeQaHn66G3C30LoZ+NE33vJJpWVqV+CHFIcUQwgvpxm3eZflbLhivhvfneIa+S5xHdhEMhoIwB5ntZXkmTNPS9Y9Uk4u9O5bLOX2xSCa95IpVJUa/xxHPRNXoHzPrLQ5920shaxeJ4FGpIPRX9wz4zygK7hGFFlNFhRQgi34TshI2o0+SJkifef/cd+GD/5k+gmzAjtsQEDtOseMC8Bon2b3vfa8QP3qR/pmm/BzlvW7E8FgyHgBCO5zLMW55KFDCGKAmmU0mq4sCV4qUyJ6ND5rJVstSvCAw0Nk/OsAhxyZMRy846O/8IsgBFYELKqlwUBsSeq2abVCZhvSSeK9HYVRu66RnVj9LQeyR3KU+CdxpyhgExgzpFRJEjjQs5bTUL4aAMk/AQLGt4OiPYkIPS51oqQ6z9eAyjRMzB//8Upf+ixxQFwQZ2E0rm7CY0GMkIRnbriJf0hgtF4fWQDKA5JAPYcRKHk4jPAeFaNbloEN9Wk+G4FtOM4wVveJea5ZyLCeCrYmIucbZNTGVVFlWjLuSEg1+TE2DwhpxIsEZOJodPk5MjX7BOToBOe/pT5je6U0joY91pg5QCtGhOurg5JpJJSvhub9qgJBhQPIfUY1ffMUXva2lDb/oANWFIr6oJOTWhbWoS+VGW4kJM6OHeRAAika5/+H0xUYrXiAnd7U1737lBZOMQnUlV1y6sG2rldL3AWsWT51g1PWvrU20BzZw2qQY92sSmT+ywbkWXVnq7vvKD2dNpTlxXreyZ8YdxILIQ1pf1UcfvUt48F7xE9ozHnM4+tlGLKhXxUWZP/Z6db5MdT8nGSZFauiQqefrGO2OCe4CPN8QfVG9ISMMH3fCGegOd/XXq12VuWA+BtyvOsndvMgwIoYVj0GO3i3RmiK9aBvQLsGC5WD12iw1mpe4qLPjEYsfA1VrntgwFG214JwqRS3VZ7ui9cmdKiSt3+LLcIULeL3f2NjHXsQl2We7oZ1px1/nIKi0jxuZ+7OctLUfgIS2TLfzW9m3ZygkcWzmcbDF5h98zWSG0AZYBsPTi7i6KMB1BdcRz0NX+wTV1iLZLKhPnaqLR71FTdM+Iz8V0acRJFN2412JGVogp+kwf/oE/FIXh5Ks2yQn9yzdM9N+6YaLfcsNEW4gNr90wo1s3zDXEtjncNcXG/819JHj7BxBKbvA3FQAA"; byte[] sBytes = DatatypeConverter.parseBase64Binary(s); String test = "123"; InputStream in = new ByteArrayInputStream(test.getBytes()); ByteArrayOutputStream result = new ByteArrayOutputStream(); OutputStream out = new DeflaterOutputStream(result); doCopy(in, out); for (int i = 0; i < sBytes.length; i++) { for (int j = 1; i + j <= sBytes.length; j++) { try { in = new GZIPInputStream(new ByteArrayInputStream(sBytes, i, j)); result = new ByteArrayOutputStream(); doCopy(in, result); System.out.println(i + " " + j + " " + new String(result.toByteArray())); } catch (Exception e) { } } } // byte[] bytes = result.toByteArray(); // in = new InflaterInputStream(new ByteArrayInputStream(sBytes)); // result = new ByteArrayOutputStream(); // doCopy(in, result); // // String s1 = new String(result.toByteArray()); // String s2 = ""; } catch (Exception e) { e.printStackTrace(); } }
public void setModified(Date modified) { Calendar cal = Calendar.getInstance(); cal.setTime(modified); String date = DatatypeConverter.printDateTime(cal); res.addProperty( DCTerms.modified, model.createTypedLiteral(date, JenaOREConstants.dateTypedLiteral)); }
public void recognizeFromFileExplicit() throws Exception { File pcmFile = new File(testFileName); HttpURLConnection conn = (HttpURLConnection) new URL(serverURL).openConnection(); // construct params JSONObject params = new JSONObject(); params.put("format", "wav"); params.put("rate", 16000); params.put("channel", "1"); params.put("token", token); params.put("cuid", cuid); params.put("len", pcmFile.length()); params.put("speech", DatatypeConverter.printBase64Binary(loadFile(pcmFile))); // add request header conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setDoInput(true); conn.setDoOutput(true); // send request DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(params.toString()); wr.flush(); wr.close(); printResponse(conn); }
@BeforeClass(alwaysRun = true) public void init() throws Exception { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(springSecurity()).build(); testUser = new SpringUser( 3L, "*****@*****.**", "Test", "User", "testuser", "testuser", "es", getGrantedAuthorities(), true, true, true, true); token = new TokenHandler( DatatypeConverter.parseBase64Binary( "9SyECk96oDsTmXfogIfgdjhdsgvagHJLKNLvfdsfR8cbXTvoPjX+Pq/T/b1PqpHX0lYm0oCBjXWICA==")) .createTokenForUser(testUser); }
private static String getEncodedHistogram(Histogram combined) { ByteBuffer targetBuffer = ByteBuffer.allocate(combined.getNeededByteBufferCapacity()); int compressedLength = combined.encodeIntoCompressedByteBuffer(targetBuffer, Deflater.BEST_COMPRESSION); byte[] compressedArray = Arrays.copyOf(targetBuffer.array(), compressedLength); return DatatypeConverter.printBase64Binary(compressedArray); }
/** * Import book exemplars * * @param nodes * @return */ private Boolean processExemplars(NodeList nodes) { NodeList exemplars = nodes.item(0).getChildNodes(); for (int i = 0; i < exemplars.getLength(); i++) { if (exemplars.item(i).getNodeType() == Node.ELEMENT_NODE) { Element exemplarNode = (Element) exemplars.item(i); Exemplar exemplar = new Exemplar(); exemplar.setIdexemplar(Integer.parseInt(getTagValue("idexemplar", exemplarNode))); exemplar.setAquired( DatatypeConverter.parseDateTime(getTagValue("aquired", exemplarNode)).getTime()); exemplar.setState(Integer.parseInt(getTagValue("state", exemplarNode))); Book book = bookMgr.findByIdbook(Integer.parseInt(getTagValue("book", exemplarNode))); if (book == null) { continue; } exemplar.setBook(book); try { exemplarMgr.save(exemplar); } catch (EJBException ex) { ex.printStackTrace(System.out); } } } return true; }
/** Generates secret key. Initializes MAC(s). */ private void setupKeyAndMac() { /* * Lets see if an encoded key was given to the application, if so use * it and skip the code to generate it. */ try { InitialContext context = new InitialContext(); String encodedKeyArray = (String) context.lookup("java:comp/env/jsf/ClientSideSecretKey"); byte[] keyArray = DatatypeConverter.parseBase64Binary(encodedKeyArray); sk = new SecretKeySpec(keyArray, KEY_ALGORITHM); } catch (NamingException exception) { if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.log(Level.FINEST, "Unable to find the encoded key.", exception); } } if (sk == null) { try { KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM); kg.init(KEY_LENGTH); // 256 if you're using the Unlimited Policy Files sk = kg.generateKey(); // System.out.print("SecretKey: " + // DatatypeConverter.printBase64Binary(sk.getEncoded())); } catch (Exception e) { throw new FacesException(e); } } }
public void serializeAttributes( com.sun.identity.federation.jaxb.entityconfig.impl.runtime.XMLSerializer context) throws org.xml.sax.SAXException { if (_Id != null) { context.startAttribute("", "id"); try { context.text(context.onID(this, ((java.lang.String) _Id)), "Id"); } catch (java.lang.Exception e) { com.sun.identity.federation.jaxb.entityconfig.impl.runtime.Util .handlePrintConversionException(this, e, context); } context.endAttribute(); } context.startAttribute("", "maxProcessingTime"); try { context.text( javax.xml.bind.DatatypeConverter.printInteger( ((java.math.BigInteger) _MaxProcessingTime)), "MaxProcessingTime"); } catch (java.lang.Exception e) { com.sun.identity.federation.jaxb.entityconfig.impl.runtime.Util .handlePrintConversionException(this, e, context); } context.endAttribute(); if (_Actor != null) { context.startAttribute("http://schemas.xmlsoap.org/soap/envelope/", "actor"); try { context.text(((java.lang.String) _Actor), "Actor"); } catch (java.lang.Exception e) { com.sun.identity.federation.jaxb.entityconfig.impl.runtime.Util .handlePrintConversionException(this, e, context); } context.endAttribute(); } if (has_MustUnderstand) { context.startAttribute("http://schemas.xmlsoap.org/soap/envelope/", "mustUnderstand"); try { context.text( javax.xml.bind.DatatypeConverter.printBoolean(((boolean) _MustUnderstand)), "MustUnderstand"); } catch (java.lang.Exception e) { com.sun.identity.federation.jaxb.entityconfig.impl.runtime.Util .handlePrintConversionException(this, e, context); } context.endAttribute(); } }
/** * Import borrows * * @param nodes * @return */ public Boolean processBorrows(NodeList nodes) { NodeList borrows = nodes.item(0).getChildNodes(); for (int i = 0; i < borrows.getLength(); i++) { if (borrows.item(i).getNodeType() == Node.ELEMENT_NODE) { Element borrowNode = (Element) borrows.item(i); Borrow borrow = new Borrow(); borrow.setIdborrow(Integer.parseInt(getTagValue("idborrow", borrowNode))); borrow.setProlongations(Integer.parseInt(getTagValue("prolongations", borrowNode))); borrow.setBorrowed( DatatypeConverter.parseDateTime(getTagValue("borrowed", borrowNode)).getTime()); // set returned date (can be null) try { if (getTagValue("returned", borrowNode) != null) { borrow.setReturned( DatatypeConverter.parseDateTime(getTagValue("returned", borrowNode)).getTime()); } } catch (NullPointerException e) { } User user = userMgr.findByIduser(Integer.parseInt(getTagValue("user", borrowNode))); if (user == null) { continue; } borrow.setUser(user); Exemplar exemplar = exemplarMgr.findByIdexemplar(Integer.parseInt(getTagValue("exemplar", borrowNode))); if (exemplar == null) { continue; } borrow.setExemplar(exemplar); try { borrowMgr.Save(borrow); } catch (EJBException ex) { ex.printStackTrace(System.out); } } } return true; }