Example usage for java.io ByteArrayOutputStream close

List of usage examples for java.io ByteArrayOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayOutputStream has no effect.

Usage

From source file:it.polito.elite.dog.core.library.model.DeviceStatus.java

/**
 * Serialize a DeviceStatus into a String using a byte encoding
 * @param object//from ww w .ja v a  2s  .  c  o  m
 *          a DeviceStatus ready for serialization
 * @return a byte encoded String of a DeviceStatus
 * @throws IOException 
 */
public static String serializeToString(DeviceStatus object) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream encoder = new ObjectOutputStream(baos);
    //serialize the DeviceStatus
    encoder.writeObject(object);
    //flush and close everything
    encoder.flush();
    baos.flush();
    encoder.close();
    baos.close();
    return new String(Base64.encodeBase64(baos.toByteArray()));
}

From source file:com.mirth.connect.connectors.jms.JmsMessageUtils.java

/**
 * @param message//  www .j av a2  s . c  o  m
 *            the message to receive the bytes from. Note this only works
 *            for TextMessge, ObjectMessage, StreamMessage and BytesMessage.
 * @return a byte array corresponding with the message payload
 * @throws JMSException
 *             if the message can't be read or if the message passed is a
 *             MapMessage
 * @throws java.io.IOException
 *             if a failiare occurs while stream and converting the message
 *             data
 */
