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:net.bull.javamelody.TestMonitoringFilter.java

private void monitoring(Map<HttpParameter, String> parameters, boolean checkResultContent)
        throws IOException, ServletException {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    expect(request.getRequestURI()).andReturn("/test/monitoring").anyTimes();
    expect(request.getRequestURL()).andReturn(new StringBuffer("/test/monitoring")).anyTimes();
    expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    expect(request.getRemoteAddr()).andReturn("here").anyTimes();
    final Random random = new Random();
    if (random.nextBoolean()) {
        expect(request.getHeaders("Accept-Encoding"))
                .andReturn(Collections.enumeration(Arrays.asList("application/gzip"))).anyTimes();
    } else {/*from   ww  w  .j ava  2s .com*/
        expect(request.getHeaders("Accept-Encoding"))
                .andReturn(Collections.enumeration(Arrays.asList("text/html"))).anyTimes();
    }
    for (final Map.Entry<HttpParameter, String> entry : parameters.entrySet()) {
        if (HttpParameter.REQUEST == entry.getKey()) {
            expect(request.getHeader(entry.getKey().getName())).andReturn(entry.getValue()).anyTimes();
        } else {
            expect(entry.getKey().getParameterFrom(request)).andReturn(entry.getValue()).anyTimes();
        }
    }
    final Range range = Period.JOUR.getRange();
    final List<JavaInformations> javaInformationsList = Collections
            .singletonList(new JavaInformations(null, false));
    // getAttribute("range") et getAttribute("javaInformationsList") pour PdfController
    expect(request.getAttribute("range")).andReturn(range).anyTimes();
    expect(request.getAttribute("javaInformationsList")).andReturn(javaInformationsList).anyTimes();
    if (parameters.isEmpty() || HttpPart.JNLP.getName().equals(parameters.get(HttpParameter.PART))) {
        // dans au moins un cas on met un cookie
        final Cookie[] cookies = { new Cookie("dummy", "dummy"),
                new Cookie(PERIOD_COOKIE_NAME, Period.SEMAINE.getCode()), };
        expect(request.getCookies()).andReturn(cookies).anyTimes();
    }
    final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    expect(response.getOutputStream()).andReturn(new FilterServletOutputStream(output)).anyTimes();
    final StringWriter stringWriter = new StringWriter();
    expect(response.getWriter()).andReturn(new PrintWriter(stringWriter)).anyTimes();
    final FilterChain chain = createNiceMock(FilterChain.class);

    replay(request);
    replay(response);
    replay(chain);
    monitoringFilter.doFilter(request, response, chain);
    verify(request);
    verify(response);
    verify(chain);

    if (checkResultContent) {
        assertTrue("result", output.size() != 0 || stringWriter.getBuffer().length() != 0);
    }
}

From source file:com.esd.ps.EmployerController.java

/**
 * ? zip//from  w  w  w .j  a  v  a 2 s.c o  m
 * 
 * @param packName
 * @param taskLvl
 */
