Example usage for javax.xml.bind.annotation.adapters HexBinaryAdapter HexBinaryAdapter

List of usage examples for javax.xml.bind.annotation.adapters HexBinaryAdapter HexBinaryAdapter

Introduction

In this page you can find the example usage for javax.xml.bind.annotation.adapters HexBinaryAdapter HexBinaryAdapter.

Prototype

HexBinaryAdapter

Source Link

Usage

From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java

protected String writeToXML() {

    StringWriter sw = new StringWriter();

    try {//from   w w w .jav  a 2  s  .  c o m

        XMLStreamWriter xsw = XMLOutputFactory.newFactory().createXMLStreamWriter(sw);

        xsw.writeStartDocument();
        xsw.writeCharacters("\n");
        xsw.writeStartElement("root");
        xsw.writeCharacters("\n");
        xsw.writeStartElement(CORRECTION_ELEMENT);
        xsw.writeAttribute(N_POINTS_ATTR, Integer.toString(this.distanceCutoffs.getDimension()));
        xsw.writeAttribute(REF_CHANNEL_ATTR, Integer.toString(this.referenceChannel));
        xsw.writeAttribute(CORR_CHANNEL_ATTR, Integer.toString(this.correctionChannel));

        xsw.writeCharacters("\n");

        for (int i = 0; i < this.distanceCutoffs.getDimension(); i++) {
            xsw.writeStartElement(CORRECTION_POINT_ELEMENT);

            xsw.writeAttribute(X_POS_ATTR, Double.toString(this.positionsForCorrection.getEntry(i, 0)));
            xsw.writeAttribute(Y_POS_ATTR, Double.toString(this.positionsForCorrection.getEntry(i, 1)));
            xsw.writeAttribute(Z_POS_ATTR, Double.toString(this.positionsForCorrection.getEntry(i, 2)));

            xsw.writeCharacters("\n");

            String x_param_string = "";
            String y_param_string = "";
            String z_param_string = "";

            for (int j = 0; j < this.correctionX.getColumnDimension(); j++) {
                String commaString = "";
                if (j != 0)
                    commaString = ", ";
                x_param_string += commaString + this.correctionX.getEntry(i, j);
                y_param_string += commaString + this.correctionY.getEntry(i, j);
                z_param_string += commaString + this.correctionZ.getEntry(i, j);
            }

            x_param_string = x_param_string.trim() + "\n";
            y_param_string = y_param_string.trim() + "\n";
            z_param_string = z_param_string.trim() + "\n";

            xsw.writeStartElement(X_PARAM_ELEMENT);

            xsw.writeCharacters(x_param_string);

            xsw.writeEndElement();

            xsw.writeCharacters("\n");

            xsw.writeStartElement(Y_PARAM_ELEMENT);

            xsw.writeCharacters(y_param_string);

            xsw.writeEndElement();

            xsw.writeCharacters("\n");

            xsw.writeStartElement(Z_PARAM_ELEMENT);

            xsw.writeCharacters(z_param_string);

            xsw.writeEndElement();

            xsw.writeCharacters("\n");

            xsw.writeEndElement();

            xsw.writeCharacters("\n");

        }

        xsw.writeStartElement(BINARY_DATA_ELEMENT);

        xsw.writeAttribute(ENCODING_ATTR, ENCODING_NAME);

        ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream();

        try {

            ObjectOutputStream oos = new ObjectOutputStream(bytesOutput);

            oos.writeObject(this);

        } catch (java.io.IOException e) {
            java.util.logging.Logger.getLogger(LOG_NAME)
                    .severe("Exception encountered while serializing correction: " + e.getMessage());

        }

        HexBinaryAdapter adapter = new HexBinaryAdapter();
        xsw.writeCharacters(adapter.marshal(bytesOutput.toByteArray()));

        xsw.writeEndElement();

        xsw.writeCharacters("\n");

        xsw.writeEndElement();

        xsw.writeCharacters("\n");

        xsw.writeEndElement();

        xsw.writeCharacters("\n");

        xsw.writeEndDocument();

    } catch (XMLStreamException e) {

        java.util.logging.Logger.getLogger(LOG_NAME)
                .severe("Exception encountered while writing XML correction output: " + e.getMessage());

    }

    return sw.toString();

}