public static byte[] getBytesFromMessage(Message message) throws JMSException, IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024 * 2];
    int len;

    if (message instanceof BytesMessage) {
        BytesMessage bMsg = (BytesMessage) message;
        // put message in read-only mode
        bMsg.reset();
        while ((len = bMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
    } else if (message instanceof StreamMessage) {
        StreamMessage sMsg = (StreamMessage) message;
        sMsg.reset();
        while ((len = sMsg.readBytes(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
    } else if (message instanceof ObjectMessage) {
        ObjectMessage oMsg = (ObjectMessage) message;
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(bs);
        os.writeObject(oMsg.getObject());
        os.flush();
        baos.write(bs.toByteArray());
        os.close();
        bs.close();
    } else if (message instanceof TextMessage) {
        TextMessage tMsg = (TextMessage) message;
        baos.write(tMsg.getText().getBytes());
    } else {
        throw new JMSException("Cannot get bytes from Map Message");
    }

    baos.flush();
    byte[] bytes = baos.toByteArray();
    baos.close();
    return bytes;
}

From source file:outfox.dict.contest.util.FileUtils.java

/**
 * /*from   w  w  w .j  av  a  2 s  .c o m*/
 * @param file
 * @return
 */
public static byte[] getBytesFromFile(File file) {
    byte[] byteArray = null;
    try {
        if (file == null) {
            return null;
        }
        FileInputStream in = new FileInputStream(file);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] b = new byte[4096];
        int n;
        while ((n = in.read(b)) != -1) {
            out.write(b, 0, n);
        }
        byteArray = out.toByteArray();
        in.close();
        out.close();
    } catch (IOException e) {
        LOG.error("FileUtils.getBytesFromFile error...", e);
    }
    return byteArray;
}

From source file:Base64Decoder.java

/**
 * Returns the decoded form of the given encoded string.
 * //from w w  w  .  j a  v  a 2 s. c om
 * @param encoded
 *            the string to decode
 * @return the decoded form of the encoded string
 */
public static String decode(String encoded) {
    byte[] bytes = null;
    try {
        bytes = encoded.getBytes("8859_1");
    } catch (UnsupportedEncodingException ignored) {
    }

    Base64Decoder in = new Base64Decoder(new ByteArrayInputStream(bytes));

    ByteArrayOutputStream out = new ByteArrayOutputStream((int) (bytes.length * 0.67));

    try {
        byte[] buf = new byte[4 * 1024]; // 4K buffer
        int bytesRead;
        while ((bytesRead = in.read(buf)) != -1) {
            out.write(buf, 0, bytesRead);
        }
        out.close();

        return out.toString("8859_1");
    } catch (IOException ignored) {
        return null;
    }
}

From source file:com.wareninja.opensource.gravatar4android.common.Utils.java

public static byte[] downloadImage_alternative2(String url) throws GenericException {

    byte[] imageData = null;
    try {//w  w  w .j  ava 2 s  .c o  m

        URLConnection connection = new URL(url).openConnection();

        InputStream stream = connection.getInputStream();

        //BufferedInputStream in=new BufferedInputStream(stream);//default 8k buffer
        BufferedInputStream in = new BufferedInputStream(stream, 10240);// 10k=10240, 2x8k=16384
        ByteArrayOutputStream out = new ByteArrayOutputStream(10240);
        int read;
        byte[] b = new byte[4096];

        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }

        out.flush();
        out.close();

        imageData = out.toByteArray();
    } catch (FileNotFoundException e) {
        return null;
    } catch (Exception e) {

        Log.w(TAG, "Exc=" + e);
        throw new GenericException(e);
    }

    return imageData;
}

From source file:com.moss.greenshell.wizard.catastrophe.PostMortemScreen.java

public static void submitErrorReport(final Throwable cause, final ErrorReportDecorator... decorators)
        throws Exception {

    List<ErrorReportChunk> chunks = new LinkedList<ErrorReportChunk>();

    try {/*from   ww  w .  ja  v a  2  s. co m*/
        if (cause instanceof InternalErrorException) {
            InternalErrorException ie = (InternalErrorException) cause;
            ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                    ie.id().getBytes("UTF8"));
            chunks.add(chunk);
        } else if (cause instanceof SOAPFaultException) {
            SOAPFaultException soapFault = (SOAPFaultException) cause;
            String content = soapFault.getFault().getFirstChild().getTextContent();
            String prefix = "Internal Service Error Occurred: ";
            if (content.startsWith(prefix)) {
                String id = content.substring(prefix.length());
                ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                        id.getBytes("UTF8"));
                chunks.add(chunk);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }

    // STACK TRACE
    ByteArrayOutputStream stackBytes = new ByteArrayOutputStream();
    PrintStream stackPrintStream = new PrintStream(stackBytes);
    cause.printStackTrace(stackPrintStream);
    stackPrintStream.close();
    stackBytes.close();

    ErrorReportChunk chunk = new ErrorReportChunk("stack trace", "text/plain", stackBytes.toByteArray());
    chunks.add(chunk);

    // THREAD DUMP

    ByteArrayOutputStream dumpBytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(dumpBytes);
    Map<Thread, StackTraceElement[]> traceMap = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> next : traceMap.entrySet()) {
        out.println();
        out.println(next.getKey().getName());
        for (StackTraceElement line : next.getValue()) {
            String className = emptyIfNull(line.getClassName());
            String methodName = emptyIfNull(line.getMethodName());
            String fileName = emptyIfNull(line.getFileName());

            out.println("    " + className + "." + methodName + " (" + fileName + " line "
                    + line.getLineNumber() + ")");
        }
    }
    out.flush();
    out.close();
    ErrorReportChunk stackDump = new ErrorReportChunk("thread dump", "text/plain", dumpBytes.toByteArray());
    chunks.add(stackDump);

    // SYSTEM PROPERTIES
    ByteArrayOutputStream propsBytes = new ByteArrayOutputStream();
    PrintStream propsOut = new PrintStream(propsBytes);
    for (Map.Entry<Object, Object> next : System.getProperties().entrySet()) {
        propsOut.println(" " + next.getKey() + "=" + next.getValue());
    }
    propsOut.flush();
    propsOut.close();
    chunks.add(new ErrorReportChunk("system properties", "text/plain", propsBytes.toByteArray()));

    // LOCAL CLOCK
    chunks.add(new ErrorReportChunk("local clock", "text/plain", new DateTime().toString().getBytes()));

    // NETWORKING
    StringBuffer networking = new StringBuffer();
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        networking.append("INTERFACE: " + iface.getName() + " (" + iface.getDisplayName() + ")\n");
        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            networking.append("  Address:" + address.getHostAddress() + "\n");
            networking.append("      Cannonical Host Name: " + address.getCanonicalHostName() + "\n");
            networking.append("                 Host Name: " + address.getHostName() + "\n");
        }
    }
    chunks.add(new ErrorReportChunk("network configuration", "text/plain", networking.toString().getBytes()));

    // DECORATORS
    if (decorators != null) {
        for (ErrorReportDecorator decorator : decorators) {
            chunks.addAll(decorator.makeChunks(cause));
        }
    }
    ErrorReport report = new ErrorReport(chunks);
    Reporter reporter = new Reporter();
    ReportId id = reporter.submitReport(report);
}

