Example usage for org.apache.commons.codec.binary Hex encodeHex

List of usage examples for org.apache.commons.codec.binary Hex encodeHex

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Hex encodeHex.

Prototype

public static char[] encodeHex(byte[] data) 

Source Link

Document

Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.

Usage

From source file:mvm.rya.mongodb.dao.SimpleMongoDBStorageStrategy.java

public BasicDBObject serializeInternal(RyaStatement statement) {
    String context = "";
    if (statement.getContext() != null) {
        context = statement.getContext().getData();
    }/*from   www .j  ava 2 s  .  com*/
    String id = statement.getSubject().getData() + " " + statement.getPredicate().getData() + " "
            + statement.getObject().getData() + " " + context;
    byte[] bytes = id.getBytes();
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        bytes = digest.digest(bytes);
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    BasicDBObject doc = new BasicDBObject(ID, new String(Hex.encodeHex(bytes)))
            .append(SUBJECT, statement.getSubject().getData())
            .append(PREDICATE, statement.getPredicate().getData())
            .append(OBJECT, statement.getObject().getData())
            .append(OBJECT_TYPE, statement.getObject().getDataType().toString()).append(CONTEXT, context);
    return doc;

}

From source file:au.com.ish.derbydump.derbydump.metadata.Column.java

/**
 * this is a tricky one. according to// ww w .  j  a  va  2s  .  c o m
 <ul>
 <li>http://db.apache.org/derby/docs/10.2/ref/rrefjdbc96386.html</li>
 <li>http://stackoverflow.com/questions/7510112/how-to-make-java-ignore-escape-sequences-in-a-string</li>
 <li>http://dba.stackexchange.com/questions/10642/mysql-mysqldump-uses-n-instead-of-null</li>
 <li>http://stackoverflow.com/questions/12038814/import-hex-binary-data-into-mysql</li>
 <li>http://stackoverflow.com/questions/3126210/insert-hex-values-into-mysql</li>
 <li>http://www.xaprb.com/blog/2009/02/12/5-ways-to-make-hexadecimal-identifiers-perform-better-on-mysql/</li>
 </ul>
 and many others, there is no safer way of exporting blobs than separate data files or hex format.<br/>
 tested, mysql detects and imports hex encoded fields automatically.
        
 * @param blob Blob which we will convert to hex encoded string
 * @return String representation of binary data
 */
public static String processBinaryData(Blob blob) throws SQLException {
    if (blob == null) {
        return "NULL";
    }
    int blobLength = (int) blob.length();
    if (blobLength == 0) {
        return "NULL";
    }
    byte[] bytes = blob.getBytes(1L, blobLength);

    return "0x" + new String(Hex.encodeHex(bytes)).toUpperCase();
}

From source file:com.anyi.gp.license.RegisterTools.java

public static String encodeString(String str) {
    String tempStr = "";
    try {/*from   w w w .j a  v a2s .c  o m*/
        String encodeStr = "$#TGDF*FAA&21we@VGXD532w23413!";
        if (str == null) {
            str = "";
        }

        int i = 0;
        int j = 0;
        for (i = 0; i < str.length(); i++) {
            if (j >= encodeStr.length()) {
                j = 0;
            }
            tempStr = tempStr + (char) (str.charAt(i) ^ encodeStr.charAt(j));
            j++;
        }
        tempStr = new String(Hex.encodeHex(tempStr.getBytes("GBK")));
    } catch (Exception ex) {
        throw new RuntimeException(ex.getMessage());
    }
    return tempStr;
}

From source file:edu.psu.citeseerx.utility.FileDigest.java

/**
 * Informs if the MD5 file digest is equals to a given digest
 * @param digest  a <code>byte[]</code> that represents a file digest
 * @param toValidate File to validate againts digest
 * @return   true if the MD5 file digest is equals to digest
 *///from  www . j  a  va 2  s  .c  om
public static boolean validateMD5(byte[] digest, File toValidate) {
    String fileDigest = new String(Hex.encodeHex(digest));
    return validateMD5(fileDigest, toValidate);
}

From source file:com.qut.middleware.esoe.sso.servlet.SSOServlet.java

private void doRequest(HttpServletRequest request, HttpServletResponse response, RequestMethod method)
        throws ServletException, IOException {
    SSOProcessorData data;/*from w w w .j a v a2  s  . co m*/

    data = (SSOProcessorData) request.getSession().getAttribute(SSOProcessorData.SESSION_NAME);

    String remoteAddress = request.getRemoteAddr();

    this.logger.debug("[SSO for {}] SSOServlet got {} request. SSO processor data element was {}",
            new Object[] { remoteAddress, method.toString(), data == null ? "null" : "not null" });

    if (data == null) {
        data = new SSOProcessorDataImpl();
        request.getSession().setAttribute(SSOProcessorData.SESSION_NAME, data);
    }

    data.setHttpRequest(request);
    data.setHttpResponse(response);
    data.setRequestMethod(method);

    String oldRemoteAddress = data.getRemoteAddress();
    if (oldRemoteAddress != null) {
        if (!oldRemoteAddress.equals(remoteAddress)) {
            this.logger.warn("[SSO for {}] IP address changed. Old address was: {}", remoteAddress,
                    oldRemoteAddress);
        }
    }

    data.setRemoteAddress(remoteAddress);

    try {
        SSOProcessor.result result = this.ssoProcessor.execute(data);
        this.logger.debug("[SSO for {}] SSOProcessor returned a result of {}",
                new Object[] { remoteAddress, String.valueOf(result) });
    } catch (SSOException e) {
        if (!data.isResponded()) {
            InetAddress inetAddress = Inet4Address.getByName(remoteAddress);
            String code = CalendarUtils.generateXMLCalendar().toString() + "-"
                    + new String(Hex.encodeHex(inetAddress.getAddress()));

            this.logger.error("[SSO for {}] {} Error occurred in SSOServlet.doPost. Exception was: {}", code,
                    e.getMessage());
            this.logger.debug(code + " Error occurred in SSOServlet.doPost. Exception follows", e);
            throw new ServletException(
                    "An error occurred during the sign-on process, and the session could not be established. Instance error is: "
                            + code);
        }
    }
}

