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:com.pdfhow.diff.UploadServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request/*  w ww . ja v  a2 s  .  com*/
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            ServletOutputStream op = response.getOutputStream();

            response.setContentType(getMimeType(file));
            response.setContentLength((int) file.length());
            response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

            byte[] bbuf = new byte[1024];
            DataInputStream in = new DataInputStream(new FileInputStream(file));

            while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                op.write(bbuf, 0, bytes);
            }

            in.close();
            op.flush();
            op.close();
        }
    } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("delfile"));
        if (file.exists()) {
            file.delete(); // TODO:check and report success
        }
    } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
        File file = new File(
                request.getServletContext().getRealPath("/") + "imgs/" + request.getParameter("getthumb"));
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg")
                    || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    BufferedImage thumb = Scalr.resize(im, 75);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else if (mimetype.endsWith("jpg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    ServletOutputStream srvos = response.getOutputStream();
                    response.setContentLength(os.size());
                    response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
                    os.writeTo(srvos);
                    srvos.flush();
                    srvos.close();
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}

From source file:org.nuxeo.ecm.platform.xmlrpc.connector.NuxeoXmlRpcServletServer.java

@Override
public void execute(XmlRpcStreamRequestConfig pConfig, ServerStreamConnection pConnection)
        throws XmlRpcException {

    ServletStreamConnection ssc = (ServletStreamConnection) pConnection;
    String uri = ssc.getRequest().getRequestURI();
    String handlerPrefix = "";
    if (!uri.endsWith("/rpc") && !uri.endsWith("/rpc/")) {
        String[] urlParts = uri.split("/");
        handlerPrefix = urlParts[urlParts.length - 1];
    }/*from w w w .  j av a  2 s .  co m*/
    log.debug("execute: ->");
    try {
        Object result;
        Throwable error;
        InputStream istream = null;
        try {
            istream = getInputStream(pConfig, pConnection);
            XmlRpcRequest request = getRequest(pConfig, istream, handlerPrefix);
            result = execute(request);
            istream.close();
            istream = null;
            error = null;
            log.debug("execute: Request performed successfully");
        } catch (Throwable t) {
            log.error("execute: Error while performing request", t);
            result = null;
            error = t;
        } finally {
            if (istream != null) {
                try {
                    istream.close();
                } catch (Throwable ignore) {

                }
            }
        }
        boolean contentLengthRequired = isContentLengthRequired(pConfig);
        ByteArrayOutputStream baos;
        OutputStream ostream;
        if (contentLengthRequired) {
            baos = new ByteArrayOutputStream();
            ostream = baos;
        } else {
            baos = null;
            ostream = pConnection.newOutputStream();
        }
        ostream = getOutputStream(pConnection, pConfig, ostream);
        try {
            if (error == null) {
                writeResponse(pConfig, ostream, result);
            } else {
                writeError(pConfig, ostream, error);
            }
            ostream.close();
            ostream = null;
        } finally {
            if (ostream != null) {
                try {
                    ostream.close();
                } catch (Throwable ignore) {
                }
            }
        }
        if (baos != null) {
            OutputStream dest = getOutputStream(pConfig, pConnection, baos.size());
            try {
                baos.writeTo(dest);
                dest.close();
                dest = null;
            } finally {
                if (dest != null) {
                    try {
                        dest.close();
                    } catch (Throwable ignore) {
                    }
                }
            }
        }
        pConnection.close();
        pConnection = null;
    } catch (IOException e) {
        throw new XmlRpcException("I/O error while processing request: " + e.getMessage(), e);
    } finally {
        if (pConnection != null) {
            try {
                pConnection.close();
            } catch (Throwable ignore) {
            }
        }
    }
    log.debug("execute: <-");
}

From source file:com.atolcd.alfresco.web.scripts.shareStats.AuditExportGet.java

@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    try {//w  ww  .j  ava2  s.  c  o  m
        if (PermissionsHelper.isAuthorized(req)) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Charset charset = Charset.forName("UTF-8"); // ISO-8859-1
            CsvWriter csv = new CsvWriter(baos, ',', charset);

            Map<String, Object> model = new HashMap<String, Object>();
            AuditQueryParameters params = wsSelectAudits.buildParametersFromRequest(req);

            String interval = req.getParameter("interval");
            String type = req.getParameter("type");
            if (type.equals("volumetry") || type.equals("users-count")) {
                String values = req.getParameter("values");
                model.put("values", values.split(","));
            } else {
                wsSelectAudits.checkForQuery(model, params, type);
            }
            buildCsvFromRequest(model, csv, params, type, interval);

            csv.close();
            res.setHeader("Content-Disposition", "attachment; filename=\"export.csv\"");
            res.setContentType("application/csv"); // application/octet-stream
            baos.writeTo(res.getOutputStream());
        } else {
            res.setStatus(Status.STATUS_UNAUTHORIZED);
        }

    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        res.reset();
    }
}

