Example usage for javax.xml.bind DatatypeConverter parseHexBinary

List of usage examples for javax.xml.bind DatatypeConverter parseHexBinary

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter parseHexBinary.

Prototype

public static byte[] parseHexBinary(String lexicalXSDHexBinary) 

Source Link

Document

Converts the string argument into an array of bytes.

Usage

From source file:de.decoit.simu.cbor.xml.dictionary.parser.DictionaryParser.java

/**
 * Create a CBOR data item of the correct type filled with the specified value.
 * Possible values for the type parameter are:<br>
 * - uint (Unsigned Integer)<br>/* w ww .j a va  2s  .  co m*/
 * - negint (Negative Integer)<br>
 * - double (Double)<br>
 * - bytestr (Byte String)<br>
 * - unistr (Unicode String)<br>
 * - bool (Boolean)<br>
 * The provided CBOR value must be a valid value for that type, otherwise an exception
 * will be raised by the specific parser.
 *
 * @param type CBOR type to use
 * @param value Value of the data item
 * @return CBOR data item
 * @throws IOException if an invalid CBOR type was provided
 */
private DataItem createCborDataItem(String type, String value) throws IOException {
    if (StringUtils.isBlank(type)) {
        throw new IllegalArgumentException("CBOR type must not be blank");
    }

    if (StringUtils.isBlank(value)) {
        throw new IllegalArgumentException("CBOR value must not be blank");
    }

    switch (type) {
    case "uint":
        return new UnsignedInteger(Long.valueOf(value));
    case "negint":
        return new NegativeInteger(Long.valueOf(value));
    case "double":
        return new DoublePrecisionFloat(Double.valueOf(value));
    case "bytestr":
        return new ByteString(DatatypeConverter.parseHexBinary(value));
    case "unistr":
        return new UnicodeString(value);
    case "bool":
        if (Boolean.parseBoolean(value)) {
            return new SimpleValue(SimpleValueType.TRUE);
        } else {
            return new SimpleValue(SimpleValueType.FALSE);
        }
    default:
        throw new IOException("Unknown CBOR type found: " + type);
    }
}

From source file:net.opentsdb.tree.Branch.java

/**
 * Converts a hex string to a branch ID byte array (row key)
 * @param branch_id The branch ID to convert
 * @return The branch ID as a byte array
 * @throws IllegalArgumentException if the string is not valid hex
 */// w  w  w .j a  v  a 2 s.c om
public static byte[] stringToId(final String branch_id) {
    if (branch_id == null || branch_id.isEmpty()) {
        throw new IllegalArgumentException("Branch ID was empty");
    }
    if (branch_id.length() < 4) {
        throw new IllegalArgumentException("Branch ID was too short");
    }
    String id = branch_id;
    if (id.length() % 2 != 0) {
        id = "0" + id;
    }
    return DatatypeConverter.parseHexBinary(id);
}

From source file:com.emc.ecs.smart.SmartUploader.java

/**
 * Does a standard PUT upload using HttpURLConnection.
 *///  w w  w.ja  v  a  2 s  .  co  m
