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.apache.hadoop.hbase.mapred.TestSerialization.java

@Test
public void testLargeMutation() throws Exception {
    Put put = new Put(row);
    put.add(family, qualifier, value);//from  ww  w  . j  a  va 2s  .  com

    MutationSerialization serialization = new MutationSerialization();
    Serializer<Mutation> serializer = serialization.getSerializer(Mutation.class);
    Deserializer<Mutation> deserializer = serialization.getDeserializer(Mutation.class);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ByteArrayInputStream is = null;
    try {
        serializer.open(os);
        serializer.serialize(put);
        os.flush();
        is = new ByteArrayInputStream(os.toByteArray());
        deserializer.open(is);
        deserializer.deserialize(null);
    } catch (InvalidProtocolBufferException e) {
        assertTrue("Got InvalidProtocolBufferException in " + name.getMethodName(),
                e.getCause() instanceof InvalidProtocolBufferException);
    } catch (Exception e) {
        fail("Got an invalid exception: " + e);
    }
}

From source file:com.springsecurity.plugin.util.ImageResizer.java

public File reziseTo(File source, File dest, int width, int height, String ext) {
    try {//from  www.ja  v a  2  s  .  co  m
        ImageResizer img = new ImageResizer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img.scale(source, width, height), ext, baos);
        dest.delete();
        baos.writeTo(new FileOutputStream(dest));
        baos.flush();
    } catch (IOException e) {
        System.err.println("err" + e.getMessage());
    }
    return dest;
}

From source file:com.htmlhifive.tools.codeassist.ui.config.CodeAssistConfig.java

/**
 * ???.// w w  w.  ja  va2 s . c o m
 * 
 * @return ????????
 */
public boolean saveConfig() {

    Properties properties = new Properties();
    properties.setProperty(KEY_OPTION_PATH, configBean.getOptionFilePath());
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    InputStream input = null;
    try {
        properties.store(output, "");
        output.flush();
        input = new ByteArrayInputStream(output.toByteArray());
        configProp.refreshLocal(IResource.DEPTH_ZERO, null);
        if (configProp.exists()) {
            configProp.setContents(input, false, false, null);
        } else {
            configProp.create(input, false, null);
        }
        return true;
    } catch (CoreException e) {
        logger.log(UIMessages.UIEM0002, e);
        ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                UIMessages.UIDT0002.getText(), UIMessages.UIEM0002.getText(), e.getStatus());
    } catch (IOException e) {
        logger.log(UIMessages.UIEM0002, e);
        ErrorDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
                UIMessages.UIDT0002.getText(), UIMessages.UIEM0002.getText(),
                new Status(IStatus.ERROR, H5CodeAssistUIPlugin.PLUGIN_ID, e.getMessage()));
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
    }
    return false;
}

From source file:org.apache.abdera.ext.gdata.GoogleLoginAuthScheme.java

protected String getAuth(String id, String pwd, String service) {
    try {//  ww  w .j  a v  a 2  s .co  m
        AbderaClient abderaClient = new AbderaClient();
        Formatter f = new Formatter();
        f.format("Email=%s&Passwd=%s&service=%s&source=%s", URLEncoder.encode(id, "utf-8"),
                URLEncoder.encode(pwd, "utf-8"), (service != null) ? URLEncoder.encode(service, "utf-8") : "",
                URLEncoder.encode(Version.APP_NAME, "utf-8"));
        StringRequestEntity stringreq = new StringRequestEntity(f.toString(),
                "application/x-www-form-urlencoded", "utf-8");
        String uri = "https://www.google.com/accounts/ClientLogin";
        RequestOptions options = abderaClient.getDefaultRequestOptions();
        options.setContentType("application/x-www-form-urlencoded");
        ClientResponse response = abderaClient.post(uri, stringreq, options);
        InputStream in = response.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int n = -1;
        while ((n = in.read()) != -1) {
            out.write(n);
        }
        out.flush();
        response.release();
        String auth = new String(out.toByteArray());
        return auth.split("\n")[2].replaceAll("Auth=", "auth=");
    } catch (Exception e) {
    }
    return null;
}

From source file:org.openmrs.module.complexdatadb.api.handler.ImageDBHandler.java

/**
 * @see org.openmrs.obs.ComplexObsHandler#saveObs(org.openmrs.Obs)
 *///  w ww.  j  a  v  a  2s .c o m
@Override
public Obs saveObs(Obs obs) throws APIException {

    // Get the buffered image from the ComplexData.
    BufferedImage img = null;

    Object data = obs.getComplexData().getData();
    if (data instanceof BufferedImage) {
        img = (BufferedImage) data;
    } else if (data instanceof InputStream) {
        try {
            img = ImageIO.read((InputStream) data);
            if (img == null) {
                throw new IllegalArgumentException("Invalid image file");
            }
        } catch (IOException e) {
            throw new APIException(
                    "Unable to convert complex data to a valid input stream and then read it into a buffered image",
                    e);
        }
    }

    if (img == null) {
        throw new APIException("Cannot save complex obs where obsId=" + obs.getObsId()
                + " because its ComplexData.getData() is null.");
    }

    try {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        String extension = getExtension(obs.getComplexData().getTitle());
        ImageIO.write(img, extension, baos);
        baos.flush();
        byte[] bImage = baos.toByteArray();
        baos.close();

        ComplexDataToDB image = new ComplexDataToDB();

        image.setData(bImage);

        Context.getService(ComplexDataToDBService.class).saveComplexDataToDB(image);

        // Set the Title and URI for the valueComplex
        obs.setValueComplex(extension + " image |" + image.getUuid());

        // Remove the ComlexData from the Obs
        obs.setComplexData(null);

    } catch (IOException ioe) {
        throw new APIException("Trying to write complex obs to the database. ", ioe);
    }

    return obs;
}

