Example usage for javax.xml.bind DatatypeConverter printHexBinary

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

Introduction

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

Prototype

public static String printHexBinary(byte[] val) 

Source Link

Document

Converts an array of bytes into a string.

Usage

From source file:com.microsoftopentechnologies.windowsazurestorage.service.UploadToFileService.java

private String uploadCloudFile(final CloudFile cloudFile, final FilePath localPath) throws WAStorageException {
    try {/*  w w w  .  j  a v  a  2 s  .c om*/
        ensureDirExist(cloudFile.getParent());
        cloudFile.setMetadata(updateMetadata(cloudFile.getMetadata()));

        final MessageDigest md = DigestUtils.getMd5Digest();
        long startTime = System.currentTimeMillis();
        try (InputStream inputStream = localPath.read();
                DigestInputStream digestInputStream = new DigestInputStream(inputStream, md)) {
            cloudFile.upload(digestInputStream, localPath.length(), null, new FileRequestOptions(),
                    Utils.updateUserAgent());
        }
        long endTime = System.currentTimeMillis();

        println("Uploaded blob with uri " + cloudFile.getUri() + " in " + getTime(endTime - startTime));
        return DatatypeConverter.printHexBinary(md.digest());
    } catch (IOException | InterruptedException | URISyntaxException | StorageException e) {
        throw new WAStorageException("fail to upload file to azure file storage", e);
    }

}

From source file:at.tuwien.mnsa.smssender.SMS.java

/**
 * Get the list of single SMS for a possible concatenated SMS
 * @return //from w w  w .j a va 2s  .c  om
 */
public List<SMSRepresentation> getMultiMessage() {
    List<SMSRepresentation> messages = new LinkedList<>();

    //try to get all in a single message
    SMSRepresentation single = this.getMessage();
    if (single.len <= 160) {
        messages.add(single);
        return messages;
    }

    //else, one message is not sufficient :-(
    //we have to split the messages
    String remainingText = this.text;
    int len = 153;
    int remaining = this.text.length();

    List<SMSPDUConverter.SMSPDUConversionResult> messageResults = new ArrayList<>();
    while (remaining > 0) {
        String text = remainingText.substring(0, Math.min(remainingText.length(), len));

        SMSPDUConverter.SMSPDUConversionResult conversionResult = SMSPDUConverter.getInstance().getContent(text,
                1);
        if (conversionResult.len > 153) {
            //we got too much :-(
            //try shorten it
            len--;
            continue;
        }
        //add the message
        messageResults.add(conversionResult);

        remaining = remaining - len;

        //continue in the text
        if (remaining > 0) {
            remainingText = remainingText.substring(len);
        }

    }

    for (int i = 0; i < messageResults.size(); i++) {
        List<Byte> bytes = new ArrayList<>();

        bytes.add((byte) 0x00); //SMSC Information
        bytes.add((byte) 0x41); //First octed of the SMS-Submit message

        bytes.add((byte) i); //TP-Message-Reference (0: phone default)
        //The message reference should be different with each SMS-SUBMIT PDU sent. (mobiletidings.com)

        int lenRec = this.recipient.length();
        bytes.add((byte) lenRec);
        bytes.add((byte) 0x91);

        bytes.addAll(Arrays.asList(ArrayUtils.toObject(getSemiOctet(this.recipient))));

        bytes.add((byte) 0x00); //TP-PID Protocol Identifier
        bytes.add((byte) 0x00); //7 bit encoding
        //bytes.add((byte) 0xAA); //validity (4 days) - @TODO: optional?

        int lenContent = Math.min(160, messageResults.get(i).len + 7); //count of septets
        bytes.add((byte) lenContent);

        bytes.add((byte) 0x05); //User data header length (UDHL)

        bytes.addAll(getMultiMessagePayloadHeader(i + 1, messageResults.size()));

        byte[] message = messageResults.get(i).message;
        bytes.addAll(Arrays.asList(ArrayUtils.toObject(message)));

        String sMessage = DatatypeConverter
                .printHexBinary(ArrayUtils.toPrimitive(bytes.toArray(new Byte[bytes.size()])));
        int smsLen = (sMessage.length() / 2) - 1;

        messages.add(new SMSRepresentation(sMessage, smsLen));
        //System.out.println("length: " + (((messages.get(i).length()/2)-1)));
    }

    //return DatatypeConverter.printHexBinary(ArrayUtils.toPrimitive(bytes.toArray(new Byte[bytes.size()])));

    return messages;
}

From source file:at.tuwien.mnsa.smssender.SMSPDUConverter.java