private void doSimpleUpload() {
    try {
        fileSize = Files.size(fileToUpload);
        HttpURLConnection conn = null;
        long start = System.currentTimeMillis();
        try (DigestInputStream is = new DigestInputStream(Files.newInputStream(fileToUpload),
                MessageDigest.getInstance("MD5"))) {
            conn = (HttpURLConnection) uploadUrl.openConnection();
            conn.setFixedLengthStreamingMode(fileSize);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(false);
            conn.setUseCaches(false);
            conn.setRequestMethod(HttpMethod.PUT);
            conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM);
            OutputStream os = conn.getOutputStream();
            byte[] buf = new byte[CHUNK_SIZE];
            int len;

            while ((len = is.read(buf)) != -1) {
                os.write(buf, 0, len);
                bytesUploaded += len;
                printPercent();
            }
            os.close();

            if (conn.getResponseCode() != ClientResponse.Status.OK.getStatusCode()) {
                throw new RuntimeException("Unable to upload object content: status=" + conn.getResponseCode());
            } else {
                List<String> eTags = conn.getHeaderFields().get(HttpHeaders.ETAG);
                if (eTags == null || eTags.size() < 1) {
                    throw new RuntimeException("Unable to get ETag for uploaded data");
                } else {
                    byte[] sentMD5 = is.getMessageDigest().digest();
                    String eTag = eTags.get(0);
                    byte[] gotMD5 = DatatypeConverter.parseHexBinary(eTag.substring(1, eTag.length() - 1));
                    if (!Arrays.equals(gotMD5, sentMD5)) {
                        throw new RuntimeException("ETag doesn't match streamed data's MD5.");
                    }
                }
            }
        } catch (IOException e) {
            throw new Exception("IOException while uploading object content after writing " + bytesUploaded
                    + " of " + fileSize + " bytes: " + e.getMessage());
        } finally {
            if (conn != null)
                conn.disconnect();
        }

        long elapsed = System.currentTimeMillis() - start;
        printRate(fileSize, elapsed);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.nifi.processors.standard.TestPutSQL.java

@Test
public void testBinaryColumnTypes()
        throws InitializationException, ProcessException, SQLException, IOException, ParseException {
    final TestRunner runner = TestRunners.newTestRunner(PutSQL.class);
    try (final Connection conn = service.getConnection()) {
        try (final Statement stmt = conn.createStatement()) {
            stmt.executeUpdate(//w w w  . j a  v a 2  s . com
                    "CREATE TABLE BINARYTESTS (id integer primary key, bn1 CHAR(8) FOR BIT DATA, bn2 VARCHAR(100) FOR BIT DATA, "
                            + "bn3 LONG VARCHAR FOR BIT DATA)");
        }
    }

    runner.addControllerService("dbcp", service);
    runner.enableControllerService(service);
    runner.setProperty(PutSQL.CONNECTION_POOL, "dbcp");

    final byte[] insertStatement = "INSERT INTO BINARYTESTS (ID, bn1, bn2, bn3) VALUES (?, ?, ?, ?)".getBytes();

    final String arg2BIN = fixedSizeByteArrayAsASCIIString(8);
    final String art3VARBIN = fixedSizeByteArrayAsASCIIString(50);
    final String art4LongBin = fixedSizeByteArrayAsASCIIString(32700); //max size supported by Derby

    //ASCII (default) binary formatn
    Map<String, String> attributes = new HashMap<>();
    attributes.put("sql.args.1.type", String.valueOf(Types.INTEGER));
    attributes.put("sql.args.1.value", "1");
    attributes.put("sql.args.2.type", String.valueOf(Types.BINARY));
    attributes.put("sql.args.2.value", arg2BIN);
    attributes.put("sql.args.3.type", String.valueOf(Types.VARBINARY));
    attributes.put("sql.args.3.value", art3VARBIN);
    attributes.put("sql.args.4.type", String.valueOf(Types.LONGVARBINARY));
    attributes.put("sql.args.4.value", art4LongBin);

    runner.enqueue(insertStatement, attributes);

    //ASCII with specified format
    attributes = new HashMap<>();
    attributes.put("sql.args.1.type", String.valueOf(Types.INTEGER));
    attributes.put("sql.args.1.value", "2");
    attributes.put("sql.args.2.type", String.valueOf(Types.BINARY));
    attributes.put("sql.args.2.value", arg2BIN);
    attributes.put("sql.args.2.format", "ascii");
    attributes.put("sql.args.3.type", String.valueOf(Types.VARBINARY));
    attributes.put("sql.args.3.value", art3VARBIN);
    attributes.put("sql.args.3.format", "ascii");
    attributes.put("sql.args.4.type", String.valueOf(Types.LONGVARBINARY));
    attributes.put("sql.args.4.value", art4LongBin);
    attributes.put("sql.args.4.format", "ascii");

    runner.enqueue(insertStatement, attributes);

    //Hex
    final String arg2HexBIN = fixedSizeByteArrayAsHexString(8);
    final String art3HexVARBIN = fixedSizeByteArrayAsHexString(50);
    final String art4HexLongBin = fixedSizeByteArrayAsHexString(32700);

    attributes = new HashMap<>();
    attributes.put("sql.args.1.type", String.valueOf(Types.INTEGER));
    attributes.put("sql.args.1.value", "3");
    attributes.put("sql.args.2.type", String.valueOf(Types.BINARY));
    attributes.put("sql.args.2.value", arg2HexBIN);
    attributes.put("sql.args.2.format", "hex");
    attributes.put("sql.args.3.type", String.valueOf(Types.VARBINARY));
    attributes.put("sql.args.3.value", art3HexVARBIN);
    attributes.put("sql.args.3.format", "hex");
    attributes.put("sql.args.4.type", String.valueOf(Types.LONGVARBINARY));
    attributes.put("sql.args.4.value", art4HexLongBin);
    attributes.put("sql.args.4.format", "hex");

    runner.enqueue(insertStatement, attributes);

    //Base64
    final String arg2Base64BIN = fixedSizeByteArrayAsBase64String(8);
    final String art3Base64VARBIN = fixedSizeByteArrayAsBase64String(50);
    final String art4Base64LongBin = fixedSizeByteArrayAsBase64String(32700);

    attributes = new HashMap<>();
    attributes.put("sql.args.1.type", String.valueOf(Types.INTEGER));
    attributes.put("sql.args.1.value", "4");
    attributes.put("sql.args.2.type", String.valueOf(Types.BINARY));
    attributes.put("sql.args.2.value", arg2Base64BIN);
    attributes.put("sql.args.2.format", "base64");
    attributes.put("sql.args.3.type", String.valueOf(Types.VARBINARY));
    attributes.put("sql.args.3.value", art3Base64VARBIN);
    attributes.put("sql.args.3.format", "base64");
    attributes.put("sql.args.4.type", String.valueOf(Types.LONGVARBINARY));
    attributes.put("sql.args.4.value", art4Base64LongBin);
    attributes.put("sql.args.4.format", "base64");

    runner.enqueue(insertStatement, attributes);

    runner.run();

    runner.assertAllFlowFilesTransferred(PutSQL.REL_SUCCESS, 4);

    try (final Connection conn = service.getConnection()) {
        try (final Statement stmt = conn.createStatement()) {
            final ResultSet rs = stmt.executeQuery("SELECT * FROM BINARYTESTS");

            //First Batch
            assertTrue(rs.next());
            assertEquals(1, rs.getInt(1));
            assertTrue(Arrays.equals(arg2BIN.getBytes("ASCII"), rs.getBytes(2)));
            assertTrue(Arrays.equals(art3VARBIN.getBytes("ASCII"), rs.getBytes(3)));
            assertTrue(Arrays.equals(art4LongBin.getBytes("ASCII"), rs.getBytes(4)));

            //Second batch
            assertTrue(rs.next());
            assertEquals(2, rs.getInt(1));
            assertTrue(Arrays.equals(arg2BIN.getBytes("ASCII"), rs.getBytes(2)));
            assertTrue(Arrays.equals(art3VARBIN.getBytes("ASCII"), rs.getBytes(3)));
            assertTrue(Arrays.equals(art4LongBin.getBytes("ASCII"), rs.getBytes(4)));

            //Third Batch (Hex)
            assertTrue(rs.next());
            assertEquals(3, rs.getInt(1));
            assertTrue(Arrays.equals(DatatypeConverter.parseHexBinary(arg2HexBIN), rs.getBytes(2)));
            assertTrue(Arrays.equals(DatatypeConverter.parseHexBinary(art3HexVARBIN), rs.getBytes(3)));
            assertTrue(Arrays.equals(DatatypeConverter.parseHexBinary(art4HexLongBin), rs.getBytes(4)));

            //Fourth Batch (Base64)
            assertTrue(rs.next());
            assertEquals(4, rs.getInt(1));
            assertTrue(Arrays.equals(DatatypeConverter.parseBase64Binary(arg2Base64BIN), rs.getBytes(2)));
            assertTrue(Arrays.equals(DatatypeConverter.parseBase64Binary(art3Base64VARBIN), rs.getBytes(3)));
            assertTrue(Arrays.equals(DatatypeConverter.parseBase64Binary(art4Base64LongBin), rs.getBytes(4)));

            assertFalse(rs.next());
        }
    }
}

From source file:org.cryptonode.jncryptor.AES256v2CryptorTest.java

/**
 * Tests decryption of a known ciphertext.
 * /* w  ww . j  av a  2s.  com*/
 * @throws Exception
 */
@Test
public void testKnownCiphertext() throws Exception {
    final String password = "P@ssw0rd!";
    final String expectedPlaintextString = "Hello, World! Let's use a few blocks " + "with a longer sentence.";

    // TODO confirm this with Rob Napier
    String knownCiphertext = "02013F194AA9969CF70C8ACB76824DE4CB6CDCF78B7449A87C679FB8EDB6"
            + "A0109C513481DE877F3A855A184C4947F2B3E8FEF7E916E4739F9F889A717FCAF277402866341008A"
            + "09FD3EBAC7FA26C969DD7EE72CFB695547C971A75D8BF1CC5980E0C727BD9F97F6B7489F687813BEB"
            + "94DEB61031260C246B9B0A78C2A52017AA8C92";

    byte[] ciphertext = DatatypeConverter.parseHexBinary(knownCiphertext);

    AES256v2Cryptor cryptor = new AES256v2Cryptor();
    byte[] plaintext = cryptor.decryptData(ciphertext, password.toCharArray());

    String plaintextString = new String(plaintext, Charsets.UTF_8);

    assertEquals(expectedPlaintextString, plaintextString);
}

From source file:org.cryptonode.jncryptor.TestVectorReader.java

static List<KDFTestVector> readKDFVectors() throws IOException {
    List<String> lines = readLinesFromTestResource("/kdf-v3");

    final Iterator<String> iterator = lines.iterator();

    List<KDFTestVector> result = new ArrayList<KDFTestVector>();

    while (true) {
        String titleValue = readNextValue(iterator, TITLE_FIELD, false);
        if (titleValue == null) {
            // we are done
            break;
        }/*from w ww .j av  a2s  . c om*/

        int versionValue = Integer.parseInt(readNextValue(iterator, VERSION_FIELD, true));

        String passwordValue = readNextValue(iterator, PASSWORD_FIELD, true);
        byte[] saltValue = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, SALT_FIELD, true).replace(" ", ""));
        byte[] keyValue = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, KEY_FIELD, true).replace(" ", ""));

        result.add(new KDFTestVector(titleValue, versionValue, passwordValue, saltValue, keyValue));
    }

    return result;
}