From source file:com.kellerkindt.scs.utilities.Utilities.java

/**
 * Serializes the MetaData of an ItemStack
 * and marshals it then in a String/*from  w ww .ja  va  2  s .  co  m*/
 * @param itemMeta The MetaData so save
 * @return The marshaled ItemStack as String
 * @throws IOException On any internal Exception
 */
public static String toHexString(ItemMeta itemMeta) throws IOException {

    // create streams
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);

    // write map
    oos.writeObject(itemMeta.serialize());
    oos.flush();

    // toHexString
    return new HexBinaryAdapter().marshal(baos.toByteArray());
}

From source file:com.kellerkindt.scs.utilities.Utilities.java

/**
 * Deserializes the ItemMeta of an ItemStack from a marshaled String
 * @param hex ItemMeta marshaled in a String
 * @return The deserialized ItemMeta/*from   w  w  w. j a  v a 2s  .c  o  m*/
 * @throws IOException On any internal exception
 */
@SuppressWarnings("unchecked")
public static ItemMeta toItemMeta(String hex) throws IOException {

    // create streams
    byte[] bytes = new HexBinaryAdapter().unmarshal(hex);
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bais);

    try {
        return (ItemMeta) ConfigurationSerialization.deserializeObject((Map<String, Object>) ois.readObject());

    } catch (ClassNotFoundException cnfe) {
        throw new IOException(cnfe);
    }
}

From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java

/**
 * Reads a stored correction from disk.//w w  w  .  j  a va  2  s . c o m
 * 
 * @param filename                  The name of the file containing the Correction that was previously written to disk.
 * @return                          The Correction contained in the file.
 * @throws java.io.IOException      if the Correction cannot be successfully read.
 * @throws ClassNotFoundException   if the file does not contain a Correction.
 */
public static Correction readFromDisk(String filename) throws java.io.IOException, ClassNotFoundException {

    File f = new File(filename);

    FileReader fr = new FileReader(f);

    XMLStreamReader xsr = null;
    String encBinData = null;

    try {
        xsr = XMLInputFactory.newFactory().createXMLStreamReader(fr);

        while (xsr.hasNext()) {

            int event = xsr.next();

            if (event != XMLStreamReader.START_ELEMENT)
                continue;

            if (xsr.hasName() && xsr.getLocalName() == BINARY_DATA_ELEMENT) {

                encBinData = xsr.getElementText();

                break;

            }

        }
    } catch (XMLStreamException e) {
        java.util.logging.Logger.getLogger(LOG_NAME)
                .severe("Exception encountered while reading XML correction: " + e.getMessage());
    }
    byte[] binData = (new HexBinaryAdapter()).unmarshal(encBinData);

    ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(binData));

    Object o = oi.readObject();

    return (Correction) o;

}

From source file:com.smartmarmot.dbforbix.config.Config.java