/**
 * Get the PDU encoding for the given message
 * @param message//from w  ww .  ja va2 s  .c  o m
 * @param rightshift of the content for concatination
 * @return 
 */
public SMSPDUConversionResult getContent(String message, int rightshift) {
    List<Byte> finalized = new LinkedList<>();
    BitSet currentWorkingBS = new BitSet(16);

    int currentShiftpos = 0;
    boolean currentlyExtended = false;
    int len = 0;

    //repeat while there are characters left
    while (message.length() > 0) {
        String c = message.substring(0, 1);
        message = message.substring(1);
        byte value;

        //loook up current character
        if (this.GSM_3GPP_TS_23_038.containsKey(c)) {
            value = this.GSM_3GPP_TS_23_038.get(c);
        } else {
            if (this.GSM_3GPP_TS_23_038_EXTENSION.containsKey(c)) {
                if (!currentlyExtended) {
                    //extension -> now do the escape character!
                    //do the "new" character the other round
                    message = c + message;
                    currentlyExtended = true;
                    value = this.GSM_3GPP_TS_23_038.get("\u001B");
                } else {
                    //we just did the ecsape character, now do the char from
                    //the extended alphabet
                    value = this.GSM_3GPP_TS_23_038_EXTENSION.get(c);
                    currentlyExtended = false;
                }
            } else {
                throw new RuntimeException("Not found: " + c);

            }

        }

        //start at 0x0
        if (currentShiftpos == 0) {
            //add current char beginning at pos 0
            addByteToBitset(value, currentWorkingBS, 0, 1, 7);
        } else {
            //else start at second byte and do flipping

            //make place for the right bits of the current char in the front
            currentWorkingBS = rightShiftBitset(currentWorkingBS, currentShiftpos);

            //add last X bits in front of the bitset
            addByteToBitset(value, currentWorkingBS, 0, 8 - currentShiftpos, currentShiftpos);

            //add the first X bits at the end of the bitset if any
            if (currentShiftpos < 7) {
                addByteToBitset(value, currentWorkingBS, 8, 1, 7 - currentShiftpos);
            }

            //the first byte of the bitset is now complete! :)
            byte finalByte = currentWorkingBS.toByteArray()[0];
            finalByte = swapEndianFormat(finalByte);
            finalized.add(finalByte);

            //shift bitset left by 8 bits since we just finished and exported a byte
            currentWorkingBS = leftShiftBitset(currentWorkingBS, 8);
        }

        currentShiftpos = (currentShiftpos + 1) % 8;
        len++;
        //for first character -> just add to the bitset
        //addByteToBitset(value, bitset, i*7);

        /*//exchange characters
        for (int j=0;j<((i%8)*8-(i%8)*7);j++) {
        boolean cBit = content.get()
        }*/

    }

    //add last byte (swap back our eagerly shifted byte)
    if (currentShiftpos == 7) {
        byte finalByte = 0x00;
        finalized.add(finalByte);
    } else if (currentShiftpos != 0) {
        byte finalByte = (currentWorkingBS.isEmpty()) ? 0x0 : currentWorkingBS.toByteArray()[0];
        finalByte = swapEndianFormat(finalByte);

        //I don't really know why,  
        //but java fills right shifts with 1s
        //so we have to manually set all new (left) bits to zero
        for (int i = 0; i < currentShiftpos; i++) {
            finalByte = (byte) (finalByte >> 1);
            finalByte = (byte) (finalByte & 0x7F); //unset first bit
        }

        //finalByte = (byte) (finalByte & 0x3F);
        finalized.add(finalByte);
    }

    byte[] finalM = ArrayUtils.toPrimitive(finalized.toArray(new Byte[finalized.size()]));
    Logger.getGlobal().info("1: " + DatatypeConverter.printHexBinary(finalM));

    //in case of rightshift for concatenation -> right shift the whole array
    if (rightshift > 0) {
        BitSet bs = BitSet.valueOf(finalM);
        bs = rightShiftBitset(bs, rightshift);
        finalM = bs.toByteArray();
        Logger.getGlobal().info("2: " + DatatypeConverter.printHexBinary(finalM));
    }

    SMSPDUConversionResult res = new SMSPDUConversionResult(finalM, len);

    return res;
}

From source file:com.microsoftopentechnologies.windowsazurestorage.service.UploadToBlobService.java

/**
 * @param blob/*from   w  ww. j  a v a 2 s.  c  om*/
 * @param src
 * @throws StorageException
 * @throws IOException
 * @throws InterruptedException
 * @returns Md5 hash of the uploaded file in hexadecimal encoding
 */
