Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:jp.igapyon.selecrawler.SeleCrawlerWebContentTrimmer.java

public void processFile(final File file) throws IOException {
    String contents = FileUtils.readFileToString(file, "UTF-8");
    contents = SimpleHtmlNormalizerUtil.normalizeHtml(contents);

    final Document document = SimpleMyXmlUtil.string2Document(contents);

    final Element elementRoot = document.getDocumentElement();

    processElement(elementRoot);//  ww w. ja  v a 2  s .  c o  m

    try {
        // write xml
        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
        final DOMSource source = new DOMSource(elementRoot);
        final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        final StreamResult target = new StreamResult(outStream);
        transformer.transform(source, target);

        outStream.flush();

        final File fileNormalTrim = new File(file.getParentFile(),
                file.getName() + SeleCrawlerConstants.EXT_SC_NORMAL_TRIM);
        FileUtils.writeByteArrayToFile(fileNormalTrim,
                SimpleHtmlCleanerNormalizerUtil.normalizeHtml(outStream.toByteArray()));
    } catch (TransformerConfigurationException ex) {
        throw new IOException(ex);
    } catch (TransformerFactoryConfigurationError ex) {
        throw new IOException(ex);
    } catch (TransformerException ex) {
        throw new IOException(ex);
    }
}

From source file:io.wcm.handler.media.impl.ImageFileServlet.java

@Override
protected byte[] getBinaryData(Resource resource, SlingHttpServletRequest request) throws IOException {
    // get media app config
    MediaHandlerConfig config = AdaptTo.notNull(request, MediaHandlerConfig.class);

    // check for image scaling parameters
    int width = 0;
    int height = 0;
    String[] selectors = request.getRequestPathInfo().getSelectors();
    if (selectors.length >= 3) {
        width = NumberUtils.toInt(selectors[1]);
        height = NumberUtils.toInt(selectors[2]);
    }/*w ww  .ja  v  a  2  s  .  c  o m*/
    if (width <= 0 || height <= 0) {
        return null;
    }

    // check for cropping parameter
    CropDimension cropDimension = null;
    if (selectors.length >= 4) {
        String cropString = selectors[3];
        try {
            cropDimension = CropDimension.fromCropString(cropString);
        } catch (IllegalArgumentException ex) {
            // ignore
        }
    }

    // if resizing requested rescale via layer
    Layer layer = resource.adaptTo(Layer.class);
    if (layer == null) {
        return null;
    }

    // if required: crop image
    if (cropDimension != null) {
        layer.crop(cropDimension.getRectangle());
    }

    // resize layer
    if (width <= layer.getWidth() && height <= layer.getHeight()) {
        layer.resize(width, height);
    }

    // stream to byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    String contentType = getContentType(resource, request);
    layer.write(contentType, config.getDefaultImageQuality(contentType), bos);
    bos.flush();
    return bos.toByteArray();
}

From source file:com.playhaven.android.diagnostic.test.PHTestCase.java

protected byte[] readFile(File file) throws IOException {
    PlayHaven.d("reading file: " + file.getAbsolutePath());
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
    byte[] buf = new byte[1024];
    int len;/*from   ww  w .j  a v a2  s. c o m*/
    while ((len = in.read(buf)) != -1)
        out.write(buf, 0, len);

    out.flush();
    buf = out.toByteArray();
    in.close();
    out.close();
    return buf;
}

From source file:org.mule.module.http.functional.listener.HttpListenerAttachmentsTestCase.java

private HttpEntity createHttpEntity(boolean useChunkedMode) throws IOException {
    HttpEntity multipartEntity = getMultipartEntity(true);
    if (useChunkedMode) {
        //The only way to send multipart + chunked is putting the multipart content in an output stream entity.
        ByteArrayOutputStream multipartOutput = new ByteArrayOutputStream();
        multipartEntity.writeTo(multipartOutput);
        multipartOutput.flush();
        ByteArrayEntity byteArrayEntity = new ByteArrayEntity(multipartOutput.toByteArray());
        multipartOutput.close();//from  ww w .  j  a  v a  2s  . c  o m

        byteArrayEntity.setChunked(true);
        byteArrayEntity.setContentEncoding(multipartEntity.getContentEncoding());
        byteArrayEntity.setContentType(multipartEntity.getContentType());
        return byteArrayEntity;
    } else {
        return multipartEntity;
    }
}

From source file:com.comcast.video.dawg.show.video.VideoSnap.java

/**
 * Retrieve the image with input image id from cache and stores it in output
 * stream.//ww w .j a  va 2  s  .  c  o m
 *
 * @param imgId
 *            Id of captured image
 * @param deviceId
 *            Device mac address
 * @param response
 *            httpservelet response
 * @param session
 *            http sssion
 * @throws IOException
 */
public void saveSnappedImage(String imgId, String deviceId, HttpServletResponse response, HttpSession session)
        throws IOException {

    String suffixName = getCurrentDateAndTime();
    String fileName = deviceId.toUpperCase() + "_" + suffixName + "." + IMG_FORMAT;

    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

    UniqueIndexedCache<BufferedImage> imgCache = getClientCache(session).getImgCache();

    BufferedImage img = imgCache.getItem(imgId);
    if (img != null) {
        OutputStream stream = response.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(img, IMG_FORMAT, byteArrayOutputStream);
        byteArrayOutputStream.flush();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        stream.write(bytes);
        response.flushBuffer();
    } else {
        LOGGER.error("Could not retrieve the captured image!!!");
    }

}

From source file:com.echopf.ECHOFile.java

