/** * Gets a copy of the buffered bytes. * * @return the byte array * @see org.bson.io.OutputBuffer#pipe(java.io.OutputStream) */ public byte[] toByteArray() { try { ByteArrayOutputStream bout = new ByteArrayOutputStream(size()); pipe(bout); return bout.toByteArray(); } catch (IOException ioe) { throw new RuntimeException("should be impossible", ioe); } }
/** * mostly for testing */ public byte[] toByteArray() { try { final ByteArrayOutputStream bout = new ByteArrayOutputStream(size()); pipe(bout); return bout.toByteArray(); } catch (IOException ioe) { throw new RuntimeException("should be impossible", ioe); } }
public String hex() { final StringBuilder buf = new StringBuilder(); try { pipe(new OutputStream() { @Override public void write(int b) { String s = Integer.toHexString(0xff & b); if (s.length() < 2) buf.append("0"); buf.append(s); } }); } catch (IOException ioe) { throw new RuntimeException("impossible"); } return buf.toString(); }
public String md5() { final MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error - this implementation of Java doesn't support MD5."); } md5.reset(); try { pipe(new OutputStream() { @Override public void write(byte[] b, int off, int len) { md5.update(b, off, len); } @Override public void write(int b) { md5.update((byte) (b & 0xFF)); } }); } catch (IOException ioe) { throw new RuntimeException("impossible"); } byte[] md5Bytes = md5.digest(); StringBuffer md5String = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) { md5String.append(String.format("%02x", md5Bytes[i])); } return md5String.toString(); }