From source file:com.linkedin.databus.client.registration.RegistrationIdGenerator.java

/**
 * Generate a hash out of the String id/*from w w  w. java  2  s  . c om*/
 *
 * @param id
 * @return
 */
private static String generateByteHash(String id) {
    try {
        final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.reset();
        messageDigest.update(id.getBytes(Charset.forName("UTF8")));
        final byte[] resultsByte = messageDigest.digest();
        String hash = new String(Hex.encodeHex(resultsByte));

        final int length = 8;
        if (hash.length() > length)
            hash = hash.substring(0, length);

        return hash;
    } catch (NoSuchAlgorithmException nse) {
        LOG.error("Unexpected error : Got NoSuchAlgorithm exception for MD5");
        return "";
    }
}

From source file:com.impetus.client.crud.datatypes.ByteDataTest.java

/**
 * On insert image in cassandra blob object
 * //from ww  w  . ja v  a2s  .co  m
 * @throws Exception
 *             the exception
 */
@Test
public void onInsertBlobImageCassandra() throws Exception {

    PersonCassandra personWithKey = new PersonCassandra();
    personWithKey.setPersonId("111");

    BufferedImage originalImage = ImageIO.read(new File("src/test/resources/nature.jpg"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(originalImage, "jpg", baos);
    baos.flush();
    byte[] imageInByte = baos.toByteArray();

    baos.close();

    personWithKey.setA(imageInByte);
    em.persist(personWithKey);

    em.clear();

    String qry = "Select p from PersonCassandra p where p.personId = 111";
    Query q = em.createQuery(qry);
    List<PersonCassandra> persons = q.getResultList();
    PersonCassandra person = persons.get(0);

    InputStream in = new ByteArrayInputStream(person.getA());
    BufferedImage bImageFromConvert = ImageIO.read(in);

    ImageIO.write(bImageFromConvert, "jpg", new File("src/test/resources/nature-test.jpg"));

    Assert.assertNotNull(person.getA());
    Assert.assertEquals(new File("src/test/resources/nature.jpg").getTotalSpace(),
            new File("src/test/resources/nature-test.jpg").getTotalSpace());
    Assert.assertEquals(String.valueOf(Hex.encodeHex((byte[]) imageInByte)),
            String.valueOf(Hex.encodeHex((byte[]) person.getA())));

}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.dta.DTAFileReaderSpi.java

@Override
public boolean canDecodeInput(BufferedInputStream stream) throws IOException {
    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }/*from   ww  w .j  a  v  a  2  s  .  co m*/

    dbgLog.fine("applying the dta test\n");

    byte[] b = new byte[DTA_HEADER_SIZE];

    if (stream.markSupported()) {
        stream.mark(0);
    }
    int nbytes = stream.read(b, 0, DTA_HEADER_SIZE);

    if (nbytes == 0) {
        throw new IOException();
    }

    if (stream.markSupported()) {
        stream.reset();
    }

    dbgLog.info("hex dump: 1st 4bytes =>" + new String(Hex.encodeHex(b)) + "<-");

    if (b[2] != 1) {
        dbgLog.fine("3rd byte is not 1: given file is not stata-dta type");
        return false;
    } else if ((b[1] != 1) && (b[1] != 2)) {
        dbgLog.fine("2nd byte is neither 0 nor 1: this file is not stata-dta type");
        return false;
    } else if (!DTAFileReaderSpi.stataReleaseNumber.containsKey(b[0])) {
        dbgLog.fine("1st byte (" + b[0] + ") is not within the ingestable range [rel. 3-10]:"
                + "this file is NOT stata-dta type");
        return false;
    } else {
        dbgLog.fine("this file is stata-dta type: " + DTAFileReaderSpi.stataReleaseNumber.get(b[0])
                + "(No in HEX=" + b[0] + ")");
        return true;
    }

}

From source file:com.mastercard.mobile_api.bytes.ByteArray.java

/**
 * Convert the Byte Array into a Java String HEX formatted
 *
 * @return A Java String with the content of the Byte Array encoded in HEX
 *
 * *//*from   w  w w  .  java 2 s.c  o m*/
public String toHexString() {
    return new String(Hex.encodeHex(mData)).toUpperCase();
}

From source file:net.padlocksoftware.padlock.validator.ValidatorTest.java

License:asdf

@Test
public void testPrior() throws Exception {
    KeyPair pair = KeyManager.createKeyPair();
    License license = LicenseFactory.createLicense();
    license.setStartDate(new Date(System.currentTimeMillis() + 20000L));

    LicenseSigner signer = LicenseSigner.createLicenseSigner((DSAPrivateKey) pair.getPrivate());
    signer.sign(license);/*from  w  ww  .j a v a  2s.  c o  m*/

    String key = new String(Hex.encodeHex(pair.getPublic().getEncoded()));
    Validator validator = new Validator(license, key);
    boolean ex = false;
    try {
        validator.validate();
    } catch (ValidatorException e) {
        ex = true;
    }
    assertTrue(ex);
}