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:gov.utah.dts.det.ccl.actions.reports.ReportsPrintAction.java

@Action(value = "print-license-renewal-letters")
public void doPrintLicenseRenewalLetters() {
    Person person = null;/* w  w w  .j a va2s  . co  m*/
    if (specialistId != null) {
        person = personService.getPerson(specialistId);
    }
    if (person == null || person.getId() == null) {
        return;
    }

    try {
        // Default endDate to the last day of the current month
        if (endDate == null) {
            Calendar cal = Calendar.getInstance();
            int maxDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
            cal.set(Calendar.DAY_OF_MONTH, maxDay);
            endDate = cal.getTime();
        }

        List<FacilityLicenseView> licenses = facilityService.getFosterCareRenewalLicensesBySpecialist(endDate,
                specialistId);
        ByteArrayOutputStream ba = LicenseRenewalLettersReport.generate(licenses);
        if (ba != null && ba.size() > 0) {
            // This is where the response is set
            String filename = "";
            if (person != null) {
                if (StringUtils.isNotBlank(person.getFirstName())) {
                    filename += person.getFirstName();
                }
                if (StringUtils.isNotBlank(person.getLastName())) {
                    if (filename.length() > 0) {
                        filename += "_";
                    }
                    filename += person.getLastName();
                }
            }
            if (filename.length() > 0) {
                filename += "_";
            }
            filename += "license_renewal_letters.pdf";
            sendToResponse(ba, filename);
        }
    } catch (Exception ex) {
        generateErrorPdf();
    }
}

From source file:net.facework.core.http.ModAssetServer.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws HttpException, IOException {
    AbstractHttpEntity body = null;/*from  w w w  .j a v a 2 s. c om*/

    final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }

    final String url = URLDecoder.decode(request.getRequestLine().getUri());
    if (request instanceof HttpEntityEnclosingRequest) {
        HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
        byte[] entityContent = EntityUtils.toByteArray(entity);
        Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length);
    }

    final String location = "www" + (url.equals("/") ? "/index.htm" : url);
    response.setStatusCode(HttpStatus.SC_OK);

    try {
        Log.i(TAG, "Requested: \"" + url + "\"");

        // Compares the Last-Modified date header (if present) with the If-Modified-Since date
        if (request.containsHeader("If-Modified-Since")) {
            try {
                Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue());
                if (date.compareTo(mServer.mLastModified) <= 0) {
                    // The file has not been modified
                    response.setStatusCode(HttpStatus.SC_NOT_MODIFIED);
                    return;
                }
            } catch (DateParseException e) {
                e.printStackTrace();
            }
        }

        // We determine if the asset is compressed
        try {
            AssetFileDescriptor afd = mAssetManager.openFd(location);

            // The asset is not compressed
            FileInputStream fis = new FileInputStream(afd.getFileDescriptor());
            fis.skip(afd.getStartOffset());
            body = new InputStreamEntity(fis, afd.getDeclaredLength());

            Log.d(TAG, "Serving uncompressed file " + "www" + url);

        } catch (FileNotFoundException e) {

            // The asset may be compressed
            // AAPT compresses assets so first we need to uncompress them to determine their length
            InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000);
            byte[] tmp = new byte[4096];
            int length = 0;
            while ((length = stream.read(tmp)) != -1)
                buffer.write(tmp, 0, length);
            body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size());
            stream.close();

            Log.d(TAG, "Serving compressed file " + "www" + url);

        }

        body.setContentType(getMimeMediaType(url) + "; charset=UTF-8");
        response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified));

    } catch (IOException e) {
        // File does not exist
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        body = new EntityTemplate(new ContentProducer() {
            @Override
            public void writeTo(final OutputStream outstream) throws IOException {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                writer.write("<html><body><h1>");
                writer.write("File ");
                writer.write("www" + url);
                writer.write(" not found");
                writer.write("</h1></body></html>");
                writer.flush();
            }
        });
        Log.d(TAG, "File " + "www" + url + " not found");
        body.setContentType("text/html; charset=UTF-8");
    }

    response.setEntity(body);

}

