Example usage for org.apache.commons.io.output ByteArrayOutputStream writeTo

List of usage examples for org.apache.commons.io.output ByteArrayOutputStream writeTo

Introduction

In this page you can find the example usage for org.apache.commons.io.output ByteArrayOutputStream writeTo.

Prototype

public synchronized void writeTo(OutputStream out) throws IOException 

Source Link

Document

Writes the entire contents of this byte stream to the specified output stream.

Usage

From source file:com.orange.mmp.mvc.bundle.Controller.java

@SuppressWarnings("unchecked")
@Override// w ww  .j a va 2  s. c o m
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    int pathInfoStart = request.getRequestURI().indexOf(urlMapping);
    if (pathInfoStart < 0) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
        return null;
    }
    // Get user agent to obtain branchID
    String userAgent = request.getHeader(Constants.HTTP_HEADER_USERAGENT);
    Mobile mobile = new Mobile();
    mobile.setUserAgent(userAgent);
    Mobile[] mobiles = (Mobile[]) DaoManagerFactory.getInstance().getDaoManager().getDao("mobile").find(mobile);
    String branchId = null;//Constants.DEFAULT_BRANCH_ID;
    if (mobiles != null && mobiles.length > 0) {
        branchId = mobiles[0].getBranchId();
    } else {
        Branch branch = new Branch();
        branch.setDefault(true);
        Branch[] branches = (Branch[]) DaoManagerFactory.getInstance().getDaoManager().getDao("branch")
                .find(branch);
        if (branches != null && branches.length > 0)
            branchId = branches[0].getId();
    }

    String pathInfo = request.getRequestURI().substring(pathInfoStart + urlMapping.length());
    String requestParts[] = pathInfo.split("/");
    String widgetId = null;
    String resourceName = null;
    InputStream input = null;

    if (requestParts.length > 2) {
        widgetId = requestParts[1];
        resourceName = pathInfo.substring(widgetId.length() + 2);
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentLength(0);
        return null;
    }

    input = WidgetManager.getInstance().getWidgetResource(resourceName, widgetId, branchId);

    if (input == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
    } else {
        ByteArrayOutputStream resourceBuffer = new ByteArrayOutputStream();
        OutputStream output = response.getOutputStream();
        try {
            IOUtils.copy(input, resourceBuffer);
            response.setContentLength(resourceBuffer.size());
            resourceBuffer.writeTo(output);
        } catch (IOException ioe) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentLength(0);
        } finally {
            if (input != null)
                input.close();
            if (output != null)
                output.close();
            if (resourceBuffer != null)
                resourceBuffer.close();
        }
    }
    return null;
}

From source file:com.nextdoor.bender.ipc.s3.S3Transport.java

protected ByteArrayOutputStream compress(ByteArrayOutputStream raw) throws TransportException {
    ByteArrayOutputStream compressed = new ByteArrayOutputStream();
    BZip2CompressorOutputStream bcos = null;
    try {/*from w ww  .j a  v  a2 s . com*/
        bcos = new BZip2CompressorOutputStream(compressed);
    } catch (IOException e) {
        throw new TransportException("unable to open compressed stream", e);
    }

    try {
        raw.writeTo(bcos);
        bcos.flush();
    } catch (IOException e) {
        throw new TransportException("unable to compress data", e);
    } finally {
        try {
            bcos.close();
        } catch (IOException e) {
        }
    }

    return compressed;
}

From source file:gov.nih.nci.caarray.application.translation.geosoft.GeoSoftExporterBean.java

private void addReadmeFile(ArchiveOutputStream ar) throws IOException {
    final InputStream is = GeoSoftExporterBean.class.getResourceAsStream("README.txt");
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(is, baos);/*from www  .  ja  va 2  s  . co  m*/
    is.close();

    final ArchiveEntry ae = this.fileAccessHelper.createArchiveEntry(ar, "README.txt", baos.size());
    ar.putArchiveEntry(ae);
    baos.writeTo(ar);
    ar.closeArchiveEntry();
}

From source file:hudson.console.ConsoleNote.java

private ByteArrayOutputStream encodeToBytes() throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(buf));
    try {/*from  w w w  .j a va  2  s .  com*/
        oos.writeObject(this);
    } finally {
        oos.close();
    }

    ByteArrayOutputStream buf2 = new ByteArrayOutputStream();

    DataOutputStream dos = new DataOutputStream(new Base64OutputStream(buf2, true, -1, null));
    try {
        buf2.write(PREAMBLE);
        dos.writeInt(buf.size());
        buf.writeTo(dos);
    } finally {
        dos.close();
    }
    buf2.write(POSTAMBLE);
    return buf2;
}

From source file:gov.nih.nci.caarray.application.translation.geosoft.GeoSoftExporterBean.java

