Example usage for java.io ByteArrayOutputStream reset

List of usage examples for java.io ByteArrayOutputStream reset

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream reset.

Prototype

public synchronized void reset() 

Source Link

Document

Resets the count field of this ByteArrayOutputStream to zero, so that all currently accumulated output in the output stream is discarded.

Usage

From source file:de.alpharogroup.io.SerializedObjectUtils.java

/**
 * The Method toByteArray() serialize an Object to byte array.
 *
 * @param <T>/*from  w w  w. j  a  v  a  2 s.co  m*/
 *            the generic type of the given object
 * @param object
 *            The Object to convert into a byte array.
 * @return The byte array from the Object.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static <T> byte[] toByteArray(final T object) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = null;
    ObjectOutputStream objectOutputStream = null;
    try {

        byteArrayOutputStream = new ByteArrayOutputStream(FileConstants.KILOBYTE);

        byteArrayOutputStream.reset();
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    } finally {
        StreamUtils.closeOutputStream(byteArrayOutputStream);
        StreamUtils.closeOutputStream(objectOutputStream);
    }
}

From source file:org.apache.hadoop.hbase.security.EncryptionUtil.java

/**
 * Protect a key by encrypting it with the secret key of the given subject.
 * The configuration must be set up correctly for key alias resolution.
 * @param conf configuration/*  w ww.  j av  a  2s  .c o m*/
 * @param subject subject key alias
 * @param key the key
 * @return the encrypted key bytes
 */
public static byte[] wrapKey(Configuration conf, String subject, Key key) throws IOException {
    // Wrap the key with the configured encryption algorithm.
    String algorithm = conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES);
    Cipher cipher = Encryption.getCipher(conf, algorithm);
    if (cipher == null) {
        throw new RuntimeException("Cipher '" + algorithm + "' not available");
    }
    EncryptionProtos.WrappedKey.Builder builder = EncryptionProtos.WrappedKey.newBuilder();
    builder.setAlgorithm(key.getAlgorithm());
    byte[] iv = null;
    if (cipher.getIvLength() > 0) {
        iv = new byte[cipher.getIvLength()];
        RNG.nextBytes(iv);
        builder.setIv(ByteStringer.wrap(iv));
    }
    byte[] keyBytes = key.getEncoded();
    builder.setLength(keyBytes.length);
    builder.setHash(ByteStringer.wrap(Encryption.hash128(keyBytes)));
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Encryption.encryptWithSubjectKey(out, new ByteArrayInputStream(keyBytes), subject, conf, cipher, iv);
    builder.setData(ByteStringer.wrap(out.toByteArray()));
    // Build and return the protobuf message
    out.reset();
    builder.build().writeDelimitedTo(out);
    return out.toByteArray();
}

From source file:com.yahoo.bullet.record.AvroBulletRecordTest.java

public static byte[] getAvroBytes(Map<String, Object> data) {
    try {//w ww. j  av a2 s .com
        // Keep this independent from the code
        BulletAvro record = new BulletAvro(data);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        SpecificDatumWriter<BulletAvro> writer = new SpecificDatumWriter<>(BulletAvro.class);
        Encoder encoder = new EncoderFactory().directBinaryEncoder(stream, null);
        stream.reset();
        writer.write(record, encoder);
        encoder.flush();
        return stream.toByteArray();
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.xebialabs.overthere.cifs.telnet.CifsTelnetConnection.java

private static void handleReceivedLine(final ByteArrayOutputStream outputBuf, final String outputBufStr,
        final PipedOutputStream toCallersStdout) throws IOException {
    if (!outputBufStr.contains(DETECTABLE_WINDOWS_PROMPT)) {
        toCallersStdout.write(outputBuf.toByteArray());
        toCallersStdout.flush();/*from w ww . jav  a2s.  com*/
    }
    outputBuf.reset();
}

From source file:URLEncoder.java

public static String encode(String s, String enc) throws UnsupportedEncodingException {
    if (!needsEncoding(s)) {
        return s;
    }/*  w  w  w  .j  a v a2 s. co  m*/

    int length = s.length();

    StringBuffer out = new StringBuffer(length);

    ByteArrayOutputStream buf = new ByteArrayOutputStream(10); // why 10?
    // w3c says
    // so.

    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(buf, enc));

    for (int i = 0; i < length; i++) {
        int c = (int) s.charAt(i);
        if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == ' ') {
            if (c == ' ') {
                c = '+';
            }

            toHex(out, buf.toByteArray());
            buf.reset();

            out.append((char) c);
        } else {
            try {
                writer.write(c);

                if (c >= 0xD800 && c <= 0xDBFF && i < length - 1) {
                    int d = (int) s.charAt(i + 1);
                    if (d >= 0xDC00 && d <= 0xDFFF) {
                        writer.write(d);
                        i++;
                    }
                }

                writer.flush();
            } catch (IOException ex) {
                throw new IllegalArgumentException(s);
            }
        }
    }
    try {
        writer.close();
    } catch (IOException ioe) {
        // Ignore exceptions on close.
    }

    toHex(out, buf.toByteArray());

    return out.toString();
}

From source file:hydrograph.ui.common.util.XMLUtil.java