From source file:io.warp10.script.functions.URLFETCH.java

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    if (!stack.isAuthenticated()) {
        throw new WarpScriptException(getName() + " requires the stack to be authenticated.");
    }/*  ww w .  j av  a  2s.  com*/

    Object o = stack.pop();

    if (!(o instanceof String) && !(o instanceof List)) {
        throw new WarpScriptException(getName() + " expects a URL or list thereof on top of the stack.");
    }

    List<URL> urls = new ArrayList<URL>();

    try {
        if (o instanceof String) {
            urls.add(new URL(o.toString()));
        } else {
            for (Object oo : (List) o) {
                urls.add(new URL(oo.toString()));
            }
        }
    } catch (MalformedURLException mue) {
        throw new WarpScriptException(getName() + " encountered an invalid URL.");
    }

    //
    // Check URLs
    //

    for (URL url : urls) {
        if (!StandaloneWebCallService.checkURL(url)) {
            throw new WarpScriptException(getName() + " encountered an invalid URL '" + url + "'");
        }
    }

    //
    // Check that we do not exceed the maxurlfetch limit
    //

    AtomicLong urlfetchCount = (AtomicLong) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_COUNT);
    AtomicLong urlfetchSize = (AtomicLong) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_SIZE);

    if (urlfetchCount.get()
            + urls.size() > (long) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_LIMIT)) {
        throw new WarpScriptException(getName() + " is limited to "
                + stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_LIMIT) + " calls.");
    }

    List<Object> results = new ArrayList<Object>();

    for (URL url : urls) {
        urlfetchCount.addAndGet(1);

        HttpURLConnection conn = null;

        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(false);
            conn.setRequestMethod("GET");

            byte[] buf = new byte[8192];

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            InputStream in = conn.getInputStream();

            while (true) {
                int len = in.read(buf);

                if (len < 0) {
                    break;
                }

                if (urlfetchSize.get() + baos.size()
                        + len > (long) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_MAXSIZE)) {
                    throw new WarpScriptException(getName()
                            + " would exceed maximum size of content which can be retrieved via URLFETCH ("
                            + stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_MAXSIZE) + " bytes)");
                }

                baos.write(buf, 0, len);
            }

            urlfetchSize.addAndGet(baos.size());

            List<Object> res = new ArrayList<Object>();

            res.add(conn.getResponseCode());
            Map<String, List<String>> hdrs = conn.getHeaderFields();

            if (hdrs.containsKey(null)) {
                List<String> statusMsg = hdrs.get(null);
                if (statusMsg.size() > 0) {
                    res.add(statusMsg.get(0));
                } else {
                    res.add("");
                }
            } else {
                res.add("");
            }
            hdrs.remove(null);
            res.add(hdrs);
            res.add(Base64.encodeBase64String(baos.toByteArray()));

            results.add(res);
        } catch (IOException ioe) {
            throw new WarpScriptException(getName() + " encountered an error while fetching '" + url + "'");
        } finally {
            if (null != conn) {
                conn.disconnect();
            }
        }
    }

    stack.push(results);

    return stack;
}

From source file:org.codeqinvest.codechanges.scm.svn.SvnFileRetrieverService.java

/**
 * Loads a given version (revision) of a file from a svn server.
 *
 * @return the loaded file from the svn server
 * @throws SVNException                 if errors occur during communication with the svn server
 * @throws UnsupportedEncodingException if the read bytes cannot be converted to string with encoding supplied by {@code connectionSettings}
 *///from   w w w  .  j  av a  2 s  . c  om
SvnFile getFile(ScmConnectionSettings connectionSettings, String file, long revision)
        throws SVNException, UnsupportedEncodingException {
    ByteArrayOutputStream content = new ByteArrayOutputStream();
    SVNProperties properties = new SVNProperties();
    SvnRepositoryFactory.create(connectionSettings).getFile(file, revision, properties, content);

    final String eolStyle = properties.getStringValue(SVNProperty.EOL_STYLE);
    final String fileContent = new String(content.toByteArray(), connectionSettings.getEncoding());
    log.debug("Retrieved revision {} of file {} ({} bytes, eol = {}) from subversion", revision, file,
            content.size(), eolStyle);
    return new SvnFile(fileContent, getLineSeparator(eolStyle));
}

From source file:org.jolokia.history.HistoryStore.java

/**
 * Get the size of this history store in bytes
 *
 * @return size in bytes//w  ww  .ja va 2  s .c  o m
 */
