List of usage examples for javax.xml.bind DatatypeConverter parseHexBinary
public static byte[] parseHexBinary(String lexicalXSDHexBinary)
Converts the string argument into an array of bytes.
From source file:HttpClientJniTest.java
@Test public void testSendFile() throws Exception { long handle = 0; File dir = null;//from w ww . j a v a 2 s. c o m try { dir = Files.createTempDir(); File file = new File(dir, "test.txt"); FileUtils.writeStringToFile(file, STATIC_FILE_DATA); String sout = wiltoncall("server_create", GSON.toJson( ImmutableMap.builder().put("views", TestGateway.views()).put("tcpPort", TCP_PORT).build())); Map<String, Long> shamap = GSON.fromJson(sout, LONG_MAP_TYPE); handle = shamap.get("serverHandle"); assertTrue(file.exists()); String resp = wiltoncall("httpclient_send_file", GSON.toJson(ImmutableMap.builder().put("url", ROOT_URL + "postmirror") .put("filePath", file.getAbsolutePath()).put("remove", true) .put("metadata", ImmutableMap.builder().put("forceHttp10", true).build()).build())); Map<String, Object> map = GSON.fromJson(resp, MAP_TYPE); byte[] bytes = DatatypeConverter.parseHexBinary((String) map.get("dataHex")); assertEquals(STATIC_FILE_DATA, new String(bytes, "UTF-8")); // not stable on windows // Thread.sleep(200); // assertFalse(file.exists()); } finally { wiltoncall("server_stop", GSON.toJson(ImmutableMap.builder().put("serverHandle", handle).build())); deleteDirQuietly(dir); } }
From source file:fi.okm.mpass.shibboleth.authn.impl.BaseInitializeWilmaContextTest.java
/** * Validates the checksum of the given url. * @param url The source for the checksum validation. * @param checksum The checksum./*w w w . j a v a 2 s.com*/ * @return true if valid, false otherwise. * @throws Exception */ protected boolean validateChecksum(final String url, final String checksum) throws Exception { SecretKey macKey = new SecretKeySpec(sharedSecret.getBytes("UTF-8"), WilmaAuthenticationContext.MAC_ALGORITHM); Mac mac = Mac.getInstance(WilmaAuthenticationContext.MAC_ALGORITHM); mac.init(macKey); byte[] digest = mac.doFinal(url.getBytes("UTF-8")); return Arrays.equals(DatatypeConverter.parseHexBinary(checksum), digest); }
From source file:de.decoit.simu.cbor.ifmap.identifier.CBORMacAddress.java
/** * Parse the string representation of a MAC address into a byte array. * * @param value String representation of MAC address * @return Raw bytes of MAC address// w w w. ja va 2s .c o m */ private byte[] processStringRepresentation(String value) { if (StringUtils.isBlank(value)) { throw new IllegalArgumentException("Value string may not be blank"); } // Remove seprators and leading and trailing whitespaces String strippedAddress; if (value.contains("-")) { strippedAddress = StringUtils.replace(value, "-", ""); } else if (value.contains(":")) { strippedAddress = StringUtils.replace(value, ":", ""); } else if (value.contains(".")) { strippedAddress = StringUtils.replace(value, ".", ""); } else { strippedAddress = value; } byte[] address = DatatypeConverter.parseHexBinary(strippedAddress); if (address.length != 6) { throw new IllegalArgumentException("Invalid number of bytes for MAC address: " + address.length); } return address; }
From source file:gov.ca.cwds.rest.util.jni.CmsPKCompressor.java
/** * Convenience method. Decompress (inflate) a hexadecimal string of a PK-compressed archive. * //from w ww .j a v a2s. co m * @param hex base64-encoded, PK-compressed archive * @return raw byte array of decompressed document * @throws IOException If an I/O error occurs */ public byte[] decompressHex(String hex) throws IOException { if (StringUtils.isBlank(hex)) { throw new IOException("REQUIRED: hex to decompress cannot be null"); } final byte[] bytes = decompressBytes(DatatypeConverter.parseHexBinary(hex.trim())); LOGGER.debug("CmsPKCompressor.decompressHex(String): bytes len={}", bytes.length); return bytes; }
From source file:fi.okm.mpass.shibboleth.authn.impl.ValidateWilmaResponse.java
/** {@inheritDoc} */ @Override// w w w.ja v a 2 s. co m protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final AuthenticationContext authenticationContext) { final HttpServletRequest servletRequest = getHttpServletRequest(); final WilmaAuthenticationContext wilmaContext = authenticationContext .getSubcontext(WilmaAuthenticationContext.class, false); final String nonce = wilmaContext.getNonce(); if (!getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_NONCE).equals(nonce)) { log.warn("{}: Invalid nonce in the incoming Wilma response!", getLogPrefix()); log.debug("{} vs {}", nonce, getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_NONCE)); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } final String checksum = getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_CHECKSUM); final String query = servletRequest.getQueryString().substring(0, servletRequest.getQueryString() .indexOf("&" + WilmaAuthenticationContext.PARAM_NAME_CHECKSUM + "=")); final String url = servletRequest.getRequestURL().append("?").append(query).toString(); try { final Mac mac = Mac.getInstance(algorithm); mac.init(macKey); byte[] digest = mac.doFinal(url.getBytes("UTF-8")); if (!Arrays.equals(DatatypeConverter.parseHexBinary(checksum), digest)) { log.warn("{}: The checksum validation failed for user {}", getLogPrefix(), getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_USER_ID)); log.trace("{} (params) vs {}", checksum, new String(Hex.encodeHex(digest))); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException | UnsupportedEncodingException | IllegalArgumentException e) { log.error("{}: Could not verify the checksum {}", getLogPrefix(), checksum, e); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } log.trace("{}: Building authentication result for user {}", getLogPrefix(), getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_USER_ID)); buildAuthenticationResult(profileRequestContext, authenticationContext); }
From source file:HttpClientJniTest.java
@Test public void testHttps() throws Exception { long handle = 0; try {/*from w w w .j ava2 s. c om*/ String sout = wiltoncall("server_create", GSON.toJson(ImmutableMap.builder() .put("views", TestGateway.views()).put("tcpPort", TCP_PORT_HTTPS) .put("ssl", ImmutableMap.builder() .put("keyFile", "src/test/resources/certificates/server/localhost.pem") .put("keyPassword", "test") .put("verifyFile", "src/test/resources/certificates/server/staticlibs_test_ca.cer") .put("verifySubjectSubstr", "CN=testclient").build()) .build())); Map<String, Long> shamap = GSON.fromJson(sout, LONG_MAP_TYPE); handle = shamap.get("serverHandle"); String resp = wiltoncall("httpclient_send_request", GSON.toJson(ImmutableMap.builder().put("url", ROOT_URL_HTTPS + "hello") .put("metadata", ImmutableMap.builder().put("forceHttp10", true) .put("sslcertFilename", "src/test/resources/certificates/client/testclient.cer") .put("sslcertype", "PEM") .put("sslkeyFilename", "src/test/resources/certificates/client/testclient.key") .put("sslKeyType", "PEM").put("sslKeypasswd", "test").put("sslVerifyhost", true) .put("sslVerifypeer", true) .put("cainfoFilename", "src/test/resources/certificates/client/staticlibs_test_ca.cer") .build()) .build())); Map<String, Object> map = GSON.fromJson(resp, MAP_TYPE); byte[] bytes = DatatypeConverter.parseHexBinary((String) map.get("dataHex")); assertEquals(HELLO_RESP, new String(bytes, "UTF-8")); } finally { wiltoncall("server_stop", GSON.toJson(ImmutableMap.builder().put("serverHandle", handle).build())); } }
From source file:de.csdev.ebus.utils.EBusUtils.java
/** * Converts a hex string to byte array// w w w.j a v a2 s . c o m * * @param hexDumpString * @return */ static public byte[] toByteArray(String hexDumpString) { if (StringUtils.isEmpty(hexDumpString)) { return new byte[0]; } return DatatypeConverter.parseHexBinary(hexDumpString.replaceAll(" ", "")); }
From source file:AIR.Common.DB.AbstractDLL.java
protected void executePreparedStatementBatch(SQLConnection connection, String query, List<Map<Integer, Object>> paramsList) throws ReturnStatusException { PreparedStatement prepStmt = null; try {//w w w.j av a 2s . c om boolean preexistingAutoCommitMode = connection.getAutoCommit(); connection.setAutoCommit(false); prepStmt = connection.prepareStatement(query); if (paramsList != null) { for (Map<Integer, Object> params : paramsList) { Iterator<Entry<Integer, Object>> param = params.entrySet().iterator(); while (param.hasNext()) { Entry<Integer, Object> entry = param.next(); if (entry.getValue() instanceof String) { prepStmt.setString(entry.getKey(), entry.getValue().toString()); } else if (entry.getValue() instanceof Integer) { prepStmt.setInt(entry.getKey(), (Integer) entry.getValue()); } else if (entry.getValue() instanceof Date) { prepStmt.setString(entry.getKey(), String.format("%s", AbstractDateUtilDll .getDateAsFormattedMillisecondsString((Date) entry.getValue()))); } else if (entry.getValue() instanceof UUID) { String newStr = entry.getValue().toString().replaceAll("-", ""); prepStmt.setBytes(entry.getKey(), DatatypeConverter.parseHexBinary(newStr)); } else if (entry.getValue() instanceof Boolean) { prepStmt.setBoolean(entry.getKey(), (Boolean) entry.getValue()); } } prepStmt.addBatch(); } } prepStmt.executeBatch(); prepStmt.close(); connection.commit(); // reset autocommit. connection.setAutoCommit(preexistingAutoCommitMode); } catch (SQLException exp) { throw new ReturnStatusException(exp); } finally { if (prepStmt != null) try { prepStmt.close(); } catch (SQLException e) { } } }
From source file:com.axelor.apps.account.service.payment.PayboxService.java
/** * Fonction calculant la signature HMAC des paramtres * @param data//from w ww. ja v a2 s . co m * La chaine contenant les paramtres * @param hmacKey * La cl HMAC * @param algorithm * L'algorithme utilis (SHA512, ...) * @return * @throws AxelorException */ public String getHmacSignature(String data, String hmacKey, String algorithm) throws AxelorException { try { byte[] bytesKey = DatatypeConverter.parseHexBinary(hmacKey); SecretKeySpec secretKey = new SecretKeySpec(bytesKey, "Hmac" + algorithm); Mac mac = Mac.getInstance("Hmac" + algorithm); mac.init(secretKey); byte[] macData = mac.doFinal(data.getBytes(this.CHARSET)); // final byte[] hex = new Hex().encode( macData ); // return new String( hex, this.CHARSET ); // LOG.debug("Message HMAC 2 : {}",new String( hex, this.CHARSET )); String s = StringTool.getHexString(macData); return s.toUpperCase(); } catch (InvalidKeyException e) { throw new AxelorException(String.format("%s :\n %s", GeneralServiceImpl.EXCEPTION, e), IException.INCONSISTENCY); } catch (NoSuchAlgorithmException e) { throw new AxelorException(String.format("%s :\n %s", GeneralServiceImpl.EXCEPTION, e), IException.INCONSISTENCY); } catch (UnsupportedEncodingException e) { throw new AxelorException(String.format("%s :\n %s", GeneralServiceImpl.EXCEPTION, e), IException.INCONSISTENCY); } }
From source file:com.marklogic.client.test.EvalTest.java
private void runAndTestXQuery(ServerEvaluationCall call) throws JsonProcessingException, IOException, SAXException, ParserConfigurationException, DatatypeConfigurationException { Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(this.getClass().getClassLoader().getResourceAsStream("1-empty-1.0.xml")); call = call.addNamespace("myPrefix", "http://marklogic.com/test").addVariable("myPrefix:myString", "Mars") .addVariable("myArray", new JacksonHandle().with(new ObjectMapper().createArrayNode().add("item1").add("item2"))) .addVariable("myObject", new JacksonHandle().with(new ObjectMapper().createObjectNode().put("item1", "value1"))) .addVariable("myAnyUri", "http://marklogic.com/a") .addVariable("myBinary", DatatypeConverter.printHexBinary(",".getBytes())) .addVariable("myBase64Binary", DatatypeConverter.printBase64Binary(new byte[] { 1, 2, 3 })) .addVariable("myHexBinary", DatatypeConverter.printHexBinary(new byte[] { 1, 2, 3 })) .addVariable("myDuration", "P100D").addVariable("myDocument", new DOMHandle(document)) .addVariable("myQName", "myPrefix:a") //.addVariable("myAttribute", "<a a=\"a\"/>") .addVariable("myComment", "<!--a-->").addVariable("myElement", "<a a=\"a\"/>") .addVariable("myProcessingInstruction", "<?a?>") .addVariable("myText", new StringHandle("a").withFormat(Format.TEXT)) // the next three use built-in methods of ServerEvaluationCall .addVariable("myBool", true).addVariable("myInteger", 1234567890123456789l) .addVariable("myBigInteger", "123456789012345678901234567890") .addVariable("myDecimal", "1111111111111111111.9999999999") .addVariable("myDouble", 11111111111111111111.7777777777).addVariable("myFloat", 1.1) .addVariable("myGDay", "---01").addVariable("myGMonth", "--01") .addVariable("myGMonthDay", "--01-01").addVariable("myGYear", "1901") .addVariable("myGYearMonth", "1901-01").addVariable("myDate", "2014-09-01") .addVariable("myDateTime", DatatypeFactory.newInstance().newXMLGregorianCalendar(septFirst).toString()) .addVariable("myTime", "00:01:01"); EvalResultIterator results = call.eval(); try {//from w w w . j a v a 2 s. c o m EvalResult result = results.next(); assertEquals("myString should = 'Mars'", "Mars", result.getAs(String.class)); assertEquals("myString should be Type.STRING", EvalResult.Type.STRING, result.getType()); assertEquals("myString should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myArray should = [\"item1\",\"item2\"]", new ObjectMapper().readTree("[\"item1\",\"item2\"]"), result.getAs(JsonNode.class)); assertEquals("myArray should be Type.JSON", EvalResult.Type.JSON, result.getType()); assertEquals("myArray should be Format.JSON", Format.JSON, result.getFormat()); result = results.next(); assertEquals("myObject should = {\"item1\":\"value1\"}", new ObjectMapper().readTree("{\"item1\":\"value1\"}"), result.getAs(JsonNode.class)); assertEquals("myObject should be Type.JSON", EvalResult.Type.JSON, result.getType()); assertEquals("myObject should be Format.JSON", Format.JSON, result.getFormat()); result = results.next(); assertEquals("myAnyUri looks wrong", "http://marklogic.com/a", result.getString()); assertEquals("myAnyUri should be Type.ANYURI", EvalResult.Type.ANYURI, result.getType()); assertEquals("myAnyUri should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myBinary looks wrong", ",", result.getString()); assertEquals("myBinary should be Type.BINARY", EvalResult.Type.BINARY, result.getType()); assertEquals("myBinary should be Format.UNKNOWN", Format.UNKNOWN, result.getFormat()); result = results.next(); assertArrayEquals("myBase64Binary should = 1, 2, 3", new byte[] { 1, 2, 3 }, DatatypeConverter.parseBase64Binary(result.getString())); assertEquals("myBase64Binary should be Type.BASE64BINARY", EvalResult.Type.BASE64BINARY, result.getType()); assertEquals("myBase64Binary should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertArrayEquals("myHexBinary should = 1, 2, 3", new byte[] { 1, 2, 3 }, DatatypeConverter.parseHexBinary(result.getString())); assertEquals("myHexBinary should be Type.HEXBINARY", EvalResult.Type.HEXBINARY, result.getType()); assertEquals("myHexBinary should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myDuration should = P100D", "P100D", result.getString()); assertEquals("myDuration should be Type.DURATION", EvalResult.Type.DURATION, result.getType()); assertEquals("myDuration should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myQName doesn't look right", "myPrefix:a", result.getString()); assertEquals("myQName should be Type.QNAME", EvalResult.Type.QNAME, result.getType()); assertEquals("myQName should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myDocument doesn't look right", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<search:options xmlns:search=\"http://marklogic.com/appservices/search\"/>", result.getString()); assertEquals("myDocument should be Type.XML", EvalResult.Type.XML, result.getType()); assertEquals("myDocument should be Format.XML", Format.XML, result.getFormat()); result = results.next(); assertEquals("myAttribute looks wrong", "a", result.getString()); assertEquals("myAttribute should be Type.ATTRIBUTE", EvalResult.Type.ATTRIBUTE, result.getType()); assertEquals("myAttribute should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myComment should = <!--a-->", "<!--a-->", result.getString()); assertEquals("myComment should be Type.COMMENT", EvalResult.Type.COMMENT, result.getType()); assertEquals("myComment should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myElement looks wrong", "<a a=\"a\"/>", result.getString()); assertEquals("myElement should be Type.XML", EvalResult.Type.XML, result.getType()); assertEquals("myElement should be Format.XML", Format.XML, result.getFormat()); result = results.next(); assertEquals("myProcessingInstruction should = <?a?>", "<?a?>", result.getString()); assertEquals("myProcessingInstruction should be Type.PROCESSINGINSTRUCTION", EvalResult.Type.PROCESSINGINSTRUCTION, result.getType()); assertEquals("myProcessingInstruction should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myText should = a", "a", result.getString()); assertEquals("myText should be Type.TEXTNODE", EvalResult.Type.TEXTNODE, result.getType()); assertEquals("myText should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myBool should = true", true, result.getBoolean()); assertEquals("myBool should be Type.BOOLEAN", EvalResult.Type.BOOLEAN, result.getType()); assertEquals("myBool should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myInteger should = 1234567890123456789l", 1234567890123456789l, result.getNumber().longValue()); assertEquals("myInteger should be Type.INTEGER", EvalResult.Type.INTEGER, result.getType()); assertEquals("myInteger should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myBigInteger looks wrong", new BigInteger("123456789012345678901234567890"), new BigInteger(result.getString())); assertEquals("myBigInteger should be Type.STRING", EvalResult.Type.STRING, result.getType()); assertEquals("myBigInteger should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myDecimal looks wrong", 1111111111111111111.9, result.getNumber().doubleValue(), .001); assertEquals("myDecimal should be Type.DECIMAL", EvalResult.Type.DECIMAL, result.getType()); assertEquals("myDecimal should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myDouble looks wrong", 1.11111111111111E19, result.getNumber().doubleValue(), .001); assertEquals("myDouble should be Type.DOUBLE", EvalResult.Type.DOUBLE, result.getType()); assertEquals("myDouble should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myFloat looks wrong", 1.1, result.getNumber().floatValue(), .001); assertEquals("myFloat should be Type.FLOAT", EvalResult.Type.FLOAT, result.getType()); assertEquals("myFloat should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myGDay looks wrong", "---01", result.getString()); assertEquals("myGDay should be Type.GDAY", EvalResult.Type.GDAY, result.getType()); assertEquals("myGDay should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myGMonth looks wrong", "--01", result.getString()); assertEquals("myGMonth should be Type.GMONTH", EvalResult.Type.GMONTH, result.getType()); assertEquals("myGMonth should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myGMonthDay looks wrong", "--01-01", result.getString()); assertEquals("myGMonthDay should be Type.GMONTHDAY", EvalResult.Type.GMONTHDAY, result.getType()); assertEquals("myGMonthDay should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myGYear looks wrong", "1901", result.getString()); assertEquals("myGYear should be Type.GYEAR", EvalResult.Type.GYEAR, result.getType()); assertEquals("myGYear should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myGYearMonth looks wrong", "1901-01", result.getString()); assertEquals("myGYearMonth should be Type.GYEARMONTH", EvalResult.Type.GYEARMONTH, result.getType()); assertEquals("myGYearMonth should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); // the lexical format MarkLogic uses to serialize a date assertEquals("myDate should = '2014-09-01", "2014-09-01", result.getString()); assertEquals("myDate should be Type.DATE", EvalResult.Type.DATE, result.getType()); assertEquals("myDate should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); // the lexical format MarkLogic uses to serialize a dateTime assertEquals("myDateTime should = '2014-09-01T00:00:00+02:00'", "2014-09-01T00:00:00+02:00", result.getString()); assertEquals("myDateTime should be Type.DATETIME", EvalResult.Type.DATETIME, result.getType()); assertEquals("myDateTime should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myTime looks wrong", "00:01:01", result.getString()); assertEquals("myTime should be Type.TIME", EvalResult.Type.TIME, result.getType()); assertEquals("myTime should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myCtsQuery should be Type.OTHER", EvalResult.Type.OTHER, result.getType()); assertEquals("myCtsQuery should be Format.TEXT", Format.TEXT, result.getFormat()); result = results.next(); assertEquals("myFunction should be Type.OTHER", EvalResult.Type.OTHER, result.getType()); assertEquals("myFunction should be Format.TEXT", Format.TEXT, result.getFormat()); } finally { results.close(); } }