From source file:Main.java

public static byte[] decompress(byte[] data, int off, int len) {
    byte[] output = null;
    Inflater decompresser = new Inflater();
    decompresser.reset();/*from  w  w  w .  j av  a  2  s  .co m*/
    //      decompresser.setInput(data);
    decompresser.setInput(data, off, len);

    ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
    try {
        byte[] buf = new byte[1024];
        while (!decompresser.finished()) {
            int i = decompresser.inflate(buf);
            o.write(buf, 0, i);
        }
        output = o.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            o.close();
            decompresser.end();
        } catch (Exception e) {
        }
    }

    return output;
}

From source file:com.mnt.base.util.HttpUtil.java

public static String readData(InputStream in) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int len = 0;//from  w  w w  .  ja v a 2s . c om
    byte[] buff = new byte[1024];
    while ((len = in.read(buff)) > 0) {
        bos.write(buff, 0, len);
    }

    String result = bos.toString();
    bos.close();

    return result;
}

From source file:Main.java

public static byte[] zlibDecompress(byte[] data, int offset, int length) {
    byte[] output = null;

    Inflater decompresser = new Inflater();
    decompresser.reset();//from   www  .j  a v a2 s  .co  m
    try {
        decompresser.setInput(data, offset, length);
    } catch (Exception e) {
        return null;
    }

    ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
    try {
        byte[] buf = new byte[1024];
        while (!decompresser.finished()) {
            int i = decompresser.inflate(buf);
            o.write(buf, 0, i);
        }
        output = o.toByteArray();
    } catch (Exception e) {
        output = data;
        e.printStackTrace();
    } finally {
        try {
            o.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    decompresser.end();
    return output;
}

From source file:Main.java

/**
 * This class converts a DOM representation node to text.
 * @param node/*  ww w .j  ava  2 s  .  c  om*/
 * @return
 * @throws Exception
 */
public static final String toText(Node node) throws Exception {
    String ret = null;
    try {
        // Transform the DOM represent to text
        ByteArrayOutputStream xmlstr = new ByteArrayOutputStream();
        DOMSource source = new DOMSource(node);
        //source.setNode(node);

        StreamResult result = new StreamResult(xmlstr);
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        trans.transform(source, result);

        xmlstr.close();

        ret = new String(xmlstr.toByteArray());

        if ((node instanceof Document) == false) {
            // Strip off any <?xml> header
            int index = ret.indexOf("<?xml");
            if (index != -1) {
                index = ret.indexOf("<", 1);
                if (index != -1) {
                    ret = ret.substring(index);
                } else {
                    index = ret.indexOf("?>");
                    if (index != -1) {
                        index += 2;

                        // Remove any trailing whitespaces after XML header
                        while (index < ret.length() && Character.isWhitespace(ret.charAt(index))) {
                            index++;
                        }

                        ret = ret.substring(index);
                    }
                }
            }
        }

    } catch (Exception e) {
        throw new Exception("Failed to transform DOM representation into text", e);
    }
    if (ret != null) {
        return format(ret);
    }
    return ret;
}