private String uploadBlob(CloudBlockBlob blob, FilePath src)
        throws StorageException, IOException, InterruptedException {
    final MessageDigest md = DigestUtils.getMd5Digest();
    long startTime = System.currentTimeMillis();
    try (InputStream inputStream = src.read();
            DigestInputStream digestInputStream = new DigestInputStream(inputStream, md)) {
        blob.upload(digestInputStream, src.length(), null, getBlobRequestOptions(), Utils.updateUserAgent());
    }
    long endTime = System.currentTimeMillis();

    println("Uploaded to file storage with uri " + blob.getUri() + " in " + getTime(endTime - startTime));
    return DatatypeConverter.printHexBinary(md.digest());
}

From source file:ws.doerr.cssinliner.email.mandrill.MandrillEmailService.java

@Override
public PublishStatus publish(String title, String body, Map<String, String> meta, String templateNamePrefix)
        throws Exception {
    try {//w  w w. j a  v a  2  s  .c  o m
        String templateName = templateNamePrefix + meta.get(META_TEMPLATE_NAME);
        MessageDigest digest = MessageDigest.getInstance("SHA-256");

        // Get the hash from the current document
        String hash = DatatypeConverter.printHexBinary(digest.digest(body.getBytes("UTF-8")));
        String template = getTemplate(templateName);

        String[] labels = new String[] {};
        if (meta.containsKey(META_LABELS))
            labels = meta.get(META_LABELS).split(",");

        if (template == null) {
            addTemplate(templateName, title, body, labels);
            return PublishStatus.ADDED;
        } else {
            String templateHash = DatatypeConverter.printHexBinary(digest.digest(template.getBytes("UTF-8")));
            if (templateHash.equals(hash))
                return PublishStatus.NO_CHANGE;

            updateTemplate(templateName, title, body, labels);
            return PublishStatus.UPDATED;
        }

    } catch (IOException ex) {
        LOG.log(Level.SEVERE, "Exception communicating with Mandrill", ex);
        throw ex;
    } catch (NoSuchAlgorithmException ex) {
        LOG.log(Level.SEVERE, "Exception getting SHA-256 digest instance", ex);
        throw ex;
    }
}

From source file:AIR.Common.DB.SQL_TYPE_To_JAVA_TYPE.java

private UUID convertToUUID(byte[] rt) {

    String rtStr = DatatypeConverter.printHexBinary(rt);
    if (rtStr.length() != 32) {
        return null; // throw some exception?
    }/*from   w ww  .j  a v  a  2s  . c om*/
    // "BFC5216AFD8A459084AF68C1962E494A" -->
    // "BFC5216A-FD8A-4590-84AF-68C1962E494A"
    String uuidStr = String.format("%s-%s-%s-%s-%s", rtStr.substring(0, 8), rtStr.substring(8, 12),
            rtStr.substring(12, 16), rtStr.substring(16, 20), rtStr.substring(20));

    return UUID.fromString(uuidStr);
}

From source file:de.unirostock.sems.cbarchive.web.Tools.java

/**
 * Generate hash id.//from w ww  .j  ava  2s .  c om
 *
 * @param input the input
 * @return the hash id
 */
public static String generateHashId(String input) {
    try {
        byte[] hash = MessageDigest.getInstance(Fields.HASH_ALGO).digest(input.getBytes());
        return DatatypeConverter.printHexBinary(hash);
    } catch (NoSuchAlgorithmException e) {
        // As fallback send the complete String
        return input;
    }
}

From source file:com.emc.ecs.sync.model.object.AbstractSyncObject.java

@Override
public String getMd5Hex(boolean forceRead) {
    return DatatypeConverter.printHexBinary(getMd5(forceRead));
}

From source file:at.yawk.buycraft.BuycraftApiImpl.java

private JsonObject get(String action, URIBuilder builder) throws IOException {
    builder.setScheme("http") // buycraft, fix your https cert
            .setHost("api.buycraft.net").setPath("/v4").setParameter("action", action)
            .setParameter("secret", DatatypeConverter.printHexBinary(client.getApiKey()))
            .setParameter("playersOnline", onlinePlayers);
    HttpGet get;/*from ww  w.j ava2  s . com*/
    try {
        get = new HttpGet(builder.build());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    HttpResponse response = httpClient.execute(get);
    HttpEntity entity = response.getEntity();
    try (InputStream stream = entity.getContent()) {
        // can't be bothered to parse HTTP encoding, UTF-8 should do the job
        Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
        return new JsonParser().parse(reader).getAsJsonObject();
    }
}