Example usage for java.io ByteArrayOutputStream size

List of usage examples for java.io ByteArrayOutputStream size

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream size.

Prototype

public synchronized int size() 

Source Link

Document

Returns the current size of the buffer.

Usage

From source file:OutSimplePdf.java

public void makePdf(HttpServletRequest request, HttpServletResponse response, String methodGetPost)
        throws ServletException, IOException {
    try {/*from  w w  w  . j  a v a2s.c o m*/

        String msg = "your message";

        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        document.open();
        document.add(new Paragraph(msg));
        document.add(Chunk.NEWLINE);
        document.add(new Paragraph("a paragraph"));
        document.close();

        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");

        response.setContentType("application/pdf");

        response.setContentLength(baos.size());

        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();

    } catch (Exception e2) {
        System.out.println("Error in " + getClass().getName() + "\n" + e2);
    }
}

From source file:org.jbpm.designer.web.server.menu.connector.commands.AbstractCommand.java

protected void checkUploadFile(String fileName, ByteArrayOutputStream os) throws Exception {
    if (!_checkName(fileName)) {
        throw new Exception("Invalid upload file name: " + fileName);
    }//from ww w. j a  v  a2  s .co  m
    int uploadSizeOctets = os.size();
    checkUploadSizes(uploadSizeOctets);
}

From source file:com.sapito.direccion.PdfView.java

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

    ByteArrayOutputStream baos = createTemporaryOutputStream();
    Document document = new Document(PageSize.LETTER);
    PdfWriter pdfWriter = PdfWriter.getInstance(document, baos);
    pdfWriter.setViewerPreferences(PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage);

    document.open();/* w  w  w  .  j  a v a2 s. c  o  m*/
    buildPdfDocument(model, document, pdfWriter, request, response);
    document.close();

    response.setHeader("Content-Disposition",
            "attachment; filename=" + model.get("filename").toString() + ".pdf");
    //response.setContentLength(baos.size());
    System.out.println("size:" + baos.size());
    writeToResponse(response, baos);

}

From source file:org.archive.wayback.replay.swf.SWFReplayRenderer.java

@Override
public void renderResource(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        WaybackRequest wbRequest, CaptureSearchResult result, Resource httpHeadersResource,
        Resource payloadResource, ResultURIConverter uriConverter, CaptureSearchResults results)
        throws ServletException, IOException, WaybackException {

    try {//from  ww  w  . j a  v  a2 s .  c  o m

        // copy HTTP response code:
        HttpHeaderOperation.copyHTTPMessageHeader(httpHeadersResource, httpResponse);

        // load and process original headers:
        Map<String, String> headers = HttpHeaderOperation.processHeaders(httpHeadersResource, result,
                uriConverter, httpHeaderProcessor);

        // The URL of the resource, for resolving embedded relative URLs:
        URL url = null;
        try {
            url = new URL(result.getOriginalUrl());
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
            throw new IOException(e1.getMessage());
        }
        // the date to associate with the embedded, rewritten URLs:
        String datespec = result.getCaptureTimestamp();
        SWFUrlRewriter rw = new SWFUrlRewriter(uriConverter, url, datespec);

        // OK, try to read the input movie:
        Movie movie = getRobustMovie(RobustMovieDecoder.DECODE_RULE_NULLS);

        try {
            movie.decodeFromStream(payloadResource);
        } catch (DataFormatException e1) {
            throw new BadContentException(e1.getLocalizedMessage());
        }
        Movie outMovie = new Movie(movie);

        List<MovieTag> inTags = movie.getObjects();
        ArrayList<MovieTag> outTags = new ArrayList<MovieTag>();
        for (MovieTag tag : inTags) {
            outTags.add(rewriteTag(rw, tag));
        }
        outMovie.setObjects(outTags);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            outMovie.encodeToStream(baos);
        } catch (DataFormatException e) {
            throw new BadContentException(e.getLocalizedMessage());
        }

        // put the new corrected length:
        headers.put(HttpHeaderOperation.HTTP_LENGTH_HEADER, String.valueOf(baos.size()));

        // send the new headers:
        HttpHeaderOperation.sendHeaders(headers, httpResponse);

        // and copy the stored up byte-stream:
        baos.writeTo(httpResponse.getOutputStream());
    } catch (Exception e) {

        // Redirect to identity if there are any issues
        throw new BetterRequestException(UrlOperations.computeIdentityUrl(wbRequest));
    }
}

From source file:org.everit.osgi.dev.maven.util.FileManager.java

public byte[] tryReadingAmount(final RandomAccessFile is, final int amount) throws IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream(amount);
    byte[] buffer = new byte[amount];
    int r = is.read(buffer);
    while ((r > -1) && (bout.size() < amount)) {
        bout.write(buffer, 0, r);//from www  .ja  va2s  .  co  m
        r = is.read(buffer, 0, amount - bout.size());
    }
    return bout.toByteArray();
}

From source file:com.android.internalcopy.http.multipart.Part.java

/**
 * Return the full length of all the data.
 * If you override this method make sure to override 
 * #send(OutputStream) as well/*ww w  .ja v  a2s.co  m*/
 * 
 * @return long The length.
 * @throws IOException If an IO problem occurs
 */