private void generateSoftFile(Experiment experiment, String permaLinkUrl, ArchiveOutputStream zout)
        throws IOException {
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    final Writer w = new OutputStreamWriter(bout, "UTF-8");
    final PrintWriter out = new PrintWriter(w);
    GeoSoftFileWriterUtil.writeSoftFile(experiment, permaLinkUrl, out);
    out.close();/*from w  w w . j a  va 2s.c o  m*/

    final ArchiveEntry ae = this.fileAccessHelper.createArchiveEntry(zout,
            experiment.getPublicIdentifier() + ".soft.txt", bout.size());
    zout.putArchiveEntry(ae);
    bout.writeTo(zout);
    zout.closeArchiveEntry();
}

From source file:com.kahlon.guard.controller.example.SimpleBean.java

private void writePDFToResponse(ExternalContext externalContext, ByteArrayOutputStream baos, String fileName) {
    try {/*from w  w  w  .  j av  a  2  s.  c  o m*/
        externalContext.responseReset();
        externalContext.setResponseContentType("application/pdf");
        externalContext.setResponseHeader("Expires", "0");
        externalContext.setResponseHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        externalContext.setResponseHeader("Pragma", "public");
        //externalContext.setResponseHeader("Content-disposition", "attachment;filename=" + fileName + ".pdf");
        externalContext.setResponseHeader("Content-disposition", "inline;filename=" + fileName + ".pdf");
        externalContext.setResponseContentLength(baos.size());
        OutputStream out = externalContext.getResponseOutputStream();
        baos.writeTo(out);
        externalContext.responseFlushBuffer();
    } catch (Exception e) {
        //e.printStackTrace();
    }
}

From source file:com.amalto.core.servlet.LogViewerServlet.java

private void writeLogFileChunk(long position, int maxLines, HttpServletResponse response) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);

    FileChunkLoader loader = new FileChunkLoader(file);
    FileChunkInfo chunkInfo = loader.loadChunkTo(bufferedOutputStream, position, maxLines);
    bufferedOutputStream.close();/*www . j  a v  a2 s.c  om*/

    response.setContentType("text/plain;charset=" + charset); //$NON-NLS-1$
    response.setCharacterEncoding(charset);
    response.setHeader("X-Log-Position", String.valueOf(chunkInfo.nextPosition)); //$NON-NLS-1$
    response.setHeader("X-Log-Lines", String.valueOf(chunkInfo.lines)); //$NON-NLS-1$

    OutputStream responseOutputStream = response.getOutputStream();
    outputStream.writeTo(responseOutputStream);
    responseOutputStream.close();
}

From source file:com.orange.mmp.midlet.MidletManager.java

/**
 * Builds a ZIP archive with the appropriate name
 * @param mobile/*w w  w .j a  v  a  2s .c  om*/
 * @param signMidlet
 * @param output
 * @return   The ZIP filename
 * @throws IOException
 * @throws MMPException 
 */
public String computeZip(Mobile mobile, Boolean signMidlet, OutputStream output)
        throws IOException, MMPException {
    //Compute Zip
    ZipOutputStream zipOS = new ZipOutputStream(output);
    try {
        //Get default service
        Service service = ServiceManager.getInstance().getDefaultService();

        //Create fake ticket
        DeliveryTicket ticket = new DeliveryTicket();
        ticket.setServiceId(service.getId());

        //Get navigation widget (main scene)
        Widget appWidget = WidgetManager.getInstance().getWidget(ticket.getServiceId(), mobile.getBranchId());
        if (appWidget == null)
            appWidget = WidgetManager.getInstance().getWidget(ticket.getServiceId());
        if (appWidget == null)
            throw new IOException("application " + ticket.getServiceId() + " not found");

        ByteArrayOutputStream tmpOS = null;

        //Add JAD
        zipOS.putNextEntry(
                new ZipEntry(appWidget.getName() + com.orange.mmp.midlet.Constants.JAD_FILE_EXTENSION));
        tmpOS = getJad(ticket.getId(), mobile, signMidlet, service);
        tmpOS.writeTo(zipOS);
        zipOS.closeEntry();

        //Add JAR
        zipOS.putNextEntry(
                new ZipEntry(appWidget.getName() + com.orange.mmp.midlet.Constants.JAR_FILE_EXTENSION));
        tmpOS = getJar(service.getId(), mobile, signMidlet);
        tmpOS.writeTo(zipOS);
        zipOS.closeEntry();

        zipOS.flush();

        String[] tmpVersion = appWidget.getVersion().toString().split("\\.");
        if (tmpVersion.length > 2) {
            return appWidget.getName() + "_V" + tmpVersion[0] + "." + tmpVersion[1] + appWidget.getBranchId()
                    + "." + tmpVersion[2];
        }
        return appWidget.getName() + "_V" + appWidget.getVersion() + "_" + appWidget.getBranchId();
    } finally {
        try {
            zipOS.close();
        } catch (IOException ioe) {
        }
    }
}

