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:org.dice_research.topicmodeling.io.stream.DocumentSupplierSerializer.java

protected void writeDocument(DataOutputStream dout, Document document) throws IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream oout = new ObjectOutputStream(bout);
    oout.writeObject(document);/*from   ww  w . j  a  v a 2  s. co  m*/
    oout.close();
    dout.writeInt(bout.size());
    bout.writeTo(dout);
}

From source file:org.icgc.dcc.portal.manifest.ManifestArchive.java

public void addManifest(@NonNull String fileName, @NonNull ByteArrayOutputStream fileContents)
        throws IOException {
    val tarEntry = new TarArchiveEntry(fileName);

    tarEntry.setSize(fileContents.size());
    tar.putArchiveEntry(tarEntry);/*from w  w  w  . j a va  2 s  . c om*/

    fileContents.writeTo(tar);
    tar.closeArchiveEntry();
}

From source file:net.kahowell.xsd.fuzzer.XmlGenerator.java

private void showOrSave(ByteArrayOutputStream stream) throws IOException {
    if (outputFilename != null) {
        File file = new File(outputFilename);
        FileOutputStream fileout = new FileOutputStream(file);
        stream.writeTo(fileout);
    } else {//w ww .  ja va  2s  .co m
        System.out.println(stream.toString());
    }
}

From source file:org.apache.wink.itest.contentencoding.WinkApacheContentEncodingTest.java

/**
 * Tests sending in small bits of gzip encoded content.
 * //from ww  w  .  j av a 2 s . c  om
 * @throws HttpException
 * @throws IOException
 */
@Override
public void testSendSmallGzipContentEncoded() throws HttpException, IOException {
    ByteArrayOutputStream originalContent = new ByteArrayOutputStream();
    originalContent.write("Hello world".getBytes("UTF-8"));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(baos);

    originalContent.writeTo(gzipOut);

    gzipOut.finish();
    byte[] content = baos.toByteArray();

    ClientResponse response = client.resource(BASE_URI + "/bigbook").accept(MediaType.TEXT_PLAIN)
            .header("Content-Encoding", "gzip").contentType("text/plain; charset=utf-8").post(content);
    assertEquals(200, response.getStatusCode());
    String responseBody = response.getEntity(String.class);
    assertEquals("Hello world" + "helloworld", responseBody);
}

From source file:ProxyAuthTest.java

private static File writeArrayToByteStream(String url) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    if (url != null) {
        writeCmdLine("!connect " + url, out);
    }//from  w  w w .j  a  va  2s . c o m
    writeCmdLine("!brief", out);
    writeCmdLine("!set silent true", out);
    resultFile = File.createTempFile(tabName, ".out");
    if (!"true".equals(System.getProperty("proxyAuth.debug", "false"))) {
        resultFile.deleteOnExit();
    }
    writeCmdLine("!record " + resultFile.getPath(), out);

    for (String stmt : dmlStmts) {
        writeSqlLine(stmt, out);
    }

    for (String stmt : selectStmts) {
        writeSqlLine(stmt, out);
    }

    for (String stmt : cleanUpStmts) {
        writeSqlLine(stmt, out);
    }
    writeCmdLine("!record", out);
    writeCmdLine("!quit", out);

    File tmpFile = File.createTempFile(tabName, ".q");
    tmpFile.deleteOnExit();
    scriptFileName = tmpFile.getPath();
    FileOutputStream fstream = new FileOutputStream(scriptFileName);
    out.writeTo(fstream);

    inpStream = new ByteArrayInputStream(out.toByteArray());
    return resultFile;
}

From source file:com.id.get.expand.spring.MarshallingView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Object toBeMarshalled = locateToBeMarshalled(model);
    if (toBeMarshalled == null) {
        throw new ServletException("Unable to locate object to be marshalled in model: " + model);
    }//from w ww.j  av  a 2s .c o  m
    ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    this.marshaller.marshal(toBeMarshalled, new StreamResult(baos));

    setResponseContentType(request, response);
    response.setContentLength(baos.size());
    baos.writeTo(response.getOutputStream());
}