public static void unformatXMLString(ByteArrayOutputStream arrayOutputStream) {
    byte[] bytes = arrayOutputStream.toByteArray();
    try (InputStream inputStream = new ByteArrayInputStream(bytes);
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);) {
        arrayOutputStream.reset();
        String line;/*from ww w  . j a  v a 2  s .c o  m*/
        while ((line = reader.readLine()) != null) {
            arrayOutputStream.write((line.trim() + "\n").getBytes());
        }
    } catch (IOException e) {
        logger.warn("Unable to remove formatting while saving UI XML string", e);
    }
}

From source file:Main.java

/**
 * Encode a path as required by the URL specification (<a href="http://www.ietf.org/rfc/rfc1738.txt">
 * RFC 1738</a>). This differs from <code>java.net.URLEncoder.encode()</code> which encodes according
 * to the <code>x-www-form-urlencoded</code> MIME format.
 *
 * @param path the path to encode//from  w ww .  j  a v  a  2s .co  m
 * @return the encoded path
 */
public static String encodePath(String path) {
    // stolen from org.apache.catalina.servlets.DefaultServlet ;)

    /**
     * Note: Here, ' ' should be encoded as "%20"
     * and '/' shouldn't be encoded.
     */

    int maxBytesPerChar = 10;
    StringBuffer rewrittenPath = new StringBuffer(path.length());
    ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
    OutputStreamWriter writer;
    try {
        writer = new OutputStreamWriter(buf, "UTF8");
    } catch (Exception e) {
        e.printStackTrace();
        writer = new OutputStreamWriter(buf);
    }

    for (int i = 0; i < path.length(); i++) {
        int c = path.charAt(i);
        if (safeCharacters.get(c)) {
            rewrittenPath.append((char) c);
        } else {
            // convert to external encoding before hex conversion
            try {
                writer.write(c);
                writer.flush();
            } catch (IOException e) {
                buf.reset();
                continue;
            }
            byte[] ba = buf.toByteArray();
            for (int j = 0; j < ba.length; j++) {
                // Converting each byte in the buffer
                byte toEncode = ba[j];
                rewrittenPath.append('%');
                int low = (toEncode & 0x0f);
                int high = ((toEncode & 0xf0) >> 4);
                rewrittenPath.append(hexadecimal[high]);
                rewrittenPath.append(hexadecimal[low]);
            }
            buf.reset();
        }
    }
    return rewrittenPath.toString();
}

From source file:Main.java

public static Vector<byte[]> split(int command, byte[] dataToTransport, int chunksize) {
    Vector<byte[]> result = new Vector<byte[]>();
    if (chunksize < 8) {
        throw new RuntimeException("Invalid chunk size");
    }/*w  ww  .  j a  v  a  2s .c  om*/
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int remaining_length = dataToTransport.length;
    int offset = 0;
    int seq = 0;
    boolean firstPacket = true;

    while (remaining_length > 0) {
        int l = 0;
        if (!firstPacket) {
            baos.write(seq);
            l = Math.min(chunksize - 1, remaining_length);
        } else {
            baos.write(command);
            // first packet has the total transport length
            baos.write(remaining_length >> 8);
            baos.write(remaining_length);
            l = Math.min(chunksize - 3, remaining_length);
        }
        baos.write(dataToTransport, offset, l);
        remaining_length -= l;
        offset += l;
        result.add(baos.toByteArray());
        baos.reset();
        if (!firstPacket) {
            seq++;
        }
        firstPacket = false;
    }

    return result;
}

From source file:truelauncher.client.auth.Type2.java

protected static void writeAuthPacket(DataOutputStream dos, PlayerAuthData padata) throws IOException {
    ///*from   w  w w  . ja v  a  2s .  c o m*/
    //fake 1.7.2 handshake packet format.
    //host = authpacket(AuthConnector + nick + token + password)
    //

    //create frame buffer
    ByteArrayOutputStream frame = new ByteArrayOutputStream();
    DataOutputStream frameOut = new DataOutputStream(frame);
    String authpacket = "AuthConnector|" + padata.getNick() + "|" + padata.getToken() + "|"
            + padata.getPassword();
    //write handshake packet to frame
    //write packet id
    writeVarInt(frameOut, 0x00);
    //write protocolVersion
    writeVarInt(frameOut, padata.getProtocolVersion());
    //write authpacket instead of hostname
    writeString(frameOut, authpacket);
    //write port
    frameOut.writeShort(padata.getPort());
    //write state
    writeVarInt(frameOut, 2);
    //now write frame to real socket
    //write length
    writeVarInt(dos, frame.size());
    //write packet
    frame.writeTo(dos);
    frame.reset();
    //close frames
    frameOut.close();
    frame.close();
}

From source file:Main.java

public static Bitmap loadImageFromUrl(String url) {
    ByteArrayOutputStream out = null;
    Bitmap bitmap = null;//from   w  w w  .  j a va 2 s  .co m
    int BUFFER_SIZE = 1024 * 8;
    try {
        BufferedInputStream in = new BufferedInputStream(new URL(url).openStream(), BUFFER_SIZE);
        out = new ByteArrayOutputStream(BUFFER_SIZE);
        int length = 0;
        byte[] tem = new byte[BUFFER_SIZE];
        length = in.read(tem);
        while (length != -1) {
            out.write(tem, 0, length);
            out.flush();
            length = in.read(tem);
        }
        in.close();
        if (out.toByteArray().length != 0) {
            bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size());
        } else {
            out.close();
            return null;
        }
        out.close();
    } catch (OutOfMemoryError e) {

        out.reset();
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = 2;
        opts.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size(), opts);
        return bitmap;
    } catch (Exception e) {

        return bitmap;
    }
    return bitmap;
}