public void storeDataZIP(String packName, int taskLvl, String url, int userId, Date date) {
    InputStream in = null;
    String zipEntryName = null;
    int packId = 0;
    try {
        ZipFile zip = new ZipFile(url + Constants.SLASH + packName);
        for (Enumeration<?> entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String taskDir = Constants.EMPTY;
            if (entry.isDirectory()) {// ?
                continue;
            }
            zipEntryName = entry.getName();
            if (zipEntryName.indexOf(Constants.SLASH) < zipEntryName.lastIndexOf(Constants.SLASH)) {
                String str[] = zipEntryName.split(Constants.SLASH);
                // (zipEntryName.indexOf("/") + 1)
                taskDir = zipEntryName.substring((zipEntryName.indexOf(Constants.SLASH) + 1),
                        zipEntryName.lastIndexOf(Constants.SLASH));
                zipEntryName = str[(str.length - 1)];
            }
            zipEntryName = zipEntryName.substring(zipEntryName.indexOf(Constants.SLASH) + 1,
                    zipEntryName.length());
            // ?
            if (zipEntryName.substring((zipEntryName.length() - 3), zipEntryName.length())
                    .equals(Constants.WAV) == false) {
                // String noMatch = zipEntryName;
                continue;
            }
            in = zip.getInputStream(entry);
            // inputstrem?byte[]
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] data = new byte[4096];
            int count = -1;
            while ((count = in.read(data, 0, 4096)) != -1)
                outStream.write(data, 0, count);
            data = null;
            byte[] wav = outStream.toByteArray();

            taskWithBLOBs taskWithBLOBs = new taskWithBLOBs();
            packId = packService.getPackIdByPackName(packName);
            // wav?0kb
            if (outStream.size() == 0) {
                taskWithBLOBs.setWorkerId(0);
            }
            taskWithBLOBs.setTaskWav(wav);
            taskWithBLOBs.setTaskLvl(taskLvl);
            // ?
            taskWithBLOBs.setPackId(packId);
            taskWithBLOBs.setTaskName(zipEntryName);
            // 
            if (taskDir.trim().length() > 0) {
                taskDir = packName.substring(0, (packName.length() - 4)) + Constants.SLASH + taskDir;
            } else {
                taskDir = packName.substring(0, (packName.length() - 4));
            }
            taskWithBLOBs.setTaskDir(taskDir);
            taskWithBLOBs.setCreateId(userId);
            taskWithBLOBs.setCreateTime(date);
            // ?
            taskWithBLOBs.setTaskUpload(false);
            StackTraceElement[] items = Thread.currentThread().getStackTrace();
            taskWithBLOBs.setCreateMethod(items[1].toString());
            taskWithBLOBs.setVersion(1);
            taskService.insert(taskWithBLOBs);
        }
        zip.close();
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    File fd = new File(packName);
    fd.delete();
    packWithBLOBs pack = new packWithBLOBs();
    pack.setPackId(packId);
    pack.setUnzip(2);// ??
    StackTraceElement[] items = Thread.currentThread().getStackTrace();
    pack.setUpdateMethod(items[1].toString());
    packService.updateByPrimaryKeySelective(pack);
}

From source file:org.apache.myfaces.application.jsp.JspStateManagerImpl.java

protected Object serializeView(FacesContext context, SerializedView serializedView) {
    if (log.isTraceEnabled())
        log.trace("Entering serializeView");

    if (isSerializeStateInSession(context)) {
        if (log.isTraceEnabled())
            log.trace("Processing serializeView - serialize state in session");

        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        try {/*  w  w w  . j  a v a  2 s  .  com*/
            OutputStream os = baos;
            if (isCompressStateInSession(context)) {
                if (log.isTraceEnabled())
                    log.trace("Processing serializeView - serialize compressed");

                os.write(COMPRESSED_FLAG);
                os = new GZIPOutputStream(os, 1024);
            } else {
                if (log.isTraceEnabled())
                    log.trace("Processing serializeView - serialize uncompressed");

                os.write(UNCOMPRESSED_FLAG);
            }
            ObjectOutputStream out = new ObjectOutputStream(os);
            out.writeObject(serializedView.getStructure());
            out.writeObject(serializedView.getState());
            out.close();
            baos.close();

            if (log.isTraceEnabled())
                log.trace("Exiting serializeView - serialized. Bytes : " + baos.size());
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("Exiting serializeView - Could not serialize state: " + e.getMessage(), e);
            return null;
        }
    } else {
        if (log.isTraceEnabled())
            log.trace("Exiting serializeView - do not serialize state in session.");
        return new Object[] { serializedView.getStructure(), serializedView.getState() };
    }
}

From source file:ch.ralscha.extdirectspring.controller.RouterController.java