From source file:cascading.tap.hadoop.ZipInputFormatTest.java

public void testSplits() throws Exception {
    JobConf job = new JobConf();
    FileSystem currentFs = FileSystem.get(job);

    Path file = new Path(workDir, "test.zip");

    Reporter reporter = Reporter.NULL;/*from ww  w .  j  a v a  2 s  . c om*/

    int seed = new Random().nextInt();
    LOG.info("seed = " + seed);
    Random random = new Random(seed);
    FileInputFormat.setInputPaths(job, file);

    for (int entries = 1; entries < MAX_ENTRIES; entries += random.nextInt(MAX_ENTRIES / 10) + 1) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(byteArrayOutputStream);
        long length = 0;

        LOG.debug("creating; zip file with entries = " + entries);

        // for each entry in the zip file
        for (int entryCounter = 0; entryCounter < entries; entryCounter++) {
            // construct zip entries splitting MAX_LENGTH between entries
            long entryLength = MAX_LENGTH / entries;
            ZipEntry zipEntry = new ZipEntry("/entry" + entryCounter + ".txt");
            zipEntry.setMethod(ZipEntry.DEFLATED);
            zos.putNextEntry(zipEntry);

            for (length = entryCounter * entryLength; length < (entryCounter + 1) * entryLength; length++) {
                zos.write(Long.toString(length).getBytes());
                zos.write("\n".getBytes());
            }

            zos.flush();
            zos.closeEntry();
        }

        zos.flush();
        zos.close();

        currentFs.delete(file, true);

        OutputStream outputStream = currentFs.create(file);

        byteArrayOutputStream.writeTo(outputStream);
        outputStream.close();

        ZipInputFormat format = new ZipInputFormat();
        format.configure(job);
        LongWritable key = new LongWritable();
        Text value = new Text();
        InputSplit[] splits = format.getSplits(job, 100);

        BitSet bits = new BitSet((int) length);
        for (int j = 0; j < splits.length; j++) {
            LOG.debug("split[" + j + "]= " + splits[j]);
            RecordReader<LongWritable, Text> reader = format.getRecordReader(splits[j], job, reporter);

            try {
                int count = 0;

                while (reader.next(key, value)) {
                    int v = Integer.parseInt(value.toString());
                    LOG.debug("read " + v);

                    if (bits.get(v))
                        LOG.warn("conflict with " + v + " in split " + j + " at position " + reader.getPos());

                    assertFalse("key in multiple partitions.", bits.get(v));
                    bits.set(v);
                    count++;
                }

                LOG.debug("splits[" + j + "]=" + splits[j] + " count=" + count);
            } finally {
                reader.close();
            }
        }

        assertEquals("some keys in no partition.", length, bits.cardinality());
    }
}

From source file:biz.webgate.dominoext.poi.component.kernel.simpleviewexport.CSVExportProcessor.java

