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:com.mirth.connect.connectors.jms.JmsMessageUtils.java

public static Object getObjectForMessage(Message source) throws JMSException {
    Object result = null;/*from ww w  .java2 s .c om*/
    try {
        if (source instanceof ObjectMessage) {
            result = ((ObjectMessage) source).getObject();
        } else if (source instanceof MapMessage) {
            Hashtable map = new Hashtable();
            MapMessage m = (MapMessage) source;

            for (Enumeration e = m.getMapNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                Object obj = m.getObject(name);
                map.put(name, obj);
            }

            result = map;
        } else if (source instanceof javax.jms.BytesMessage) {

            javax.jms.BytesMessage bm = (javax.jms.BytesMessage) source;
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();

            byte[] buffer = new byte[1024 * 4];
            int len = 0;
            bm.reset();
            while ((len = bm.readBytes(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            result = baos.toByteArray();
            baos.close();
            if (result != null) {
                if (logger.isDebugEnabled())
                    logger.debug("JMSToObject: extracted " + ((byte[]) result).length
                            + " bytes from JMS BytesMessage");
            }
        } else if (source instanceof TextMessage) {
            result = ((TextMessage) source).getText();

        } else if (source instanceof BytesMessage) {
            byte[] bytes = getBytesFromMessage(source);
            return CompressionHelper.uncompressByteArray(bytes);
        } else if (source instanceof StreamMessage) {

            StreamMessage sm = (javax.jms.StreamMessage) source;

            result = new java.util.Vector();
            try {
                Object obj = null;
                while ((obj = sm.readObject()) != null) {
                    ((java.util.Vector) result).addElement(obj);
                }
            } catch (MessageEOFException eof) {
            } catch (Exception e) {
                throw new JMSException("Failed to extract information from JMS Stream Message: " + e);
            }
        } else {
            result = source;
        }
    } catch (Exception e) {
        throw new JMSException("Failed to transform message: " + e.getMessage());
    }
    return result;
}

From source file:Main.java

public static String getAssetString(Context ct, String name) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int ch = -1;//from   w  w w.j a  va2s.c  o  m
    byte[] byteData = null;
    InputStream is = null;
    try {
        is = ct.getAssets().open(name);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Read the entire asset into a local byte buffer.  
    try {
        while ((ch = is.read(buf)) != -1) {
            baos.write(buf, 0, ch);//
        }
        byteData = baos.toByteArray();
        baos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String data = null;
    try {
        data = new String(byteData, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return data;
}

From source file:cn.sharesdk.analysis.net.NetworkHelper.java

public static String Base64Gzip(String str) {
    ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    String result = null;/*from  w  w  w.  jav a2  s .co  m*/
    // gzip
    GZIPOutputStream gos;
    try {
        gos = new GZIPOutputStream(baos);
        int count;
        byte data[] = new byte[1024];
        while ((count = bais.read(data, 0, 1024)) != -1) {
            gos.write(data, 0, count);
        }
        gos.finish();
        gos.close();

        byte[] output = baos.toByteArray();
        baos.flush();
        baos.close();
        bais.close();

        result = Base64.encodeToString(output, Base64.NO_WRAP);

    } catch (IOException e) {
        e.printStackTrace();
        Ln.e("NetworkHelper", "Base64Gzip == >>", e);
    }

    //Ln.i("after base64gizp", result);
    return result;
}

From source file:net.sf.ehcache.distribution.PayloadUtil.java

/**
 * The fastest Ungzip implementation. See PageInfoTest in ehcache-constructs.
 * A high performance implementation, although not as fast as gunzip3.
 * gunzips 100000 of ungzipped content in 9ms on the reference machine.
 * It does not use a fixed size buffer and is therefore suitable for arbitrary
 * length arrays.//from   w  w  w .ja  v  a2s. c o  m
 *
 * @param gzipped
 * @return a plain, uncompressed byte[]
 */
public static byte[] ungzip(final byte[] gzipped) {
    byte[] ungzipped = new byte[0];
    try {
        final GZIPInputStream inputStream = new GZIPInputStream(new ByteArrayInputStream(gzipped));
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(gzipped.length);
        final byte[] buffer = new byte[PayloadUtil.MTU];
        int bytesRead = 0;
        while (bytesRead != -1) {
            bytesRead = inputStream.read(buffer, 0, PayloadUtil.MTU);
            if (bytesRead != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
        }
        ungzipped = byteArrayOutputStream.toByteArray();
        inputStream.close();
        byteArrayOutputStream.close();
    } catch (IOException e) {
        LOG.fatal("Could not ungzip. Heartbeat will not be working. " + e.getMessage());
    }
    return ungzipped;
}

From source file:com.ebay.erl.mobius.util.SerializableUtil.java

public final static String serializeToBase64(Serializable obj) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = null;
    try {//  w ww .  ja  va2  s  .  c  o m
        oos = new ObjectOutputStream(bos);
        oos.writeObject(obj);
        oos.flush();
        oos.close();

        String result = new String(Base64.encodeBase64(bos.toByteArray()), "UTF-8");
        return result;
    } catch (NotSerializableException e) {
        throw new IllegalArgumentException("Cannot serialize " + obj.getClass().getCanonicalName(), e);
    } finally {
        try {
            bos.close();
        } catch (Throwable e) {
            e = null;
        }

        try {
            if (oos != null)
                oos.close();
        } catch (Throwable e) {
            e = null;
        }
    }
}

From source file:com.runwaysdk.controller.ErrorUtility.java

private static String decompress(String message) {
    try {/*from www  .ja  v  a2s. c om*/
        byte[] bytes = Base64.decode(message);

        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        BufferedInputStream bufis = new BufferedInputStream(new GZIPInputStream(bis));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = bufis.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        String retval = bos.toString();
        bis.close();
        bufis.close();
        bos.close();
        return retval;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static byte[] readFile(File file) throws IOException {
    if (!file.exists()) {
        throw new IOException("not crete file=" + file.getAbsolutePath());
    }/*  w w w  . ja v  a2 s  .com*/
    FileInputStream fileInputStream = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    try {
        fileInputStream = new FileInputStream(file);
        byteArrayOutputStream = new ByteArrayOutputStream(64);
        int length = 0;
        byte[] buffer = new byte[1024];
        while ((length = fileInputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, length);
        }
        return byteArrayOutputStream.toByteArray();
    } finally {
        if (fileInputStream != null) {
            fileInputStream.close();
        }
        if (byteArrayOutputStream != null) {
            byteArrayOutputStream.close();
        }
    }
}

From source file:XMLUtils.java

public static String toString(Source source, Properties props) throws TransformerException, IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    StreamResult sr = new StreamResult(bos);
    Transformer trans = newTransformer();
    if (props == null) {
        props = new Properties();
        props.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
    }//from  w  w w  . j  av a  2s. c o m
    trans.setOutputProperties(props);
    trans.transform(source, sr);
    bos.close();
    return bos.toString();
}

From source file:edu.stanford.junction.addon.JSONObjWrapper.java

private static String decompressString(String str) {
    byte[] compressedData = Base64.decode(str);
    // Create the decompressor and give it the data to compress 
    Inflater decompressor = new Inflater();
    decompressor.setInput(compressedData);
    // Create an expandable byte array to hold the decompressed data 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);
    // Decompress the data 
    byte[] buf = new byte[1024];
    while (!decompressor.finished()) {
        try {/*from  w ww .  j a  va2 s .  c  om*/
            int count = decompressor.inflate(buf);
            bos.write(buf, 0, count);
        } catch (DataFormatException e) {
        }
    }

    try {
        bos.close();
    } catch (IOException e) {
    }

    // Get the decompressed data 
    byte[] decompressedData = bos.toByteArray();
    try {
        return new String(decompressedData, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return new String(decompressedData);
    }
}

From source file:com.qualogy.qafe.bind.core.application.io.ResourceMerger.java

@SuppressWarnings("unchecked")
public static ApplicationMapping merge(Class mergeableClassName, List<ApplicationMapping> concreteMappings,
        List<FileLocation> fileLocations, String appName, String root, boolean autoScanRoot,
        boolean recursiveScan, boolean validating) {

    logger.log(Level.FINE, "Start merging application mappings for application [{0}]", appName);

    ApplicationMapping applicationMapping = null;

    //boolean to see whether a concrete and/or location is/are set
    boolean noMappings = ((concreteMappings == null || concreteMappings.isEmpty())
            && (fileLocations == null || fileLocations.isEmpty()));

    ByteArrayInputStream in = null;
    try {//w w  w . jav a 2 s. c om

        if (concreteMappings != null) {
            for (ApplicationMapping mapping : concreteMappings) {
                if (applicationMapping != null)
                    throw new LoadFailedException(appName,
                            "loading two application-mappings through application-context without resource is not yet supported");
                if ((fileLocations == null || fileLocations.isEmpty())) {
                    applicationMapping = mapping;
                } else {
                    ByteArrayOutputStream out = null;
                    try {
                        out = new ByteArrayOutputStream();
                        new Writer().write(mapping, out, false);
                        byte[] bytes = out.toByteArray();
                        in = new ByteArrayInputStream(bytes);
                    } finally {
                        if (out != null)
                            try {
                                out.close();
                            } catch (IOException e) {
                                logger.log(Level.SEVERE,
                                        "Error occured while closing outputstream for application: " + appName,
                                        e);
                            }
                    }
                }
            }
        }

        if (noMappings || fileLocations != null) {
            List<URI> filePaths = new ArrayList<URI>();
            if (noMappings && autoScanRoot) {
                logger.warning("No application-mapping found for context, using root [" + root
                        + "] to scan for application-mapping (since auto-scan-root is set to true)");
                filePaths.add(new FileLocation(root, "").toURI());
            } else if (noMappings && !autoScanRoot) {
                throw new LoadFailedException(appName,
                        "No application-mapping found and auto-scan is false (default), cannot startup without application-mapping");
            } else if (fileLocations != null) {
                for (FileLocation location : fileLocations) {
                    location.setRoot(root);
                    URI path = location.toURI();
                    if (path == null)
                        throw new BindException(
                                "No file found at mapping file location [" + location.toString() + "]");
                    filePaths.add(path);
                }
            }

            logger.info("Start reading application mappings for application [" + appName + "] from ["
                    + filePaths + "]");

            try {
                applicationMapping = (ApplicationMapping) new Reader(ApplicationMapping.class).read(in,
                        filePaths, root, recursiveScan);
            } catch (RuntimeException e) {
                String message = e != null ? e.getMessage() : null;
                throw new LoadFailedException(appName, message, e);
            }

            logger.info("Finished reading application mappings for application [" + appName + "]");
        }
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Error occured while closing inputstream", e);
        }
    }

    return applicationMapping;
}