public static String calculateMD5Sum(String inStr) {
    MessageDigest hasher = null;//from   w  w w. j  a  v a  2  s  . c  om
    try {
        hasher = java.security.MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        LOG.error("Wrong hashing algorithm name provided while getting instance of MessageDigest: "
                + e.getLocalizedMessage());
    }
    return (new HexBinaryAdapter()).marshal(hasher.digest(inStr.getBytes()));
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.OfflineImageReconstructor.java

private INodeSection.XAttrFeatureProto.Builder xattrsXmlToProto(Node xattrs) throws IOException {
    INodeSection.XAttrFeatureProto.Builder bld = INodeSection.XAttrFeatureProto.newBuilder();
    while (true) {
        Node xattr = xattrs.removeChild(INODE_SECTION_XATTR);
        if (xattr == null) {
            break;
        }/*www. ja  va 2s  .  c  om*/
        INodeSection.XAttrCompactProto.Builder b = INodeSection.XAttrCompactProto.newBuilder();
        String ns = xattr.removeChildStr(INODE_SECTION_NS);
        if (ns == null) {
            throw new IOException("<xattr> had no <ns> entry.");
        }
        int nsIdx = XAttrProtos.XAttrProto.XAttrNamespaceProto.valueOf(ns).ordinal();
        String name = xattr.removeChildStr(SECTION_NAME);
        String valStr = xattr.removeChildStr(INODE_SECTION_VAL);
        byte[] val = null;
        if (valStr == null) {
            String valHex = xattr.removeChildStr(INODE_SECTION_VAL_HEX);
            if (valHex == null) {
                throw new IOException("<xattr> had no <val> or <valHex> entry.");
            }
            val = new HexBinaryAdapter().unmarshal(valHex);
        } else {
            val = valStr.getBytes("UTF8");
        }
        b.setValue(ByteString.copyFrom(val));

        // The XAttrCompactProto name field uses a fairly complex format
        // to encode both the string table ID of the xattr name and the
        // namespace ID.  See the protobuf file for details.
        int nameId = registerStringId(name);
        int encodedName = (nameId << XATTR_NAME_OFFSET)
                | ((nsIdx & XATTR_NAMESPACE_MASK) << XATTR_NAMESPACE_OFFSET)
                | (((nsIdx >> 2) & XATTR_NAMESPACE_EXT_MASK) << XATTR_NAMESPACE_EXT_OFFSET);
        b.setName(encodedName);
        xattr.verifyNoRemainingKeys("xattr");
        bld.addXAttrs(b);
    }
    xattrs.verifyNoRemainingKeys("xattrs");
    return bld;
}

From source file:org.jts.eclipse.conversion.cjsidl.ConversionUtil.java

/**
 * Converts a hex string to a byte array
 * @param hexString - input hex string/*from  www .ja  v  a 2 s . c o  m*/
 * @return - resulting byte array
 */
public static byte[] hexStringToByteArray(String hexString) {
    HexBinaryAdapter adapter = new HexBinaryAdapter();
    if (hexString.startsWith("0x")) {
        hexString = hexString.substring(2, hexString.length());
    }
    byte[] bytes = adapter.unmarshal(hexString);
    return bytes;
}

From source file:org.jts.eclipse.conversion.cjsidl.ConversionUtil.java

/**
 * Converts a byte array to a hex string 
 * @param hexArray - input byte array/* w  w w. j a  v a2 s .  c  o  m*/
 * @return - resulting hex string
 */
public static String byteArrayToHexString(byte[] hexArray) {
    HexBinaryAdapter adapter = new HexBinaryAdapter();
    String result = adapter.marshal(hexArray);
    return result;
}

From source file:synapticloop.b2.util.ChecksumHelper.java

/**
 * Calculate and return the sha1 sum of an input stream
 *
 * @param in the input stream to calculate the sha1 sum of
 *
 * @return the sha1 sum/*from   ww w  . j a v  a2s . c  o m*/
 *
 * @throws IOException if there was an error calculating the sha1 sum
 */
public static String calculateSha1(InputStream in) throws IOException {

    MessageDigest messageDigest;
    InputStream inputStream = null;
    try {
        messageDigest = MessageDigest.getInstance("SHA-1");
        inputStream = new BufferedInputStream(in);
        byte[] buffer = new byte[8192];
        int len = inputStream.read(buffer);

        while (len != -1) {
            messageDigest.update(buffer, 0, len);
            len = inputStream.read(buffer);
        }

        return (new HexBinaryAdapter().marshal(messageDigest.digest()));
    } catch (NoSuchAlgorithmException ex) {
        throw new IOException(ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:tech.sirwellington.alchemy.generator.StringGenerators.java

/**
 * Generates a random hexadecimal string.
 *
 * @param length The length of the String, must be at least 1.
 *
 * @return/*from  w ww  .j a v  a2s  .co m*/
 */
public static AlchemyGenerator<String> hexadecimalString(int length) {
    checkThat(length > 0, "Length must be at least 1");
    HexBinaryAdapter hexBinaryAdapter = new HexBinaryAdapter();
    AlchemyGenerator<byte[]> binaryGenerator = binary(length);

    return () -> {
        byte[] binary = one(binaryGenerator);
        String hex = hexBinaryAdapter.marshal(binary);
        return StringUtils.left(hex, length);
    };
}