From source file:org.cryptonode.jncryptor.TestVectorReader.java

static List<KeyTestVector> readKeyVectors() throws IOException {
    List<String> lines = readLinesFromTestResource("/key-v3");

    final Iterator<String> iterator = lines.iterator();

    List<KeyTestVector> result = new ArrayList<KeyTestVector>();

    while (true) {
        String titleValue = readNextValue(iterator, TITLE_FIELD, false);
        if (titleValue == null) {
            // we are done
            break;
        }//  w w  w. ja va2s .com

        int versionValue = Integer.parseInt(readNextValue(iterator, VERSION_FIELD, true));

        byte[] encryptionKey = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, ENCRYPTION_KEY_FIELD, true).replace(" ", ""));
        byte[] hmacKey = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, HMAC_KEY_FIELD, true).replace(" ", ""));
        byte[] iv = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, IV_KEY_FIELD, true).replace(" ", ""));
        byte[] plaintext = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, PLAINTEXT_FIELD, true).replace(" ", ""));
        byte[] ciphertext = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, CIPHERTEXT_FIELD, true).replace(" ", ""));

        result.add(
                new KeyTestVector(titleValue, versionValue, encryptionKey, hmacKey, iv, plaintext, ciphertext));
    }

    return result;
}

From source file:org.cryptonode.jncryptor.TestVectorReader.java

