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:org.openxdata.server.servlet.WMDownloadServlet.java

private void downloadForms(HttpServletResponse response, int studyId) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    formDownloadService.downloadForms(studyId, dos, "", "");
    baos.flush();
    dos.flush();/* w w  w  .  j a va  2 s. c o  m*/
    byte[] data = baos.toByteArray();
    baos.close();
    dos.close();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

    PrintWriter out = response.getWriter();
    out.println("<study>");

    try {
        dis.readByte(); //reads the size of the studies

        while (true) {
            String value = dis.readUTF();
            out.println("<form>" + value + "</form>");
        }
    } catch (EOFException exe) {
        //exe.printStackTrace();
    }

    out.println("</study>");
    out.flush();
    dis.close();
}

From source file:com.pursuer.reader.easyrss.network.SubscriptionDataSyncer.java

private void syncSubscriptionIcons() throws DataSyncerException {
    final Context context = dataMgr.getContext();
    if (!NetworkUtils.checkSyncingNetworkStatus(context, networkConfig)) {
        return;//w  w  w. java  2  s.  com
    }
    final ContentResolver resolver = context.getContentResolver();
    final Cursor cur = resolver.query(Subscription.CONTENT_URI,
            new String[] { Subscription._UID, Subscription._ICON, Subscription._URL }, null, null, null);
    for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
        final String uid = cur.getString(0);
        final byte[] data = cur.getBlob(1);
        final String subUrl = cur.getString(2);
        if (subUrl != null && data == null) {
            final SubscriptionIconUrl fetchUrl = new SubscriptionIconUrl(isHttpsConnection, subUrl);
            try {
                final byte[] iconData = httpGetQueryByte(fetchUrl);
                final Bitmap icon = BitmapFactory.decodeByteArray(iconData, 0, iconData.length);
                final int size = icon.getWidth() * icon.getHeight() * 2;
                final ByteArrayOutputStream output = new ByteArrayOutputStream(size);
                icon.compress(Bitmap.CompressFormat.PNG, 100, output);
                output.flush();
                output.close();
                dataMgr.updateSubscriptionIconByUid(uid, output.toByteArray());
            } catch (final IOException exception) {
                cur.close();
                throw new DataSyncerException(exception);
            }
        }
    }
    cur.close();
}

From source file:de.romankreisel.faktotum.beans.BundesbruderBean.java

private Byte[] storeImageToByteArray(Image image) throws IOException {
    if (!(image instanceof RenderedImage)) {
        BufferedImage newImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
                BufferedImage.TYPE_INT_RGB);
        newImage.getGraphics().drawImage(image, 0, 0, null);
        image = newImage;/* w w w  . j  a v  a 2s .  c o m*/
    }
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ImageIO.write((RenderedImage) image, "jpg", byteArrayOutputStream);
    byteArrayOutputStream.flush();
    byte[] imageInByte = byteArrayOutputStream.toByteArray();
    byteArrayOutputStream.close();
    return ArrayUtils.toObject(imageInByte);
}

From source file:com.netsteadfast.greenstep.bsc.command.PerspectivesDashboardExcelCommand.java