From source file:com.adaptris.core.mail.attachment.MimeMailCreator.java

/**
 * @see MailContentCreator#createAttachments(com.adaptris.core.AdaptrisMessage)
 *//*from  w  ww  .  j  a  v  a  2 s.  co  m*/
@Override
public List<MailAttachment> createAttachments(AdaptrisMessage msg) throws MailException {
    if (bodySelector == null) {
        throw new MailException("No way of selecting the body");
    }
    List<MailAttachment> attachments = new ArrayList<MailAttachment>();
    try {
        BodyPartIterator mp = MimeHelper.createBodyPartIterator(msg);
        MimeBodyPart body = bodySelector.select(mp);
        for (int i = 0; i < mp.size(); i++) {
            MimeBodyPart attachment = mp.getBodyPart(i);
            if (!attachment.equals(body)) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                StreamUtil.copyStream(attachment.getInputStream(), out);
                out.flush();
                attachments.add(new MailAttachment(out.toByteArray(), getAttachmentFileName(attachment),
                        getContentType(attachment))
                                .withContentTransferEncoding(getContentTransferEncoding(attachment)));
            }
        }
    } catch (Exception e) {
        throw new MailException(e);
    }
    return attachments;
}

From source file:org.openxdata.server.servlet.WMDownloadServlet.java

private void downloadStudies(HttpServletResponse response) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    formDownloadService.downloadStudies(dos, "", "");
    baos.flush();
    dos.flush();/* www .j av a2s . c  o m*/
    byte[] data = baos.toByteArray();
    baos.close();
    dos.close();

    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));

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

    try {
        @SuppressWarnings("unused")
        byte size = dis.readByte(); //reads the size of the studies

        while (true) {
            String value = "<study id=\"" + dis.readInt() + "\" name=\"" + dis.readUTF() + "\"/>";
            out.println(value);
        }
    } catch (EOFException exe) {
        //exe.printStackTrace();
    }
    out.println("</StudyList>");
    out.flush();
    dis.close();
}

From source file:com.glaf.chart.util.ChartUtils.java

public static byte[] createChart(Chart chartModel, JFreeChart chart) {
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    try {/*from   w  w  w.j a  v a  2s .  co  m*/
        baos = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(baos);
        java.awt.image.BufferedImage bi = chart.createBufferedImage(chartModel.getChartWidth(),
                chartModel.getChartHeight());

        if ("png".equalsIgnoreCase(chartModel.getImageType())) {
            EncoderUtil.writeBufferedImage(bi, chartModel.getImageType(), bos);
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            ServletUtilities.saveChartAsPNG(chart, chartModel.getChartWidth(), chartModel.getChartHeight(),
                    info, null);
        } else if ("jpeg".equalsIgnoreCase(chartModel.getImageType())) {
            EncoderUtil.writeBufferedImage(bi, chartModel.getImageType(), bos);
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            ServletUtilities.saveChartAsJPEG(chart, chartModel.getChartWidth(), chartModel.getChartHeight(),
                    info, null);
        }

        bos.flush();
        baos.flush();

        return baos.toByteArray();

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeQuietly(baos);
        IOUtils.closeQuietly(bos);
    }
}

From source file:gumga.framework.presentation.api.AbstractReportAPI.java

public void generateAndExportHTMLReport(String reportName, String destFile, List data,
        Map<String, Object> params, HttpServletRequest request, HttpServletResponse response)
        throws JRException, IOException {
    InputStream is = getResourceAsInputStream(request, reportName);
    setContentType(response, reportName, ReportType.HTML);
    reportService.exportReportToHtmlFile(is, data, params, destFile);

    //Set the output content
    InputStream generatedIs = request.getServletContext().getResourceAsStream(destFile);
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;//from  www .  j a  va 2  s.  c  o  m
    byte[] bytes = new byte[16384];

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

    buffer.flush();
    bytes = buffer.toByteArray();
    response.setContentLength(bytes.length);
    response.getOutputStream().write(bytes, 0, bytes.length);
}

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

@SuppressWarnings("unchecked")
private int putCharts(XSSFWorkbook wb, XSSFSheet sh, Context context) throws Exception {

    String barBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("barChartsData"));
    BufferedImage barImage = SimpleUtils.decodeToImage(barBase64Content);
    ByteArrayOutputStream barBos = new ByteArrayOutputStream();
    ImageIO.write(barImage, "png", barBos);
    barBos.flush();
    SimpleUtils.setCellPicture(wb, sh, barBos.toByteArray(), 0, 0);

    int row = 28;

    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);//from  w  ww .  ja v a  2 s  .co m
    cellHeadStyle.setFont(cellHeadFont);

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

    row = row + 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;
}