public void process2HTTP(ExportModel expModel, UISimpleViewExport uis, HttpServletResponse hsr,
        DateTimeHelper dth) {/*  w  ww  .  j  a va2s .co m*/
    try {
        ByteArrayOutputStream csvBAOS = new ByteArrayOutputStream();
        OutputStreamWriter csvWriter = new OutputStreamWriter(csvBAOS);
        CSVPrinter csvPrinter = new CSVPrinter(csvWriter, CSVFormat.DEFAULT);

        // BUILDING HEADER
        if (uis.isIncludeHeader()) {
            for (ExportColumn expColumn : expModel.getColumns()) {
                csvPrinter.print(expColumn.getColumnName());
            }
            csvPrinter.println();
        }
        // Processing Values
        for (ExportDataRow expRow : expModel.getRows()) {
            for (ExportColumn expColumn : expModel.getColumns()) {
                csvPrinter.print(convertValue(expRow.getValue(expColumn.getPosition()), expColumn, dth));
            }
            csvPrinter.println();
        }
        csvPrinter.flush();

        hsr.setContentType("text/csv");
        hsr.setHeader("Cache-Control", "no-cache");
        hsr.setDateHeader("Expires", -1);
        hsr.setContentLength(csvBAOS.size());
        hsr.addHeader("Content-disposition", "inline; filename=\"" + uis.getDownloadFileName() + "\"");
        OutputStream os = hsr.getOutputStream();
        csvBAOS.writeTo(os);
        os.close();
    } catch (Exception e) {
        ErrorPageBuilder.getInstance().processError(hsr, "Error during SVE-Generation (CSV Export)", e);
    }
}

From source file:org.apache.xmlrpc.server.XmlRpcStreamServer.java

/** Returns, whether the 
/** Processes a "connection". The "connection" is an opaque object, which is
 * being handled by the subclasses.//from   w w w  .j  a  va2 s . c  o  m
 * @param pConfig The request configuration.
 * @param pConnection The "connection" being processed.
 * @throws XmlRpcException Processing the request failed.
 */
public void execute(XmlRpcStreamRequestConfig pConfig, ServerStreamConnection pConnection)
        throws XmlRpcException {
    log.debug("execute: ->");
    try {
        Object result;
        Throwable error;
        InputStream istream = null;
        try {
            istream = getInputStream(pConfig, pConnection);
            XmlRpcRequest request = getRequest(pConfig, istream);
            result = execute(request);
            istream.close();
            istream = null;
            error = null;
            log.debug("execute: Request performed successfully");
        } catch (Throwable t) {
            logError(t);
            result = null;
            error = t;
        } finally {
            if (istream != null) {
                try {
                    istream.close();
                } catch (Throwable ignore) {
                }
            }
        }
        boolean contentLengthRequired = isContentLengthRequired(pConfig);
        ByteArrayOutputStream baos;
        OutputStream ostream;
        if (contentLengthRequired) {
            baos = new ByteArrayOutputStream();
            ostream = baos;
        } else {
            baos = null;
            ostream = pConnection.newOutputStream();
        }
        ostream = getOutputStream(pConnection, pConfig, ostream);
        try {
            if (error == null) {
                writeResponse(pConfig, ostream, result);
            } else {
                writeError(pConfig, ostream, error);
            }
            ostream.close();
            ostream = null;
        } finally {
            if (ostream != null) {
                try {
                    ostream.close();
                } catch (Throwable ignore) {
                }
            }
        }
        if (baos != null) {
            OutputStream dest = getOutputStream(pConfig, pConnection, baos.size());
            try {
                baos.writeTo(dest);
                dest.close();
                dest = null;
            } finally {
                if (dest != null) {
                    try {
                        dest.close();
                    } catch (Throwable ignore) {
                    }
                }
            }
        }
        pConnection.close();
        pConnection = null;
    } catch (IOException e) {
        throw new XmlRpcException("I/O error while processing request: " + e.getMessage(), e);
    } finally {
        if (pConnection != null) {
            try {
                pConnection.close();
            } catch (Throwable ignore) {
            }
        }
    }
    log.debug("execute: <-");
}

From source file:org.openqa.selenium.server.SeleniumDriverResourceHandler.java