@SuppressWarnings("unchecked")
private int putCharts(XSSFWorkbook wb, XSSFSheet sh, Context context) throws Exception {
    String pieBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("pieCanvasToData"));
    String barBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("barCanvasToData"));
    BufferedImage pieImage = SimpleUtils.decodeToImage(pieBase64Content);
    BufferedImage barImage = SimpleUtils.decodeToImage(barBase64Content);
    ByteArrayOutputStream pieBos = new ByteArrayOutputStream();
    ImageIO.write(pieImage, "png", pieBos);
    pieBos.flush();
    ByteArrayOutputStream barBos = new ByteArrayOutputStream();
    ImageIO.write(barImage, "png", barBos);
    barBos.flush();/*from w ww  .j  a v  a 2s  . c o  m*/
    SimpleUtils.setCellPicture(wb, sh, pieBos.toByteArray(), 0, 0);
    SimpleUtils.setCellPicture(wb, sh, barBos.toByteArray(), 0, 9);
    int row = 21;

    List<Map<String, Object>> chartDatas = (List<Map<String, Object>>) context.get("chartDatas");
    String year = (String) context.get("year");

    XSSFCellStyle cellHeadStyle = wb.createCellStyle();
    cellHeadStyle.setFillForegroundColor(new XSSFColor(SimpleUtils.getColorRGB4POIColor("#f5f5f5")));
    cellHeadStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

    XSSFFont cellHeadFont = wb.createFont();
    cellHeadFont.setBold(true);
    //cellHeadFont.setColor( new XSSFColor( SimpleUtils.getColorRGB4POIColor( "#000000" ) ) );      
    cellHeadStyle.setFont(cellHeadFont);

    int titleRow = row - 1;
    int titleCellSize = 14;
    Row headRow = sh.createRow(titleRow);
    for (int i = 0; i < titleCellSize; i++) {
        Cell headCell = headRow.createCell(i);
        headCell.setCellStyle(cellHeadStyle);
        headCell.setCellValue("Perspectives metrics gauge ( " + year + " )");
    }
    sh.addMergedRegion(new CellRangeAddress(titleRow, titleRow, 0, titleCellSize - 1));

    int cellLeft = 10;
    int rowSpace = 17;
    for (Map<String, Object> data : chartDatas) {
        Map<String, Object> nodeData = (Map<String, Object>) ((List<Object>) data.get("datas")).get(0);
        String pngImageData = SimpleUtils.getPNGBase64Content((String) nodeData.get("outerHTML"));
        BufferedImage imageData = SimpleUtils.decodeToImage(pngImageData);
        ByteArrayOutputStream imgBos = new ByteArrayOutputStream();
        ImageIO.write(imageData, "png", imgBos);
        imgBos.flush();
        SimpleUtils.setCellPicture(wb, sh, imgBos.toByteArray(), row, 0);

        XSSFColor bgColor = new XSSFColor(SimpleUtils.getColorRGB4POIColor((String) nodeData.get("bgColor")));
        XSSFColor fnColor = new XSSFColor(SimpleUtils.getColorRGB4POIColor((String) nodeData.get("fontColor")));

        XSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setFillForegroundColor(bgColor);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        XSSFFont cellFont = wb.createFont();
        cellFont.setBold(true);
        cellFont.setColor(fnColor);

        cellStyle.setFont(cellFont);

        int perTitleCellSize = 4;
        Row nowRow = sh.createRow(row);
        for (int i = 0; i < perTitleCellSize; i++) {
            Cell cell1 = nowRow.createCell(cellLeft);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue((String) nodeData.get("name"));
        }
        sh.addMergedRegion(new CellRangeAddress(row, row, cellLeft, cellLeft + perTitleCellSize - 1));

        nowRow = sh.createRow(row + 1);
        Cell cell2 = nowRow.createCell(cellLeft);
        cell2.setCellValue("Target: " + String.valueOf(nodeData.get("target")));

        nowRow = sh.createRow(row + 2);
        Cell cell3 = nowRow.createCell(cellLeft);
        cell3.setCellValue("Min: " + String.valueOf(nodeData.get("min")));

        nowRow = sh.createRow(row + 3);
        Cell cell4 = nowRow.createCell(cellLeft);
        cell4.setCellValue("Score: " + String.valueOf(nodeData.get("score")));

        row += rowSpace;
    }

    return row;
}

From source file:com.illustrationfinder.IllustrationFinderController.java

@RequestMapping(value = "/", method = RequestMethod.GET, params = { "url", "preferred-width",
        "preferred-height" })