@SuppressWarnings("resource")
public void writeJsonResponse(HttpServletResponse response, Object responseObject, Class<?> jsonView,
        boolean streamResponse, boolean isMultipart) throws IOException {

    ObjectMapper objectMapper = this.configurationService.getJsonHandler().getMapper();

    if (isMultipart) {
        response.setContentType(RouterController.TEXT_HTML.toString());
        response.setCharacterEncoding(RouterController.TEXT_HTML.getCharset().name());

        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        bos.write("<html><body><textarea>".getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        String responseJson;//w  ww  .ja  v  a2  s  . c o m
        if (jsonView == null) {
            responseJson = objectMapper.writeValueAsString(responseObject);
        } else {
            responseJson = objectMapper.writerWithView(jsonView).writeValueAsString(responseObject);
        }

        responseJson = responseJson.replace("&quot;", "\\&quot;");
        bos.write(responseJson.getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        String frameDomain = this.configurationService.getConfiguration().getFrameDomain();
        String frameDomainScript = "";
        if (frameDomain != null) {
            frameDomainScript = String
                    .format(this.configurationService.getConfiguration().getFrameDomainScript(), frameDomain);
        }
        bos.write(("</textarea>" + frameDomainScript + "</body></html>")
                .getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

        response.setContentLength(bos.size());
        FileCopyUtils.copy(bos.toByteArray(), response.getOutputStream());
    } else {

        response.setContentType(APPLICATION_JSON.toString());
        response.setCharacterEncoding(APPLICATION_JSON.getCharset().name());

        ServletOutputStream outputStream = response.getOutputStream();

        if (!streamResponse) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(bos, JsonEncoding.UTF8);

            if (jsonView == null) {
                objectMapper.writeValue(jsonGenerator, responseObject);
            } else {
                objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject);
            }

            response.setContentLength(bos.size());
            outputStream.write(bos.toByteArray());
            jsonGenerator.close();
        } else {
            JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(outputStream,
                    JsonEncoding.UTF8);
            if (jsonView == null) {
                objectMapper.writeValue(jsonGenerator, responseObject);
            } else {
                objectMapper.writerWithView(jsonView).writeValue(jsonGenerator, responseObject);
            }
            jsonGenerator.close();
        }

        outputStream.flush();
    }
}

From source file:net.zypr.api.Protocol.java

public byte[] doGetBytes(String url) throws APICommunicationException {
    Session.getInstance().addActiveRequestCount();
    long t1 = System.currentTimeMillis();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {/*from  ww  w  .j a va 2s  . c  om*/
        DefaultHttpClient httpclient = getHTTPClient();
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
        if (httpResponse.getStatusLine().getStatusCode() != 200)
            throw new APICommunicationException("HTTP Error " + httpResponse.getStatusLine().getStatusCode()
                    + " - " + httpResponse.getStatusLine().getReasonPhrase() + " at " + url);
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream inputStream = httpEntity.getContent();
        byte[] buffer = new byte[4096];
        int readCount = 0;
        while ((readCount = inputStream.read(buffer)) != -1)
            byteArrayOutputStream.write(buffer, 0, readCount);
        httpclient.getConnectionManager().shutdown();
    } catch (IOException ioException) {
        throw new APICommunicationException(ioException);
    } finally {
        Session.getInstance().removeActiveRequestCount();
        long t2 = System.currentTimeMillis();
        Debug.print(url + " : " + t1 + "-" + t2 + "=" + (t2 - t1) + " : " + byteArrayOutputStream.size()
                + " bytes");
    }
    return (byteArrayOutputStream.toByteArray());
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.BaseHttpResponse.java

protected void initHeaders(ExtendedHttpMethod httpMethod) {
    try {//from w ww. j  a v  a 2s .  co m
        ByteArrayOutputStream rawResponse = new ByteArrayOutputStream();
        ByteArrayOutputStream rawRequest = new ByteArrayOutputStream();

        if (!httpMethod.isFailed()) {
            try {
                rawResponse.write(String.valueOf(httpMethod.getStatusLine()).getBytes());
                rawResponse.write("\r\n".getBytes());
            } catch (Throwable e) {
            }
        }

        rawRequest.write((method + " " + String.valueOf(url) + " " + version + "\r\n").getBytes());

        requestHeaders = new StringToStringsMap();
        Header[] headers = httpMethod.getRequestHeaders();
        for (Header header : headers) {
            requestHeaders.put(header.getName(), header.getValue());
            rawRequest.write(header.toExternalForm().getBytes());
        }

        responseHeaders = new StringToStringsMap();

        if (!httpMethod.isFailed()) {
            headers = httpMethod.getResponseHeaders();
            for (Header header : headers) {
                responseHeaders.put(header.getName(), header.getValue());
                rawResponse.write(header.toExternalForm().getBytes());
            }

            responseHeaders.put("#status#", String.valueOf(httpMethod.getStatusLine()));
        }

        if (httpMethod.getRequestEntity() != null) {
            rawRequest.write("\r\n".getBytes());
            if (httpMethod.getRequestEntity().isRepeatable()) {
                requestContentPos = rawRequest.size();
                MaxSizeByteArrayOutputStream tempOut = new MaxSizeByteArrayOutputStream(
                        SoapUI.getSettings().getLong(UISettings.RAW_REQUEST_MESSAGE_SIZE, 0));
                httpMethod.getRequestEntity().writeRequest(tempOut);
                tempOut.writeTo(rawRequest);
            } else
                rawRequest.write("<request data not available>".getBytes());
        }

        if (!httpMethod.isFailed()) {
            rawResponse.write("\r\n".getBytes());
            rawResponse.write(httpMethod.getResponseBody());
        }

        rawResponseData = rawResponse.toByteArray();
        rawRequestData = rawRequest.toByteArray();
    } catch (Throwable e) {
        e.printStackTrace();
    }
}

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(method = { RequestMethod.POST, RequestMethod.GET })
public HttpEntity<byte[]> exporter(@RequestParam(value = "svg", required = false) String svg,
        @RequestParam(value = "type", required = false) String type,
        @RequestParam(value = "filename", required = false) String filename,
        @RequestParam(value = "width", required = false) String width,
        @RequestParam(value = "scale", required = false) String scale,
        @RequestParam(value = "options", required = false) String options,
        @RequestParam(value = "globaloptions", required = false) String globalOptions,
        @RequestParam(value = "constr", required = false) String constructor,
        @RequestParam(value = "callback", required = false) String callback,
        @RequestParam(value = "callbackHC", required = false) String callbackHC,
        @RequestParam(value = "async", required = false, defaultValue = "false") Boolean async,
        @RequestParam(value = "jsonp", required = false, defaultValue = "false") Boolean jsonp,
        HttpServletRequest request, HttpSession session)
        throws ServletException, InterruptedException, SVGConverterException, NoSuchElementException,
        PoolException, TimeoutException, IOException, ZeroRequestParameterException {

    MimeType mime = getMime(type);
    String randomFilename = null;
    String jsonpCallback = "";
    boolean isAndroid = request.getHeader("user-agent") != null
            && request.getHeader("user-agent").contains("Android");

    if ("GET".equalsIgnoreCase(request.getMethod())) {

        // Handle redirect downloads for Android devices, these come in without request parameters
        String tempFile = (String) session.getAttribute("tempFile");
        session.removeAttribute("tempFile");

        if (tempFile != null && !tempFile.isEmpty()) {
            logger.debug("filename stored in session, read and stream from filesystem");
            String basename = FilenameUtils.getBaseName(tempFile);
            String extension = FilenameUtils.getExtension(tempFile);

            return getFile(basename, extension);

        }/*from  www  .  ja  v a  2s  .  co  m*/
    }

    // check for visitors who don't know this domain is really only for the exporting service ;)
    if (request.getParameterMap().isEmpty()) {
        throw new ZeroRequestParameterException();
    }

    /* Most JSONP implementations use the 'callback' request parameter and this overwrites
     * the original callback parameter for chart creation with Highcharts. If JSONP is
     * used we recommend using the requestparameter callbackHC as the callback for Highcharts.
     * store the callback method name and reset the callback parameter,
     * otherwise it will be used when creation charts
     */
    if (jsonp) {
        async = true;
        jsonpCallback = callback;
        callback = null;

        if (callbackHC != null) {
            callback = callbackHC;
        }
    }

    if (isAndroid || MimeType.PDF.equals(mime) || async) {
        randomFilename = createRandomFileName(mime.name().toLowerCase());
    }

    /* If randomFilename is not null, then we want to save the filename in session, in case of GET is used later on*/
    if (isAndroid) {
        logger.debug("storing randomfile in session: " + FilenameUtils.getName(randomFilename));
        session.setAttribute("tempFile", FilenameUtils.getName(randomFilename));
    }

    String output = convert(svg, mime, width, scale, options, constructor, callback, globalOptions,
            randomFilename);
    ByteArrayOutputStream stream;

    HttpHeaders headers = new HttpHeaders();

    if (async) {
        String link = TempDir.getDownloadLink(randomFilename);
        stream = new ByteArrayOutputStream();
        if (jsonp) {
            StringBuilder sb = new StringBuilder(jsonpCallback);
            sb.append("('");
            sb.append(link);
            sb.append("')");
            stream.write(sb.toString().getBytes("utf-8"));
            headers.add("Content-Type", "text/javascript; charset=utf-8");
        } else {
            stream.write(link.getBytes("utf-8"));
            headers.add("Content-Type", "text/html; charset=UTF-8");
        }
    } else {
        headers.add("Content-Type", mime.getType() + "; charset=utf-8");
        if (randomFilename != null && randomFilename.equals(output)) {
            stream = writeFileToStream(randomFilename);
        } else {
            boolean base64 = !mime.getExtension().equals("svg");
            stream = outputToStream(output, base64);
        }
        filename = getFilename(filename);
        headers.add("Content-Disposition",
                "attachment; filename=" + filename.replace(" ", "_") + "." + mime.name().toLowerCase());
    }

    headers.setContentLength(stream.size());

    return new HttpEntity<byte[]>(stream.toByteArray(), headers);
}

From source file:net.jotel.ws.client.WebSocketClient.java

private String readFieldName(InputStream is) throws IOException {
    // This reads a field name, terminated by a colon, converting upper-case
    // ASCII letters to lowercase, and
    // aborting if a stray CR or LF is found.

    // 4.1.33. Let /name/ be empty byte array.
    ByteArrayOutputStream name = new ByteArrayOutputStream();

    // 4.1.34. Read a byte from the server.
    // If the connection closes before this byte is received, then fail the
    // WebSocket connection and abort these
    // steps.//from  ww w  .  ja  va 2s  .  com

    // Otherwise, handle the byte as described in the appropriate entry
    // below:

    int b = -1;
    while ((b = is.read()) != -1) {
        if (b == 0x0D) {
            // -> If the byte is 0x0D (ASCII CR)
            // If the /name/ byte array is empty, then jump to the fields
            // processing step. Otherwise, fail the
            // WebSocket connection and abort these steps.
            if (name.size() != 0) {
                throw new WebSocketException("Unexpected CR byte in field name!");
            }
            break;
        } else if (b == 0x0A) {
            // -> If the byte is 0x0A (ASCII LF)
            // Fail the WebSocket connection and abort these steps.
            throw new WebSocketException("Unexpected LF byte in field name!");
        } else if (b == 0x3A) {
            // -> If the byte is 0x3A (ASCII :)
            // Move on to the next step.
            break;
        } else if (b >= 0x41 && b <= 0x5A) {
            // -> If the byte is in the range 0x41 to 0x5A (ASCII A-Z)
            // Append a byte whose value is the byte's value plus 0x20 to
            // the /name/ byte array and redo this
            // step for the next byte.
            name.write(b + 0x20);
        } else {
            // -> Otherwise
            // Append the byte to the /name/ byte array and redo this step
            // for the next byte.
            name.write(b);
        }
    }

    if (b == -1) {
        throw new WebSocketException("Unexpected end of stream!");
    }

    return new String(name.toByteArray(), CharEncoding.UTF_8);
}

From source file:PngEncoder.java

/**
 * Writes the IDAT (Image data) chunks to the output stream.
 *
 * @param out the OutputStream to write the chunk to
 * @param csum the Checksum that is updated as data is written
 *             to the passed-in OutputStream
 * @throws IOException if a problem is encountered writing the output
 *//*w  ww . j  ava  2s  . c  o m*/
private void writeIdatChunks(OutputStream out, Checksum csum) throws IOException {
    int rowWidth = width * outputBpp; // size of image data in a row in bytes.

    int row = 0;

    Deflater deflater = new Deflater(compressionLevel);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DeflaterOutputStream defOut = new DeflaterOutputStream(byteOut, deflater);

    byte[] filteredPixelQueue = new byte[rowWidth];

    // Output Pixel Queues
    byte[][] outputPixelQueue = new byte[2][rowWidth];
    Arrays.fill(outputPixelQueue[1], (byte) 0);
    int outputPixelQueueRow = 0;
    int outputPixelQueuePrevRow = 1;

    while (row < height) {
        if (filter == null) {
            defOut.write(0);
            translator.translate(outputPixelQueue[outputPixelQueueRow], row);
            defOut.write(outputPixelQueue[outputPixelQueueRow], 0, rowWidth);
        } else {
            defOut.write(filter.getType());
            translator.translate(outputPixelQueue[outputPixelQueueRow], row);
            filter.filter(filteredPixelQueue, outputPixelQueue[outputPixelQueueRow],
                    outputPixelQueue[outputPixelQueuePrevRow], outputBpp);
            defOut.write(filteredPixelQueue, 0, rowWidth);
        }

        ++row;
        outputPixelQueueRow = row & 1;
        outputPixelQueuePrevRow = outputPixelQueueRow ^ 1;
    }
    defOut.finish();
    byteOut.close();

    writeInt(out, byteOut.size());
    csum.reset();
    out.write(IDAT);
    byteOut.writeTo(out);
    writeInt(out, (int) csum.getValue());
}