public synchronized int getSize() {
    try {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        ObjectOutputStream oOut = new ObjectOutputStream(bOut);
        oOut.writeObject(historyStore);
        bOut.close();
        return bOut.size();
    } catch (IOException e) {
        throw new IllegalStateException("Cannot serialize internal store: " + e, e);
    }
}

From source file:org.apache.nutch.analysis.lang.LanguageIdentifier.java

/**
 * Identify language from input stream./*w w  w. ja va 2  s  .co  m*/
 * 
 * @param is is the input stream to analyze.
 * @param charset is the charset to use to read the input stream.
 * @return The 2 letter
 *         <a href="http://www.w3.org/WAI/ER/IG/ert/iso639.htm">ISO 639
 *         language code</a> (en, fi, sv, ...) of the language that best
 *         matches the content of the specified input stream.
 * @throws IOException if something wrong occurs on the input stream.
 */
public String identify(InputStream is, String charset) throws IOException {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[2048];
    int len = 0;

    while (((len = is.read(buffer)) != -1) && ((analyzeLength == 0) || (out.size() < analyzeLength))) {
        if (analyzeLength != 0) {
            len = Math.min(len, analyzeLength - out.size());
        }
        out.write(buffer, 0, len);
    }
    return identify((charset == null) ? out.toString() : out.toString(charset));
}

From source file:gov.utah.dts.det.ccl.actions.reports.ReportsPrintAction.java

@Action(value = "print-facility-license-detail")
public void doPrintLicensorFacilityDetail() {
    Person person = null;/*from w  w w.j a  va 2  s.  co m*/
    if (specialistId != null) {
        person = personService.getPerson(specialistId);
    }
    if (person == null || person.getId() == null) {
        return;
    }

    try {
        List<FacilityLicenseView> licenses = facilityService.getFacilityLicenseDetail(specialistId, endDate);
        ByteArrayOutputStream ba = FacilityLicenseDetailReport.generate(person, endDate, licenses);
        if (ba != null && ba.size() > 0) {
            // This is where the response is set
            String filename = "";
            if (person != null) {
                if (StringUtils.isNotBlank(person.getFirstName())) {
                    filename += person.getFirstName();
                }
                if (StringUtils.isNotBlank(person.getLastName())) {
                    if (filename.length() > 0) {
                        filename += "_";
                    }
                    filename += person.getLastName();
                }
            }
            if (filename.length() > 0) {
                filename += "_";
            }
            filename += "facility_license_detail.pdf";
            sendToResponse(ba, filename);
        }
    } catch (Exception ex) {
        generateErrorPdf();
    }
}

From source file:org.apache.tinkerpop.gremlin.structure.util.star.StarGraphTest.java