public ModelAndView showIllustrationFinderResults(ModelMap modelMap, @RequestParam(value = "url") String pUrl,
        @RequestParam(value = "preferred-width") String pPreferredWidth,
        @RequestParam(value = "preferred-height") String pPreferredHeight) {
    final ModelAndView modelAndView = new ModelAndView("/IllustrationFinderView");

    // Add the URL to attributes
    modelMap.addAttribute("pUrl", pUrl);

    // Check if the URL is valid
    boolean isUrlValid = false;

    String url = pUrl;//from w  ww . java 2  s.  c  o  m
    if (url != null) {
        url = StringEscapeUtils.escapeHtml4(url);

        if (new UrlValidator(new String[] { "http", "https" }).isValid(url)) {
            isUrlValid = true;
        }
    }

    modelMap.addAttribute("isUrlValid", isUrlValid);

    // Get the images
    try {
        if (isUrlValid) {
            final IPostProcessor postProcessor = new HtmlPostProcessor();
            final GoogleSearchEngine searchEngine = new GoogleSearchEngine();
            final IImageProcessor<BufferedImage, BufferedImageOp> imageProcessor = new BufferedImageProcessor();

            imageProcessor.setPreferredSize(
                    new Dimension(Integer.parseInt(pPreferredWidth), Integer.parseInt(pPreferredHeight)));

            final IllustrationFinder illustrationFinder = new IllustrationFinder();
            illustrationFinder.setPostProcessor(postProcessor);
            illustrationFinder.setSearchEngine(searchEngine);
            illustrationFinder.setImageProcessor(imageProcessor);

            final List<BufferedImage> images = illustrationFinder.getImages(new URL(pUrl));

            // Convert images to base64 strings
            final List<String> imagesAsStrings = new ArrayList<>();

            if (images != null) {
                for (BufferedImage image : images) {
                    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        ImageIO.write(image, "png", baos);
                        baos.flush();
                        final byte[] imageInByteArray = baos.toByteArray();
                        baos.close();
                        final String b64 = DatatypeConverter.printBase64Binary(imageInByteArray);

                        imagesAsStrings.add(b64);
                    } catch (IOException e) {
                        // Failed to convert the image
                    }
                }
            }

            modelMap.addAttribute("images", imagesAsStrings);
        }
    } catch (IOException e) {
        // Exception triggered if the URL is malformed, it should not happen because the URL is validated before
    }

    return modelAndView;
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.exporters.PNGImageExporter.java

@Override
public void export(final File file) throws IOException {
    final BufferedImage img = generateImage();
    if (img == null)
        return;//from   www  . ja  v  a 2  s .  c om
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream(1000000);
    ImageIO.write(img, "png", buffer);
    buffer.flush();

    if (Thread.currentThread().isInterrupted())
        return;

    FileUtils.writeByteArrayToFile(file, buffer.toByteArray());
}

From source file:gov.ca.cwds.rest.util.jni.CmsPKCompressor.java

/**
 * Decompress (inflate) an InputStream of a PK-compressed document.
 * /*from   w w  w  . j a v  a2  s  .  c o  m*/
 * @param input InputStream of PK-compressed document.
 * @return byte array of decompressed document
 * @throws IOException If an I/O error occurs
 */
public byte[] decompressStream(InputStream input) throws IOException {
    if (input == null) {
        throw new IOException("REQUIRED: input stream to decompress cannot be null");
    }

    final InputStream iis = new InflateInputStream(input, true);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(DEFAULT_OUTPUT_SIZE);
    IOUtils.copy(iis, bos);

    iis.close();
    bos.flush();
    bos.close();
    return bos.toByteArray();
}

From source file:deployer.TestUtils.java

public static ByteBuffer createSampleOpenShiftWebAppTarBall() throws IOException, ArchiveException {
    ByteArrayInputStream bis = new ByteArrayInputStream(createSampleAppTarBall(ArtifactType.WebApp).array());
    CompressorInputStream cis = new GzipCompressorInputStream(bis);
    ArchiveInputStream ais = new TarArchiveInputStream(cis);

    ByteArrayOutputStream bos = new ByteArrayOutputStream(bis.available() + 2048);
    CompressorOutputStream cos = new GzipCompressorOutputStream(bos);
    ArchiveOutputStream aos = new TarArchiveOutputStream(cos);

    ArchiveEntry nextEntry;/* w w w.j  a  v  a 2 s . com*/
    while ((nextEntry = ais.getNextEntry()) != null) {
        aos.putArchiveEntry(nextEntry);
        IOUtils.copy(ais, aos);
        aos.closeArchiveEntry();
    }
    ais.close();
    cis.close();
    bis.close();

    TarArchiveEntry entry = new TarArchiveEntry(
            Paths.get(".openshift", CONFIG_DIRECTORY, "/standalone.xml").toFile());
    byte[] xmlData = SAMPLE_STANDALONE_DATA.getBytes();
    entry.setSize(xmlData.length);
    aos.putArchiveEntry(entry);
    IOUtils.write(xmlData, aos);
    aos.closeArchiveEntry();

    aos.finish();
    cos.close();
    bos.flush();
    return ByteBuffer.wrap(bos.toByteArray());
}