private void respond(HttpResponse res, RemoteCommand sc, String uniqueId) throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream(1000);
    Writer writer = new OutputStreamWriter(buf, StringUtil.__UTF_8);
    if (sc != null) {
        writer.write(sc.toString());//from  www. j av a 2 s  . co m
        log.fine("res to " + uniqueId + ": " + sc.toString());
    } else {
        log.fine("res empty");
    }
    for (int pad = 998 - buf.size(); pad-- > 0;) {
        writer.write(" ");
    }
    writer.write("\015\012");
    writer.close();
    OutputStream out = res.getOutputStream();
    buf.writeTo(out);

}

From source file:gate.crowdsource.rest.CrowdFlowerClient.java

protected JsonElement request(String method, String uri, String... formData) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("URI: " + uri + ", formData: " + Arrays.toString(formData));
    }/*from   w w w  . j  a v a2 s .c om*/
    URL cfUrl = new URL(CF_ENDPOINT + uri + "?key=" + apiKey);
    HttpURLConnection connection = (HttpURLConnection) cfUrl.openConnection();
    connection.setRequestMethod(method);
    connection.setRequestProperty("Accept", "application/json");
    if (formData != null && formData.length > 0) {
        // send the form data, URL encoded
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // annoyingly CrowdFlower doesn't support chunked streaming of
        // POSTs so we have to accumulate the content in a buffer, work
        // out its size and then POST with a Content-Length header
        ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(buffer, "UTF-8"));
        try {
            for (int i = 0; i < formData.length; i++) {
                String fieldName = formData[i];
                String fieldValue = formData[++i];
                if (i > 0) {
                    writer.write("&");
                }
                writer.write(URLEncoder.encode(fieldName, "UTF-8"));
                writer.write("=");
                writer.write(URLEncoder.encode(fieldValue, "UTF-8"));
            }
        } finally {
            writer.close();
        }

        connection.setFixedLengthStreamingMode(buffer.size());
        OutputStream connectionStream = connection.getOutputStream();
        buffer.writeTo(connectionStream);
        connectionStream.close();
    }

    // parse the response as JSON
    JsonParser parser = new JsonParser();
    Reader responseReader = new InputStreamReader(connection.getInputStream(), "UTF-8");
    try {
        return parser.parse(responseReader);
    } finally {
        responseReader.close();
    }
}

From source file:edu.ucsd.xmlrpc.xmlrpc.server.XmlRpcStreamServer.java

/** Returns, whether the 
/** Processes a "connection". The "connection" is an opaque object, which is
 * being handled by the subclasses.//from w  ww.j  ava2s .  com
 * @param pConfig The request configuration.
 * @param pConnection The "connection" being processed.
 * @throws XmlRpcException Processing the request failed.
 */
public void execute(XmlRpcStreamRequestConfig pConfig, ServerStreamConnection pConnection, WebServer wServer)
        throws XmlRpcException {
    log.debug("execute: ->");
    Object result;
    Throwable error;
    try {
        InputStream istream = null;
        try {
            istream = getInputStream(pConfig, pConnection);
            XmlRpcRequest request = getRequest(pConfig, istream);

            // Ucsd modified code
            StoredRequest storedRequest = new StoredRequest((XmlRpcClientRequestImpl) request);
            if (wServer != null) {
                wServer.addRequest(storedRequest.getRequest().getJobID(), storedRequest);
            }

            result = execute(request);
            storedRequest.setValid(true);
            ;
            storedRequest.setResult(result);

            //TODO DEMO remove
            if (result.equals(-9)) {
                throw new Throwable("Server Disconnected");
            }
            // end

            istream.close();
            istream = null;
            error = null;
            log.debug("execute: Request performed successfully");
        } catch (Throwable t) {
            logError(t);
            result = null;
            error = t;
        } finally {
            if (istream != null) {
                try {
                    istream.close();
                } catch (Throwable ignore) {
                }
            }
        }
        boolean contentLengthRequired = isContentLengthRequired(pConfig);
        ByteArrayOutputStream baos;
        OutputStream ostream;
        if (contentLengthRequired) {
            baos = new ByteArrayOutputStream();
            ostream = baos;
        } else {
            baos = null;
            ostream = pConnection.newOutputStream();
        }
        ostream = getOutputStream(pConnection, pConfig, ostream);
        try {
            if (error == null) {
                writeResponse(pConfig, ostream, result);
            } else {
                writeError(pConfig, ostream, error);
            }
            ostream.close();
            ostream = null;
        } finally {
            if (ostream != null) {
                try {
                    ostream.close();
                } catch (Throwable ignore) {
                }
            }
        }
        if (baos != null) {
            OutputStream dest = getOutputStream(pConfig, pConnection, baos.size());
            try {
                baos.writeTo(dest);
                dest.close();
                dest = null;
            } finally {
                if (dest != null) {
                    try {
                        dest.close();
                    } catch (Throwable ignore) {
                    }
                }
            }
        }
        pConnection.close();
        pConnection = null;
    } catch (IOException e) {
        throw new XmlRpcException("I/O error while processing request: " + e.getMessage(), e);
    } finally {
        if (pConnection != null) {
            try {
                pConnection.close();
            } catch (Throwable ignore) {
            }
        }
    }
    log.debug("execute: <-");
}

