Example usage for java.io ByteArrayOutputStream writeTo

List of usage examples for java.io ByteArrayOutputStream writeTo

Introduction

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

Prototype

public synchronized void writeTo(OutputStream out) throws IOException 

Source Link

Document

Writes the complete contents of this ByteArrayOutputStream to the specified output stream argument, as if by calling the output stream's write method using out.write(buf, 0, count) .

Usage

From source file:Main.java

public static File saveBitmapToExternal(Bitmap bitmap, String targetFileDirPath) {
    if (bitmap == null || bitmap.isRecycled()) {
        return null;
    }//from w  w w  .  j  a va2s  .c om

    File targetFileDir = new File(targetFileDirPath);
    if (!targetFileDir.exists() && !targetFileDir.mkdirs()) {
        return null;
    }

    File targetFile = new File(targetFileDir, UUID.randomUUID().toString());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(targetFile);
        baos.writeTo(fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            baos.flush();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (fos != null) {
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return targetFile;
}

From source file:org.apache.jetspeed.util.Base64.java

public static String encodeAsString(byte[] plaindata) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream inStream = new ByteArrayOutputStream();

    inStream.write(plaindata, 0, plaindata.length);

    // pad/*from   w w  w .  ja  va 2  s . c  o  m*/
    if ((plaindata.length % 3) == 1) {
        inStream.write(0);
        inStream.write(0);
    } else if ((plaindata.length % 3) == 2) {
        inStream.write(0);
    }

    inStream.writeTo(MimeUtility.encode(out, "base64"));
    return out.toString();
}

From source file:org.saiku.reporting.core.GenerateTest.java

public static void storeReport(MasterReport masterReport) {

    final ByteArrayOutputStream prptContent = new ByteArrayOutputStream();
    try {/*from   w  ww  . j a  v a2s  .  co  m*/
        BundleWriter.writeReportToZipStream(masterReport, prptContent);

        OutputStream outputStream = new FileOutputStream("c:/tmp/xtab.prpt");
        prptContent.writeTo(outputStream);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (BundleWriterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ContentIOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.esxx.Response.java

public static void writeObject(Object object, ContentType ct, OutputStream out) throws IOException {

    if (object == null) {
        return;//from   w ww  .  ja va 2  s.  c o  m
    }

    // Unwrap wrapped objects
    object = JS.toJavaObject(object);

    // Convert complex types to primitive types
    if (object instanceof Node) {
        ESXX esxx = ESXX.getInstance();

        if (ct.match("message/rfc822")) {
            try {
                String xml = esxx.serializeNode((Node) object);
                org.esxx.xmtp.XMTPParser xmtpp = new org.esxx.xmtp.XMTPParser();
                javax.mail.Message msg = xmtpp.convertMessage(new StringReader(xml));
                object = new ByteArrayOutputStream();
                msg.writeTo(new FilterOutputStream((OutputStream) object) {
                    @Override
                    public void write(int b) throws IOException {
                        if (b == '\r') {
                            return;
                        } else if (b == '\n') {
                            out.write('\r');
                            out.write('\n');
                        } else {
                            out.write(b);
                        }
                    }
                });
            } catch (javax.xml.stream.XMLStreamException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            } catch (javax.mail.MessagingException ex) {
                throw new ESXXException("Failed to serialize Node as message/rfc822:" + ex.getMessage(), ex);
            }
        } else {
            object = esxx.serializeNode((Node) object);
        }
    } else if (object instanceof Scriptable) {
        if (ct.match("application/x-www-form-urlencoded")) {
            String cs = Parsers.getParameter(ct, "charset", "UTF-8");

            object = StringUtil.encodeFormVariables(cs, (Scriptable) object);
        } else if (ct.match("text/csv")) {
            object = jsToCSV(ct, (Scriptable) object);
        } else {
            object = jsToJSON(object).toString();
        }
    } else if (object instanceof byte[]) {
        object = new ByteArrayInputStream((byte[]) object);
    } else if (object instanceof File) {
        object = new FileInputStream((File) object);
    }

    // Serialize primitive types
    if (object instanceof ByteArrayOutputStream) {
        ByteArrayOutputStream bos = (ByteArrayOutputStream) object;

        bos.writeTo(out);
    } else if (object instanceof ByteBuffer) {
        // Write result as-is to output stream
        WritableByteChannel wbc = Channels.newChannel(out);
        ByteBuffer bb = (ByteBuffer) object;

        bb.rewind();

        while (bb.hasRemaining()) {
            wbc.write(bb);
        }

        wbc.close();
    } else if (object instanceof InputStream) {
        IO.copyStream((InputStream) object, out);
    } else if (object instanceof Reader) {
        // Write stream as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);

        IO.copyReader((Reader) object, ow);
    } else if (object instanceof String) {
        // Write string as-is, using the specified charset (if present)
        String cs = Parsers.getParameter(ct, "charset", "UTF-8");
        Writer ow = new OutputStreamWriter(out, cs);
        ow.write((String) object);
        ow.flush();
    } else if (object instanceof RenderedImage) {
        Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(ct.getBaseType());

        if (!i.hasNext()) {
            throw new ESXXException("No ImageWriter available for " + ct.getBaseType());
        }

        ImageWriter writer = i.next();

        writer.setOutput(ImageIO.createImageOutputStream(out));
        writer.write((RenderedImage) object);
    } else {
        throw new UnsupportedOperationException("Unsupported object class type: " + object.getClass());
    }
}

From source file:org.openlmis.report.exporter.JasperReportExporter.java

/**
 * @param response/*from   w  w w  .j  a v  a 2s. c  o  m*/
 * @param byteArrayOutputStream
 */
private static void writeToServletOutputStream(HttpServletResponse response,
        ByteArrayOutputStream byteArrayOutputStream) {
    ServletOutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
        byteArrayOutputStream.writeTo(outputStream);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (outputStream != null) {
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.jbpm.bpel.integration.soap.SoapUtilTest.java

private static SOAPMessage writeAndRead(SOAPMessage soapMessage) throws SOAPException, IOException {
    // write to memory sink
    ByteArrayOutputStream soapSink = new ByteArrayOutputStream();
    soapMessage.writeTo(soapSink);/*ww  w . j av a2s  .c om*/
    soapSink.writeTo(System.out);
    System.out.println();
    // read from memory source
    return MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(soapSink.toByteArray()));
}

From source file:com.github.ipaas.ideploy.agent.util.SVNUtil.java

/**
 *  //w  ww . ja  va 2  s .  co m
 * @param repository  svn repos
 * @param remotePath  svn
 * @param savePath    ??
 * @param revision    
 * @throws Exception
 */
private static void getFile(SVNRepository repository, String remotePath, File savePath, long revision)
        throws Exception {
    //
    FileUtils.deleteQuietly(savePath);

    //
    savePath.getParentFile().mkdirs();

    //
    savePath.createNewFile();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileOutputStream fos = new FileOutputStream(savePath);
    try {
        repository.getFile(remotePath, revision, null, baos);
        baos.writeTo(fos);
    } finally {
        if (fos != null) {
            fos.close();
        }
        if (baos != null) {
            baos.close();
        }
    }
}

From source file:org.eclipse.che.api.vfs.util.ZipContent.java

public static ZipContent of(InputStream in) throws IOException {
    java.io.File file = null;// w  ww  . ja va 2s  .com
    byte[] inMemory = null;

    int count = 0;
    ByteArrayOutputStream inMemorySpool = new ByteArrayOutputStream(KEEP_IN_MEMORY_THRESHOLD);

    int bytes;
    final byte[] buff = new byte[COPY_BUFFER_SIZE];
    while (count <= KEEP_IN_MEMORY_THRESHOLD && (bytes = in.read(buff)) != -1) {
        inMemorySpool.write(buff, 0, bytes);
        count += bytes;
    }

    InputStream spool;
    if (count > KEEP_IN_MEMORY_THRESHOLD) {
        file = java.io.File.createTempFile("import", ".zip");
        try (FileOutputStream fileSpool = new FileOutputStream(file)) {
            inMemorySpool.writeTo(fileSpool);
            while ((bytes = in.read(buff)) != -1) {
                fileSpool.write(buff, 0, bytes);
            }
        }
        spool = new FileInputStream(file);
    } else {
        inMemory = inMemorySpool.toByteArray();
        spool = new ByteArrayInputStream(inMemory);
    }

    try (CountingInputStream compressedDataCounter = new CountingInputStream(spool);
            ZipInputStream zip = new ZipInputStream(compressedDataCounter)) {
        try (CountingInputStream uncompressedDataCounter = new CountingInputStream(zip)) {
            ZipEntry zipEntry;
            while ((zipEntry = zip.getNextEntry()) != null) {
                if (!zipEntry.isDirectory()) {
                    while (uncompressedDataCounter.read(buff) != -1) {
                        long uncompressedBytes = uncompressedDataCounter.getByteCount();
                        if (uncompressedBytes > ZIP_THRESHOLD) {
                            long compressedBytes = compressedDataCounter.getByteCount();
                            if (uncompressedBytes > (ZIP_RATIO * compressedBytes)) {
                                throw new IOException("Zip bomb detected");
                            }
                        }
                    }
                }
            }
        }

        return new ZipContent(
                inMemory == null ? new DeleteOnCloseFileInputStream(file) : new ByteArrayInputStream(inMemory));
    }
}

From source file:Main.java

private static void writeJpegCompressedImage(BufferedImage image, String outFile) throws IOException {
    float qualityFloat = 1f;
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    ImageWriter imgWriter = ImageIO.getImageWritersByFormatName("jpg").next();
    ImageOutputStream ioStream = ImageIO.createImageOutputStream(outStream);
    imgWriter.setOutput(ioStream);//from  www .j ava 2s  .  c o  m

    JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(Locale.getDefault());
    jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    jpegParams.setCompressionQuality(qualityFloat);

    imgWriter.write(null, new IIOImage(image, null, null), jpegParams);

    ioStream.flush();
    ioStream.close();
    imgWriter.dispose();

    OutputStream outputStream = new FileOutputStream(outFile);
    outStream.writeTo(outputStream);

}

From source file:org.eclipse.che.api.vfs.server.util.ZipContent.java

public static ZipContent newInstance(InputStream in) throws IOException {
    java.io.File file = null;//from   w w  w. j  a  v  a2  s.c  om
    byte[] inMemory = null;

    int count = 0;
    ByteArrayOutputStream inMemorySpool = new ByteArrayOutputStream(BUFFER);

    int bytes;
    final byte[] buff = new byte[BUFFER_SIZE];
    while (count <= BUFFER && (bytes = in.read(buff)) != -1) {
        inMemorySpool.write(buff, 0, bytes);
        count += bytes;
    }

    InputStream spool;
    if (count > BUFFER) {
        file = java.io.File.createTempFile("import", ".zip");
        try (FileOutputStream fileSpool = new FileOutputStream(file)) {
            inMemorySpool.writeTo(fileSpool);
            while ((bytes = in.read(buff)) != -1) {
                fileSpool.write(buff, 0, bytes);
            }
        }
        spool = new FileInputStream(file);
    } else {
        inMemory = inMemorySpool.toByteArray();
        spool = new ByteArrayInputStream(inMemory);
    }

    // Counts numbers of compressed data.
    try (CountingInputStream compressedCounter = new CountingInputStream(spool);
            ZipInputStream zip = new ZipInputStream(compressedCounter)) {

        // Counts number of uncompressed data.
        CountingInputStream uncompressedCounter = new CountingInputStream(zip) {
            @Override
            public int read() throws IOException {
                int i = super.read();
                checkCompressionRatio();
                return i;
            }

            @Override
            public int read(byte[] b, int off, int len) throws IOException {
                int i = super.read(b, off, len);
                checkCompressionRatio();
                return i;
            }

            @Override
            public int read(byte[] b) throws IOException {
                int i = super.read(b);
                checkCompressionRatio();
                return i;
            }

            @Override
            public long skip(long length) throws IOException {
                long i = super.skip(length);
                checkCompressionRatio();
                return i;
            }

            private void checkCompressionRatio() {
                long uncompressedBytes = getByteCount(); // number of uncompressed bytes
                if (uncompressedBytes > ZIP_THRESHOLD) {
                    long compressedBytes = compressedCounter.getByteCount(); // number of compressed bytes
                    if (uncompressedBytes > (ZIP_RATIO * compressedBytes)) {
                        throw new RuntimeException("Zip bomb detected. ");
                    }
                }
            }
        };

        ZipEntry zipEntry;
        while ((zipEntry = zip.getNextEntry()) != null) {
            if (!zipEntry.isDirectory()) {
                while (uncompressedCounter.read(buff) != -1) {
                    // Read full data from stream to be able detect zip-bomb.
                }
            }
        }

        return new ZipContent(
                inMemory != null ? new ByteArrayInputStream(inMemory) : new DeleteOnCloseFileInputStream(file),
                file == null);
    }
}