From source file:org.wso2.carbon.reporting.ui.servlet.BeanCollectionReportServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request  servlet request// w w  w .jav  a 2s .c om
 * @param response servlet response
 * @throws ReportingException if failed to handle report request
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ReportingException {

    String component = request.getParameter("component");
    String template = request.getParameter("template");
    String type = request.getParameter("type");
    String reportData = request.getParameter("reportDataSession");
    String downloadFileName = null;

    if (component == null || template == null || type == null || reportData == null) {
        throw new ReportingException(
                "required one or more parameters missing (component ,template , reportType, reportData)");
    }

    if (type.equals("pdf")) {
        response.setContentType("application/pdf");
        downloadFileName = template + ".pdf";
    } else if (type.equals("excel")) {
        response.setContentType("application/vnd.ms-excel");
        downloadFileName = template + ".xls";
    } else if (type.equals("html")) {
        response.setContentType("text/html");

    } else {
        throw new ReportingException("requested report type can not be support");
    }
    if (downloadFileName != null) {
        response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
    }
    Object reportDataObject = request.getSession().getAttribute(reportData);
    if (reportDataObject == null) {
        throw new ReportingException("can't generate report , data unavailable in session ");
    }

    try {
        String serverURL = CarbonUIUtil.getServerURL(request.getSession().getServletContext(),
                request.getSession());
        ConfigurationContext configurationContext = (ConfigurationContext) request.getSession()
                .getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
        String cookie = (String) request.getSession().getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);

        ReportResourceSupplierClient resourceSupplierClient = new ReportResourceSupplierClient(cookie,
                serverURL, configurationContext);

        String reportResource = resourceSupplierClient.getReportResources(component, template);
        JRDataSource jrDataSource = new BeanCollectionReportData().getReportDataSource(reportDataObject);
        JasperPrintProvider jasperPrintProvider = new JasperPrintProvider();
        JasperPrint jasperPrint = jasperPrintProvider.createJasperPrint(jrDataSource, reportResource,
                new ReportParamMap[0]);
        request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
        ReportStream reportStream = new ReportStream();
        ByteArrayOutputStream outputStream = reportStream.getReportStream(jasperPrint, type);
        ServletOutputStream servletOutputStream = response.getOutputStream();
        try {
            outputStream.writeTo(servletOutputStream);
            outputStream.flush();
        } finally {
            outputStream.close();
            servletOutputStream.close();
        }

    } catch (Exception e) {
        String msg = "Error occurred handling " + template + "report request from " + component;
        log(msg);
        throw new ReportingException(msg, e);
    }
}