From source file:it.geosolutions.imageio.plugins.exif.EXIFUtilities.java

/**
 * Write the specified {@link EXIFMetadata} object as well as the specified image data bytes to
 * the specified outputStream. It will take care of inserting the EXIF marker in the proper 
 * location within the outputStream when writing image data bytes.  
 * //from  w  ww .j a  v  a 2  s  . c o m
 * @param outputStream the outputStream where to write
 * @param imageData the bytes containing JPEG encoded image data 
 * @param imageDataSize the number of bytes to be used from the data array
 * @param exif the {@link EXIFMetadata} object holding EXIF.
 * @throws IOException
 */
private static void writeToByteStream(ByteArrayOutputStream outputStream, final byte[] imageData,
        final int imageDataSize, final EXIFMetadata exif) throws IOException {

    // locate the DQT marker in the input imageData bytes
    final int dqtMarkerPos = locateFirst(imageData, DQT_MARKER);
    if (dqtMarkerPos != -1) {

        // write to stream the initial part of imageData before appending EXIF marker
        // at the proper position
        outputStream.write(imageData, 0, dqtMarkerPos);
        outputStream.flush();

        // Append the EXIF content
        outputStream = initializeExifStream(exif, outputStream);
        outputStream.write(_0);

        // Proceed with writing the remaining part of image data bytes.
        outputStream.write(imageData, dqtMarkerPos, imageDataSize - dqtMarkerPos);
    }
}

From source file:net.sf.taverna.t2.activities.soaplab.views.SoaplabActivityContextualView.java

private String getMetadata() {
    try {// ww w .  ja v a2 s .  co m
        Configuration configuration = getConfigBean();
        JsonNode json = configuration.getJson();
        String endpoint = json.get("endpoint").textValue();
        Call call = (Call) new Service().createCall();
        call.setTimeout(new Integer(0));
        call.setTargetEndpointAddress(endpoint);
        call.setOperationName(new QName("describe"));
        String metadata = (String) call.invoke(new Object[0]);
        logger.info(metadata);
        // Old impl, returns a tree of the XML
        // ColXMLTree tree = new ColXMLTree(metadata);
        URL sheetURL = SoaplabActivityContextualView.class.getResource("/analysis_metadata_2_html.xsl");
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        logger.info(sheetURL.toString());
        Templates stylesheet = transformerFactory.newTemplates(new StreamSource(sheetURL.openStream()));
        Transformer transformer = stylesheet.newTransformer();
        StreamSource inputStream = new StreamSource(new ByteArrayInputStream(metadata.getBytes()));
        ByteArrayOutputStream transformedStream = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(transformedStream);
        transformer.transform(inputStream, result);
        transformedStream.flush();
        transformedStream.close();
        // String summaryText = "<html><head>"
        // + WorkflowSummaryAsHTML.STYLE_NOBG + "</head>"
        // + transformedStream.toString() + "</html>";
        // JEditorPane metadataPane = new ColJEditorPane("text/html",
        // summaryText);
        // metadataPane.setText(transformedStream.toString());
        // // logger.info(transformedStream.toString());
        // JScrollPane jsp = new JScrollPane(metadataPane,
        // JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        // JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        // jsp.setPreferredSize(new Dimension(0, 0));
        // jsp.getVerticalScrollBar().setValue(0);
        return transformedStream.toString();
    } catch (Exception ex) {
        return "<font color=\"red\">Error</font><p>An exception occured while trying to fetch Soaplab metadata from the server. The error was :<pre>"
                + ex.getMessage() + "</pre>";

    }
}