static List<PasswordTestVector> readPasswordVectors() throws IOException {
    List<String> lines = readLinesFromTestResource("/password-v3");

    final Iterator<String> iterator = lines.iterator();

    List<PasswordTestVector> result = new ArrayList<PasswordTestVector>();

    while (true) {
        String titleValue = readNextValue(iterator, TITLE_FIELD, false);
        if (titleValue == null) {
            // we are done
            break;
        }//from ww w  .jav a  2 s  .  c o m

        int versionValue = Integer.parseInt(readNextValue(iterator, VERSION_FIELD, true));
        String password = readNextValue(iterator, PASSWORD_FIELD, false);

        byte[] encryptionSalt = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, ENCRYPTION_SALT_FIELD, true).replace(" ", ""));
        byte[] hmacSalt = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, HMAC_SALT_FIELD, true).replace(" ", ""));
        byte[] iv = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, IV_KEY_FIELD, true).replace(" ", ""));
        byte[] plaintext = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, PLAINTEXT_FIELD, true).replace(" ", ""));
        byte[] ciphertext = DatatypeConverter
                .parseHexBinary(readNextValue(iterator, CIPHERTEXT_FIELD, true).replace(" ", ""));

        result.add(new PasswordTestVector(titleValue, versionValue, password, encryptionSalt, hmacSalt, iv,
                plaintext, ciphertext));
    }

    return result;
}

From source file:org.eclipse.smarthome.binding.lifx.internal.fields.MACAddress.java

public MACAddress(String string, boolean isHex) {
    if (!isHex) {
        this.bytes = ByteBuffer.wrap(string.getBytes());
        createHex();/* w  w  w .java  2s  .  c  om*/
    } else {
        this.bytes = ByteBuffer.wrap(DatatypeConverter.parseHexBinary(string));

        try {
            formatHex(string, 2, ":");
        } catch (IOException e) {
            logger.error("An exception occurred while formatting an HEX string : '{}'", e.getMessage());
        }
    }
}

From source file:org.glukit.dexcom.sync.DecodingUtils.java

/**
 * Takes a string like 0A 0F 05 and converts it into a byte array.
 *
 * @param hexString hex string, can contain spaces
 * @return the byte array//from w  ww .  j a va  2  s.  c  om
 */
public static byte[] fromHexString(String hexString) {
    String hexStringWithoutSpaces = StringUtils.remove(hexString, " ");
    return DatatypeConverter.parseHexBinary(hexStringWithoutSpaces);
}