From source file:com.nextdoor.bender.ipc.s3.S3Transport.java

@Override
public void sendBatch(TransportBuffer buffer, LinkedHashMap<String, String> partitions, Context context)
        throws TransportException {
    S3TransportBuffer buf = (S3TransportBuffer) buffer;

    /*/*w w  w.  j  ava2 s.c  o m*/
     * Create s3 key (filepath + filename)
     */
    LinkedHashMap<String, String> parts = new LinkedHashMap<String, String>(partitions);

    String filename = parts.remove(FILENAME_KEY);

    if (filename == null) {
        filename = context.getAwsRequestId();
    }

    String key = parts.entrySet().stream().map(s -> s.getKey() + "=" + s.getValue())
            .collect(Collectors.joining("/"));

    key = (key.equals("") ? filename : key + '/' + filename);

    if (this.basePath.endsWith("/")) {
        key = this.basePath + key;
    } else if (!this.basePath.equals("")) {
        key = this.basePath + '/' + key;
    }

    // TODO: make this dynamic
    if (key.endsWith(".gz")) {
        key = key.substring(0, key.length() - 3);
    }

    /*
     * Add or strip out compression format extension
     *
     * TODO: get this based on the compression codec
     */
    if (this.compress || buf.isCompressed()) {
        key += ".bz2";
    }

    ByteArrayOutputStream os = buf.getInternalBuffer();

    /*
     * Compress stream if needed. Don't compress a compressed stream.
     */
    ByteArrayOutputStream payload;
    if (this.compress && !buf.isCompressed()) {
        payload = compress(os);
    } else {
        payload = os;
    }

    /*
     * For memory efficiency convert the output stream into an InputStream. This is done using the
     * easystream library but under the hood it uses piped streams to facilitate this process. This
     * avoids copying the entire contents of the OutputStream to populate the InputStream. Note that
     * this process creates another thread to consume from the InputStream.
     */
    final String s3Key = key;

    /*
     * Write to OutputStream
     */
    final InputStreamFromOutputStream<String> isos = new InputStreamFromOutputStream<String>() {
        public String produce(final OutputStream dataSink) throws Exception {
            /*
             * Note this is executed in a different thread
             */
            payload.writeTo(dataSink);
            return null;
        }
    };

    /*
     * Consume InputStream
     */
    try {
        sendStream(isos, s3Key, payload.size());
    } finally {
        try {
            isos.close();
        } catch (IOException e) {
            throw new TransportException(e);
        } finally {
            buf.close();
        }
    }
}

From source file:com.orange.mmp.mvc.ota.Controller.java

/**
 * Inner method used to send JAR file to client
 * @param service The service linked to the queried JAR
 * @param lang The lang of the midlet/*from   w  w  w.  jav  a  2s .  c om*/
 * @param mobileKey The mobile download key (usely the UA key)
 * @param response The HTTP response on which the file must be written
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private ModelAndView downloadJar(Service service, String mobileKey, HttpServletRequest request,
        HttpServletResponse response) throws MMPException {
    ExecutionContext executionContext = ExecutionContext.getInstance();
    executionContext.addInfoMsg("Download JAR. Service = " + (service != null ? service.getId() : "null")
            + ", mobile key = " + mobileKey);

    Mobile mobile = new Mobile();
    mobile.setKey(mobileKey);
    Mobile mobiles[] = ((Dao<Mobile>) DaoManagerFactory.getInstance().getDaoManager().getDao("mobile"))
            .find(mobile);
    if (mobiles.length == 0)
        mobile = null;
    else
        mobile = mobiles[0];

    ByteArrayOutputStream jarBytesBuffer = MidletManager.getInstance().getJar(service.getId(), mobile, false);
    Widget widget = WidgetManager.getInstance().getWidget(service.getId(), mobile.getBranchId());
    if (widget != null) {
        response.setHeader(Constants.HTTP_HEADER_CONTENDISPOSITION,
                "attachment; filename=" + widget.getName() + ".jar");
    } else {
        ModelAndView modelAndView = new ModelAndView(internalErrorView);
        return modelAndView;
    }
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(com.orange.mmp.midlet.Constants.HTTP_HEADER_JARCONTENT);
    response.setContentLength(jarBytesBuffer.size());
    OutputStream output = null;
    try {
        output = response.getOutputStream();
        jarBytesBuffer.writeTo(output);
    } catch (IOException ioe) {
        throw new MMPException("Failed to send JAR byte buffer", ioe);
    } finally {
        try {
            if (jarBytesBuffer != null)
                jarBytesBuffer.close();
            if (output != null)
                output.close();
        } catch (IOException ioe) {
            //NOP
        }
    }
    return null;
}