From source file:org.wso2.carbon.reporting.ui.servlet.GraphGenerateServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String type = request.getParameter("reportType");
    String typeSecond = request.getParameter("reportTypeSecond");
    String dataSessionVar = request.getParameter("reportDataSession");
    String component = request.getParameter("component");
    String template = request.getParameter("template");
    String generateType;//from   w w  w.java  2  s .  c  om
    String downloadFileName = null;

    if (type == null) {
        type = " ";
    } else {
        typeSecond = " ";
    }

    if (type.equals("pdf") || typeSecond.equals("pdf")) {
        generateType = "pdf";
        response.setContentType("application/pdf");
        downloadFileName = template + ".pdf";
    } else if (type.equals("excel") || typeSecond.equals("excel")) {
        generateType = "excel";
        response.setContentType("application/vnd.ms-excel");
        downloadFileName = template + ".xsl";
    } else if (type.equals("html") || typeSecond.equals("html")) {
        generateType = "html";
        response.setContentType("text/html");

    } else {
        throw new ReportingException("requested report type can not be support");
    }
    if (downloadFileName != null) {
        response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
    }
    Object reportDataObject = request.getSession().getAttribute(dataSessionVar);
    if (reportDataObject == null) {
        throw new ReportingException("can't generate report , data unavailable in session ");
    }
    try {
        String serverURL = CarbonUIUtil.getServerURL(request.getSession().getServletContext(),
                request.getSession());
        ConfigurationContext configurationContext = (ConfigurationContext) request.getSession()
                .getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
        String cookie = (String) request.getSession().getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE);

        ReportResourceSupplierClient resourceSupplierClient = new ReportResourceSupplierClient(cookie,
                serverURL, configurationContext);

        String reportResource = resourceSupplierClient.getReportResources(component, template);
        JRDataSource jrDataSource = new BeanCollectionReportData().getReportDataSource(reportDataObject);
        JasperPrintProvider jasperPrintProvider = new JasperPrintProvider();
        JasperPrint jasperPrint = jasperPrintProvider.createJasperPrint(jrDataSource, reportResource,
                new ReportParamMap[0]);
        request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
        ReportStream reportStream = new ReportStream();
        ByteArrayOutputStream outputStream = reportStream.getReportStream(jasperPrint, generateType);
        ServletOutputStream servletOutputStream = response.getOutputStream();
        try {
            outputStream.writeTo(servletOutputStream);
            outputStream.flush();
        } finally {
            outputStream.close();
            servletOutputStream.close();
        }

    } catch (Exception e) {
        String msg = "Error occurred handling " + template + "report request from " + component;
        log(msg);
        throw e;
    }
}

From source file:no.abmu.common.jasperreports.JasperReportsXlsViewToFile.java

/**
 * Perform rendering for a single Jasper Reports exporter, that is,
 * for a pre-defined output format./*w  ww  .j a v  a2 s .c om*/
 */
protected void renderReport(JasperPrint populatedReport, Map model, HttpServletResponse response)
        throws Exception {

    log.info(" XXXXXXXXXXXXXXXXXXX renderReport: START ");

    StopWatch stopWatch = new StopWatch();
    stopWatch.start("renderReport");

    // Prepare report for rendering.
    JRExporter exporter = createExporter();

    if (getConvertedExporterParameters() != null) {
        exporter.setParameters(getConvertedExporterParameters());
    }

    // We need to write binary output to the response OutputStream.

    // Render report into local OutputStream.
    // IE workaround: write into byte array first.
    ByteArrayOutputStream baos = new ByteArrayOutputStream(OUTPUT_BYTE_ARRAY_INITIAL_SIZE);
    JasperReportsUtils.render(exporter, populatedReport, baos);

    // Flush byte array to servlet output stream.
    java.io.FileOutputStream fileOutputStream = new FileOutputStream(getOutPutFileName());

    baos.writeTo(fileOutputStream);
    fileOutputStream.flush();
    fileOutputStream.close();

    stopWatch.stop();

    log.info("[private:renderReport] tok[" + stopWatch.getTotalTimeMillis() + "] ms");
    log.info(" XXXXXXXXXXXXXXXXXXX renderReport: FINISH ");

}

From source file:com.ltasks.GZipPostMethod.java

@Override
protected RequestEntity generateRequestEntity() {
    if (mIsGzip) {
        try {//from   w  ww .jav  a2 s.c  o m
            String contentStr = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet());

            ByteArrayOutputStream originalContent = new ByteArrayOutputStream();
            originalContent.write(EncodingUtil.getAsciiBytes(contentStr));

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //ChunkedOutputStream chunkedOut = new ChunkedOutputStream(baos);
            GZIPOutputStream gzipOut = new GZIPOutputStream(baos);

            originalContent.writeTo(gzipOut);

            gzipOut.finish();
            byte[] content = baos.toByteArray();

            ByteArrayRequestEntity entity = new ByteArrayRequestEntity(content, FORM_URL_ENCODED_CONTENT_TYPE);
            return entity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    } else {
        return super.generateRequestEntity();
    }
}