/**
 * {@.en Gets a remote file data.}/*from  w w  w.j av  a 2 s.co  m*/
 * {@.ja ??????}
 * @throws ECHOException 
 */
public byte[] getRemoteBytes() throws ECHOException {

    // Get ready a background thread
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<byte[]> communicator = new Callable<byte[]>() {
        @Override
        public byte[] call() throws Exception {
            InputStream is = getRemoteInputStream();

            int nRead;
            byte[] data = new byte[16384];
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();

            return buffer.toByteArray();
        }
    };

    Future<byte[]> future = executor.submit(communicator);

    try {
        return future.get();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt(); // ignore/reset
    } catch (ExecutionException e) {
        Throwable e2 = e.getCause();
        throw new ECHOException(e2);
    }

    return null;
}

From source file:net.sf.dynamicreports.examples.genericelement.openflashchart.OpenFlashChartPdfHandler.java

private byte[] getChartSwf() throws IOException {
    InputStream is = OpenFlashChartPdfHandler.class.getResourceAsStream("open-flash-chart.swf");
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int nRead;//from www. jav  a2 s. c o m
    byte[] data = new byte[16384];

    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }

    buffer.flush();

    return buffer.toByteArray();

}

From source file:apiserver.services.cache.model.Document.java

public void setFile(Object file) throws IOException {
    if (file instanceof File) {
        if (!((File) file).exists() || ((File) file).isDirectory()) {
            throw new IOException("Invalid File Reference");
        }//from   w  ww. ja  v  a 2 s.c o m

        fileName = ((File) file).getName();
        this.file = file;
        this.setFileName(fileName);
        this.contentType = MimeType.getMimeType(fileName);

        byte[] bytes = FileUtils.readFileToByteArray(((File) file));
        this.setFileBytes(bytes);
        this.setSize(new Integer(bytes.length).longValue());
    } else if (file instanceof MultipartFile) {
        fileName = ((MultipartFile) file).getOriginalFilename();
        this.setContentType(MimeType.getMimeType(((MultipartFile) file).getContentType()));
        this.setFileName(((MultipartFile) file).getOriginalFilename());
        this.setFileBytes(((MultipartFile) file).getBytes());
        this.setSize(new Integer(this.getFileBytes().length).longValue());
    } else if (file instanceof BufferedImage) {
        if (fileName == null) {
            fileName = UUID.randomUUID().toString();
        }

        // Convert buffered reader to byte array
        String _mime = this.getContentType().name();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write((BufferedImage) file, _mime, byteArrayOutputStream);
        byteArrayOutputStream.flush();
        byte[] imageBytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        this.setFileBytes(imageBytes);
    }
}

From source file:com.keedio.nifi.processors.azure.blob.FetchAzureBlobObject.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();/*from www. ja v a 2 s.co  m*/
    if (flowFile == null) {
        return;
    }
    final long startNanos = System.nanoTime();

    final String blobObject = context.getProperty(AZURE_STORAGE_BLOB_OBJECT)
            .evaluateAttributeExpressions(flowFile).getValue();

    final AzureBlobConnectionService connectionService = context.getProperty(AZURE_STORAGE_CONTROLLER_SERVICE)
            .asControllerService(AzureBlobConnectionService.class);

    CloudBlobContainer blobContainer;
    try {
        blobContainer = connectionService.getCloudBlobContainerReference();
    } catch (URISyntaxException | InvalidKeyException | StorageException e) {
        getLogger().error("Failed to retrieve Azure Object for {}; routing to failure",
                new Object[] { flowFile, e });
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    CloudBlobWrapper blockBlob = null;
    try {
        blockBlob = new CloudBlobWrapper("overwrite", blobObject, blobContainer);
        //blobContainer.getBlockBlobReference(blobObject);
    } catch (Exception e) {
        getLogger().error("Caught exception while retrieving blob object reference", e);
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    InputStream blockBlobStream = null;
    ByteArrayOutputStream outputStream = null;
    try {
        outputStream = new ByteArrayOutputStream();
        blockBlob.download(outputStream);
        outputStream.flush();

        blockBlobStream = new ByteArrayInputStream(outputStream.toByteArray());

        flowFile = session.importFrom(blockBlobStream, flowFile);
    } catch (IOException | StorageException e) {
        getLogger().error("Caught exception while retrieving blob object", e);
    } finally {
        IOUtils.closeQuietly(blockBlobStream);
        IOUtils.closeQuietly(outputStream);
    }

    final Map<String, String> attributes = new HashMap<>();

    copyAttributes(connectionService.getContainerName(), blobObject, blockBlob, attributes);

    if (!attributes.isEmpty()) {
        flowFile = session.putAllAttributes(flowFile, attributes);
    }

    session.transfer(flowFile, REL_SUCCESS);

    final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
    getLogger().info("Successfully retrieved Blob Object for {} in {} millis; routing to success",
            new Object[] { flowFile, transferMillis });
    session.getProvenanceReporter().fetch(flowFile, blockBlob.toString(), transferMillis);
}

From source file:com.k42b3.kadabra.handler.System.java

public byte[] getContent(String path) throws Exception {
    logger.info(basePath + "/" + path);

    InputStream fis = new FileInputStream(basePath + "/" + path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    byte[] buf = new byte[1024];
    int len;//  w  ww  .  jav  a  2  s . c o  m

    len = fis.read(buf);

    while (len != -1) {
        baos.write(buf, 0, len);

        len = fis.read(buf);
    }

    baos.flush();
    baos.close();

    return baos.toByteArray();
}