public long length() throws IOException {
    if (lengthOfData() < 0) {
        return -1;
    }
    ByteArrayOutputStream overhead = new ByteArrayOutputStream();
    sendStart(overhead);
    sendDispositionHeader(overhead);
    sendContentTypeHeader(overhead);
    sendTransferEncodingHeader(overhead);
    sendEndOfHeader(overhead);
    sendEnd(overhead);
    return overhead.size() + lengthOfData();
}

From source file:com.fastbootmobile.encore.app.fragments.RecognitionFragment.java

private void loadAlbumArt(final String urlString, final ImageView iv) {
    new Thread() {
        public void run() {
            URL url;//from w ww  .j ava  2 s  . c o m
            try {
                url = new URL(urlString);
            } catch (MalformedURLException e) {
                // Too bad
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mIvArt.setImageResource(R.drawable.album_placeholder);
                    }
                });
                return;
            }

            Log.d(TAG, "Loading album art: " + urlString);

            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                InputStream is = conn.getInputStream();
                byte[] buffer = new byte[8192];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int read;
                while ((read = is.read(buffer)) > 0) {
                    baos.write(buffer, 0, read);
                }

                final Bitmap bmp = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size());
                if (bmp != null) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            iv.setImageBitmap(bmp);
                            iv.setVisibility(View.VISIBLE);
                        }
                    });
                } else {
                    Log.e(TAG, "Null bitmap from image");
                }
            } catch (IOException e) {
                Log.e(TAG, "Error downloading album art", e);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        iv.setImageResource(R.drawable.album_placeholder);
                        iv.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    }.start();
}

From source file:com.adito.core.MessageResourceLoaderServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String name = request.getPathInfo().substring(1);
    if (name.equals("")) {
        log.error("No name supplied to the class loader servlet.");
        response.sendError(500);/*from w  w  w .  j  a  v  a 2s .com*/
        return;
    }
    int idx = name.lastIndexOf('/');
    String basename = name;
    if (idx != -1) {
        basename = name.substring(idx + 1);
    }
    if (!basename.startsWith("ApplicationResources")
            || (!basename.endsWith(".properties") && !basename.endsWith(".class"))) {
        log.debug("Attempt to load something other that a resource bundle via the class loader servlet.");
        response.sendError(500);
        return;
    }

    /* This is a hack to get around the problem where we never get
     * get a request for the default language resources when they are
     * in a properties file. This is because we use a class loader on
     * the client end to retrieve the resources.
     */

    if (basename.endsWith(".class")) {
        basename = basename.substring(0, basename.length() - 6) + ".properties";
        name = name.substring(0, name.length() - 6) + ".properties";
    }

    /*
     * Load into byte array so we get the content length before sending on
     * to the client
     */
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    InputStream in = ContextHolder.getContext().getContextLoader().getResourceAsStream(name);
    if (in == null) {
        response.setContentType("text/plain");
        response.sendError(404, "Class not found");
    } else {
        try {
            Util.copy(in, bout);
        } finally {
            bout.close();
            in.close();
        }
        response.setContentType("text/plain");
        response.setContentLength(bout.size());
        response.setStatus(200);
        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        sendFile(bin, bout.size(), response);
    }
}

From source file:org.apache.jmeter.protocol.tcp.sampler.BinaryTCPClientImpl.java

/**
 * Reads data until the defined EOM byte is reached.
 * If there is no EOM byte defined, then reads until
 * the end of the stream is reached./*from  ww  w. j  a v  a 2s . c om*/
 * Response data is converted to hex-encoded binary
 * @return hex-encoded binary string
 * @throws ReadException when reading fails
 */
@Override
public String read(InputStream is) throws ReadException {
    ByteArrayOutputStream w = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[4096];
        int x = 0;
        while ((x = is.read(buffer)) > -1) {
            w.write(buffer, 0, x);
            if (useEolByte && (buffer[x - 1] == eolByte)) {
                break;
            }
        }

        IOUtils.closeQuietly(w); // For completeness
        final String hexString = JOrphanUtils.baToHexString(w.toByteArray());
        if (log.isDebugEnabled()) {
            log.debug("Read: " + w.size() + "\n" + hexString);
        }
        return hexString;
    } catch (IOException e) {
        throw new ReadException("", e, JOrphanUtils.baToHexString(w.toByteArray()));
    }
}

From source file:org.bibsonomy.rest.RestServlet.java

/**
 * Sends an error to the client.//  w  ww  .  j a  va2 s . c o m
 * 
 * @param request
 *            the current {@link HttpServletRequest} object.
 * @param response
 *            the current {@link HttpServletResponse} object.
 * @param code
 *            the error code to send.
 * @param message
 *            the message to send.
 * @throws IOException
 */
private void sendError(final HttpServletRequest request, final HttpServletResponse response, final int code,
        final String message) throws IOException {
    // get renderer
    final RenderingFormat mediaType = RESTUtils.getRenderingFormatForRequest(request.getParameterMap(),
            request.getHeader(HeaderUtils.HEADER_ACCEPT), request.getContentType());
    final Renderer renderer = rendererFactory.getRenderer(mediaType);

    // send error
    response.setStatus(code);
    response.setContentType(mediaType.getMimeType());
    final ByteArrayOutputStream cachingStream = new ByteArrayOutputStream();
    final Writer writer = new OutputStreamWriter(cachingStream, Charset.forName(RESPONSE_ENCODING));
    renderer.serializeError(writer, message);
    response.setContentLength(cachingStream.size());
    response.getOutputStream().print(cachingStream.toString(RESPONSE_ENCODING));
}