From source file:com.nemesis.admin.UploadServlet.java

/**
 * @param request//from w  w w  .  j  a  va 2  s  . c  om
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 * response)
 *
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
        File file = getFile(request, request.getParameter("getfile"));
        if (file.exists()) {
            int bytes = 0;
            try (ServletOutputStream op = response.getOutputStream()) {
                response.setContentType(getMimeType(file));
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");

                byte[] bbuf = new byte[1024];
                DataInputStream in = new DataInputStream(new FileInputStream(file));

                while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                    op.write(bbuf, 0, bytes);
                }

                in.close();
                op.flush();
            }
        }
    } else if (request.getParameter("delfile") != null && !request.getParameter("delfile").isEmpty()) {
        File file = getFile(request, request.getParameter("delfile"));
        if (file.exists()) {
            file.delete(); // TODO:check and report success
        }
    } else if (request.getParameter("getthumb") != null && !request.getParameter("getthumb").isEmpty()) {
        File file = getFile(request, request.getParameter("getthumb"));
        if (file.exists()) {
            System.out.println(file.getAbsolutePath());
            String mimetype = getMimeType(file);
            if (mimetype.endsWith("png") || mimetype.endsWith("jpeg") || mimetype.endsWith("jpg")
                    || mimetype.endsWith("gif")) {
                BufferedImage im = ImageIO.read(file);
                if (im != null) {
                    int newWidth = 75;
                    if (request.getParameter("w") != null) {
                        try {
                            newWidth = Integer.parseInt(request.getParameter("w"));
                        } catch (Exception e) {
                            //Se mantiene el valor por defecto de 75
                        }
                    }

                    BufferedImage thumb = Scalr.resize(im, newWidth);
                    if (request.getParameter("h") != null) {
                        try {
                            thumb = Scalr.crop(thumb, newWidth, Integer.parseInt(request.getParameter("h")));
                        } catch (IllegalArgumentException | ImagingOpException e) {
                            //Se mantienen las proporciones.
                        }
                    }

                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    if (mimetype.endsWith("png")) {
                        ImageIO.write(thumb, "PNG", os);
                        response.setContentType("image/png");
                    } else if (mimetype.endsWith("jpeg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else if (mimetype.endsWith("jpg")) {
                        ImageIO.write(thumb, "jpg", os);
                        response.setContentType("image/jpeg");
                    } else {
                        ImageIO.write(thumb, "GIF", os);
                        response.setContentType("image/gif");
                    }
                    try (ServletOutputStream srvos = response.getOutputStream()) {
                        response.setContentLength(os.size());
                        response.setHeader("Content-Disposition",
                                "inline; filename=\"" + file.getName() + "\"");
                        os.writeTo(srvos);
                        srvos.flush();
                    }
                }
            }
        } // TODO: check and report success
    } else {
        PrintWriter writer = response.getWriter();
        writer.write("call POST with multipart form data");
    }
}