private Pair<StarGraph, Integer> serializeDeserialize(final StarGraph starGraph) {
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {/*  w w  w . j a  v a 2 s.com*/
        graph.io(IoCore.gryo()).writer().create().writeObject(outputStream, starGraph);
        return Pair.with(
                graph.io(IoCore.gryo()).reader().create()
                        .readObject(new ByteArrayInputStream(outputStream.toByteArray()), StarGraph.class),
                outputStream.size());
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:org.jsnap.http.base.HttpServlet.java

protected void doService(org.apache.http.HttpRequest request, org.apache.http.HttpResponse response)
        throws HttpException, IOException {
    // Client might keep the executing thread blocked for very long unless this header is added.
    response.addHeader(new Header(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE));
    // Create a wrapped request object.
    String uri, data;/* w  w w .j av a  2  s.c om*/
    String method = request.getRequestLine().getMethod();
    if (method.equals(HttpGet.METHOD_NAME)) {
        BasicHttpRequest get = (BasicHttpRequest) request;
        data = get.getRequestLine().getUri();
        int ix = data.indexOf('?');
        uri = (ix < 0 ? data : data.substring(0, ix));
        data = (ix < 0 ? "" : data.substring(ix + 1));
    } else if (method.equals(HttpPost.METHOD_NAME)) {
        BasicHttpEntityEnclosingRequest post = (BasicHttpEntityEnclosingRequest) request;
        HttpEntity postedEntity = post.getEntity();
        uri = post.getRequestLine().getUri();
        data = EntityUtils.toString(postedEntity);
    } else {
        response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
        response.setHeader(new Header(HTTP.CONTENT_LEN, "0"));
        return;
    }
    String cookieLine = "";
    if (request.containsHeader(COOKIE)) {
        Header[] cookies = request.getHeaders(COOKIE);
        for (Header cookie : cookies) {
            if (cookieLine.length() > 0)
                cookieLine += "; ";
            cookieLine += cookie.getValue();
        }
    }
    HttpRequest req = new HttpRequest(uri, underlying, data, cookieLine);
    // Create a wrapped response object.
    ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
    HttpResponse resp = new HttpResponse(out);
    // Do implementation specific processing.
    doServiceImpl(req, resp);
    out.flush(); // It's good practice to do this.
    // Do the actual writing to the actual response object.
    if (resp.redirectTo != null) {
        // Redirection is requested.
        resp.statusCode = HttpStatus.SC_MOVED_TEMPORARILY;
        response.setStatusCode(resp.statusCode);
        Header redirection = new Header(LOCATION, resp.redirectTo);
        response.setHeader(redirection);
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, redirection.toString());
    } else {
        // There will be a response entity.
        response.setStatusCode(resp.statusCode);
        HttpEntity entity;
        Header contentTypeHeader;
        boolean text = resp.contentType.startsWith(Formatter.TEXT);
        if (text) { // text/* ...
            entity = new StringEntity(out.toString(resp.characterSet), resp.characterSet);
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE,
                    resp.contentType + HTTP.CHARSET_PARAM + resp.characterSet);
        } else { // application/octet-stream, image/* ...
            entity = new ByteArrayEntity(out.toByteArray());
            contentTypeHeader = new Header(HTTP.CONTENT_TYPE, resp.contentType);
        }
        boolean acceptsGzip = clientAcceptsGzip(request);
        long contentLength = entity.getContentLength();
        // If client accepts gzipped content, the implementing object requested that response
        // gets gzipped and size of the response exceeds implementing object's size threshold
        // response entity will be gzipped.
        boolean gzipped = false;
        if (acceptsGzip && resp.zipSize > 0 && contentLength >= resp.zipSize) {
            ByteArrayOutputStream zipped = new ByteArrayOutputStream(BUFFER_SIZE);
            GZIPOutputStream gzos = new GZIPOutputStream(zipped);
            entity.writeTo(gzos);
            gzos.close();
            entity = new ByteArrayEntity(zipped.toByteArray());
            contentLength = zipped.size();
            gzipped = true;
        }
        // This is where true writes are made.
        Header contentLengthHeader = new Header(HTTP.CONTENT_LEN, Long.toString(contentLength));
        Header contentEncodingHeader = null;
        response.setHeader(contentTypeHeader);
        response.setHeader(contentLengthHeader);
        if (gzipped) {
            contentEncodingHeader = new Header(CONTENT_ENCODING, Formatter.GZIP);
            response.setHeader(contentEncodingHeader);
        }
        response.setEntity(entity);
        // Log critical headers.
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG,
                "Status Code: " + Integer.toString(resp.statusCode));
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentTypeHeader.toString());
        if (gzipped)
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentEncodingHeader.toString());
        Logger.getLogger(HttpServlet.class).log(Level.DEBUG, contentLengthHeader.toString());
    }
    // Log cookies.
    for (Cookie cookie : resp.cookies) {
        if (cookie.valid()) {
            Header h = new Header(SET_COOKIE, cookie.toString());
            response.addHeader(h);
            Logger.getLogger(HttpServlet.class).log(Level.DEBUG, h.toString());
        }
    }
}

From source file:org.apache.taverna.scufl2.wfdesc.TestConvertToWfdesc.java

private void help(String argName) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintStream outBuf = new PrintStream(out);

    ByteArrayOutputStream err = new ByteArrayOutputStream();
    PrintStream errBuf = new PrintStream(err);

    try {/*from   w  w  w  .ja va 2  s  .  c o  m*/
        System.setOut(outBuf);
        System.setErr(errBuf);
        ConvertToWfdesc.main(new String[] { argName });
    } finally {
        restoreStd();
    }
    out.flush();
    out.close();
    err.flush();
    err.close();

    assertEquals(0, err.size());
    String help = out.toString("utf-8");
    //      System.out.println(help);
    assertTrue(help.contains("scufl2-to-wfdesc"));
    assertTrue(help.contains("\nIf no arguments are given"));
}