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:edu.cornell.med.icb.goby.compression.HybridChunkCodec2.java

@Override
public ByteArrayOutputStream encode(final Message readCollection) throws IOException {
    if (readCollection == null) {
        return null;
    }//from  w  w w.j  a  v a  2 s .com
    final ByteArrayOutputStream result = new ByteArrayOutputStream();
    final DataOutputStream completeChunkData = new DataOutputStream(result);
    final ByteArrayOutputStream hybridStreamBytes = new ByteArrayOutputStream();
    final Message reducedProtoBuff = handler.compressCollection(readCollection, hybridStreamBytes);

    final int hybridStreamSize = hybridStreamBytes.size();
    final byte[] bytes = hybridStreamBytes.toByteArray();

    crc32.reset();
    crc32.update(bytes);
    final int crcChecksum = (int) crc32.getValue();
    completeChunkData.writeInt(hybridStreamSize);
    completeChunkData.writeInt(crcChecksum);
    completeChunkData.write(bytes);

    final ByteArrayOutputStream out = bzip2Codec.encode(reducedProtoBuff);

    final byte[] gzipBytes = out.toByteArray();
    final int gzipBytesSize = gzipBytes.length;
    completeChunkData.write(gzipBytes);
    completeChunkData.flush();
    if (debug && chunkIndex % 100 == 0) {

        //TODO remove compression of original collection. Only useful for stat collection
        final int originalBZip2Size = bzip2Codec.encode(readCollection).toByteArray().length;

        final int gain = originalBZip2Size - (gzipBytesSize + hybridStreamSize);
        LOG.info(String.format(
                "compressed size=%d gzip size=%d (original gzip=%d) percent compressed/(compressed+gzip) %g gain=%d, %g%% ",
                hybridStreamSize, gzipBytesSize, originalBZip2Size,
                100d * ((double) hybridStreamSize) / (hybridStreamSize + gzipBytesSize), gain,
                gain * 100d / originalBZip2Size));

    }
    chunkIndex++;
    return result;
}

From source file:edu.cornell.med.icb.goby.compression.HybridChunkCodec1.java

@Override
public ByteArrayOutputStream encode(final Message readCollection) throws IOException {
    if (readCollection == null) {
        return null;
    }/*from w  w w .j av  a  2 s  .  com*/
    final ByteArrayOutputStream result = new ByteArrayOutputStream();
    final DataOutputStream completeChunkData = new DataOutputStream(result);
    final ByteArrayOutputStream hybridStreamBytes = new ByteArrayOutputStream();
    final Message reducedProtoBuff = handler.compressCollection(readCollection, hybridStreamBytes);

    final int hybridStreamSize = hybridStreamBytes.size();
    final byte[] bytes = hybridStreamBytes.toByteArray();

    crc32.reset();
    crc32.update(bytes);
    final int crcChecksum = (int) crc32.getValue();
    completeChunkData.writeInt(hybridStreamSize);
    completeChunkData.writeInt(crcChecksum);
    completeChunkData.write(bytes);

    final ByteArrayOutputStream out = gzipCodec.encode(reducedProtoBuff);

    final byte[] gzipBytes = out.toByteArray();
    final int gzipBytesSize = gzipBytes.length;
    completeChunkData.write(gzipBytes);
    completeChunkData.flush();
    if (debug && chunkIndex % 100 == 0) {

        //TODO remove compression of original collection. Only useful for stat collection
        int originalGzipSize = gzipCodec.encode(readCollection).toByteArray().length;

        final int gain = originalGzipSize - (gzipBytesSize + hybridStreamSize);
        LOG.info(String.format(
                "compressed size=%d gzip size=%d (original gzip=%d) percent compressed/(compressed+gzip) %g gain=%d, %g%% ",
                hybridStreamSize, gzipBytesSize, originalGzipSize,
                100d * ((double) hybridStreamSize) / (hybridStreamSize + gzipBytesSize), gain,
                gain * 100d / originalGzipSize));

    }
    chunkIndex++;
    return result;
}

From source file:org.apache.axis2.transport.local.LocalTransportSender.java

public void finalizeSendWithToAddress(MessageContext msgContext, ByteArrayOutputStream out) throws AxisFault {
    try {//from  w w  w.  j  a v  a  2 s .  c  o  m
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        ByteArrayOutputStream response = new ByteArrayOutputStream();

        LocalTransportReceiver localTransportReceiver = new LocalTransportReceiver(this, isNonBlocking());
        localTransportReceiver.processMessage(msgContext, in, response);

        in.close();
        out.close();
        if (response.size() > 0) {
            in = new ByteArrayInputStream(response.toByteArray());
            msgContext.setProperty(MessageContext.TRANSPORT_IN, in);
        }
    } catch (IOException e) {
        throw AxisFault.makeFault(e);
    }
}

From source file:org.apache.roller.weblogger.ui.core.filters.CompressionFilter.java

/** 
 * If browser does not support gzip, invoke resource normally. If browser 
 * does support gzip, set the Content-Encoding response header and invoke 
 * resource with a wrapped response that collects all the output. Extract 
 * the output and write it into a gzipped byte array. Finally, write that 
 * array to the client's output stream./*w w  w. j av a2s .c om*/
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    if (!this.enabled || !isGzipSupported(req)) {
        // Invoke resource normally.
        chain.doFilter(req, res);
    } else {
        // Tell browser we are sending it gzipped data.
        res.setHeader("Content-Encoding", "gzip");

        // Invoke resource, accumulating output in the wrapper.
        ByteArrayResponseWrapper responseWrapper = new ByteArrayResponseWrapper(response);

        chain.doFilter(req, responseWrapper);

        ByteArrayOutputStream outputStream = responseWrapper.getByteArrayOutputStream();

        // Get character array representing output.
        log.debug("Pre-zip size:" + outputStream.size());

        // Make a writer that compresses data and puts
        // it into a byte array.
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        GZIPOutputStream zipOut = new GZIPOutputStream(byteStream);

        // Compress original output and put it into byte array.
        zipOut.write(responseWrapper.getByteArrayOutputStream().toByteArray());

        // Gzip streams must be explicitly closed.
        zipOut.close();

        log.debug("Gzip size:" + byteStream.size());

        // Update the Content-Length header.
        res.setContentLength(byteStream.size());

        ByteArrayOutputStreamWrapper newOut = (ByteArrayOutputStreamWrapper) responseWrapper.getOutputStream();
        newOut.clear();
        newOut.setFinallized();

        /* now force close of OutputStream */
        newOut.write(byteStream.toByteArray());
        newOut.close();
    }

}

From source file:org.dataconservancy.dcs.util.http.RequestHeaderUtil.java

/**
 * Wrapper method to set fields in the HTTP response.
 *
 * @param response - the HttpServletResponse
 * @param etag - the etag/*from   www  .  j av a2 s  .c om*/
 * @param out - the output stream
 * @param lastModified - tha lsast modified DateTime
 * @throws IOException  an IO exception
 */
public void setResponseHeaderFields(HttpServletResponse response, String etag, ByteArrayOutputStream out,
        DateTime lastModified) throws IOException {
    // Compose the Response (headers, entity body)
    response.setHeader(ETAG, etag);
    response.setHeader(CONTENT_LENGTH, String.valueOf(out.size()));
    response.setHeader(CONTENT_TYPE, APPLICATION_XML);
    response.setHeader(LAST_MODIFIED, DateUtility.toRfc822(lastModified));

    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.dalendev.meteotndata.servlet.UpdateStationDataServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w  w  w.j a va 2 s . com*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream inputStream = request.getInputStream();
    ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();

    int length;
    byte[] buffer = new byte[1024];
    while ((length = inputStream.read(buffer)) >= 0) {
        byteArrayStream.write(buffer, 0, length);
    }

    if (byteArrayStream.size() > 0) {
        Station station = SerializationUtils.deserialize(byteArrayStream.toByteArray());
        Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO, station.getCode());

        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance(MeasurementList.class);
            Unmarshaller u = jc.createUnmarshaller();
            URL url = new URL(
                    "http://dati.meteotrentino.it/service.asmx/ultimiDatiStazione?codice=" + station.getCode());
            StreamSource src = new StreamSource(url.openStream());
            JAXBElement je = u.unmarshal(src, MeasurementList.class);
            MeasurementList measurementList = (MeasurementList) je.getValue();

            MeasurmentSamplerService mss = new MeasurmentSamplerService();
            mss.mergeMeasurment(station, measurementList);
            List<Measurement> sampledList = mss.getSampledMeasurementList();
            MeasurementDAO.storeStation(sampledList);

            if (sampledList.size() > 0) {
                Measurement lastMeasurement = sampledList.get(sampledList.size() - 1);
                station.setLastUpdate(lastMeasurement.getTimestamp());
                StationDAO.storeStation(station);
            }

            Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO,
                    "Station {0} has {1} new measurements",
                    new Object[] { station.getCode(), sampledList.size() });
        } catch (JAXBException ex) {
            Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        response.setStatus(200);
    } else {
        Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO,
                "Cannot retrieve Station's serialization");
    }
}

From source file:com.tassadar.multirommgr.installfragment.UbuntuManifest.java

public boolean downloadAndParse(Device dev) {
    ByteArrayOutputStream out = new ByteArrayOutputStream(8192);
    try {//from   ww w  .  j a  v a  2s. c o m
        final String url = dev.getUbuntuBaseUrl() + CHANNELS_PATH;
        if (!Utils.downloadFile(url, out, null, true) || out.size() == 0)
            return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        Object rawObject = new JSONTokener(out.toString()).nextValue();
        if (!(rawObject instanceof JSONObject)) {
            Log.e(TAG, "Malformed manifest format!");
            return false;
        }

        JSONObject o = (JSONObject) rawObject;
        SharedPreferences pref = MgrApp.getPreferences();

        Iterator itr = o.keys();
        while (itr.hasNext()) {
            String name = (String) itr.next();
            JSONObject c = o.getJSONObject(name);

            // Skip hidden channels
            if (c.optBoolean("hidden", false) && !pref.getBoolean(SettingsFragment.UTOUCH_SHOW_HIDDEN, false)) {
                continue;
            }

            addChannel(name, c);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }

    // Remove channels without the device we're currently running on and load images
    Iterator<Map.Entry<String, TreeMap<String, UbuntuChannel>>> f_itr = m_flavours.entrySet().iterator();
    while (f_itr.hasNext()) {
        Map<String, UbuntuChannel> channelMap = f_itr.next().getValue();
        Iterator<Map.Entry<String, UbuntuChannel>> c_itr = channelMap.entrySet().iterator();
        while (c_itr.hasNext()) {
            UbuntuChannel c = c_itr.next().getValue();

            // Devices like deb or tilapia won't be in
            // Ubuntu Touch manifests, yet the versions
            // for flo/grouper work fine - select those.
            String dev_name = dev.getName();
            if (!c.hasDevice(dev_name)) {
                dev_name = dev.getBaseVariantName();

                if (!c.hasDevice(dev_name)) {
                    c_itr.remove();
                    continue;
                }
            }

            try {
                if (!c.loadDeviceImages(dev_name, dev))
                    return false;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            // Remove channels with no images for our device
            if (!c.hasImages()) {
                c_itr.remove();
                continue;
            }

            Log.d(TAG, "Got channel: " + c.getDisplayName());
        }

        if (channelMap.isEmpty())
            f_itr.remove();
    }
    return true;
}

From source file:edu.cornell.med.icb.goby.compression.MessageChunksWriter.java

/**
 * Force the writing of the collection to the output stream.
 *
 * @param collectionBuilder The builder prepared with the growing collection of entries.
 * @throws IOException if there was an error writing the entries
 *///  ww w  . ja  v a  2s .c  o  m
public void flush(final com.google.protobuf.GeneratedMessage.Builder collectionBuilder) throws IOException {
    // Write the separation between two chunks: eight bytes with value 0xFF.

    // If we are flushing a completely empty file, that's OK, the flush() should occur.
    // Otherwise, only flush if we've appended entries.
    if (totalEntriesWritten == 0 || numAppended > 0) {
        // the position just before this chunk is written is recorded:
        currentChunkStartOffset = writtenBytes;

        assert out.size() == Integer.MAX_VALUE || out.size() == writtenBytes;

        //     System.out.println("Writting new chunk at position "+currentChunkStartOffset);
        if (LOG.isTraceEnabled()) {
            LOG.trace("writing zero bytes length=" + DELIMITER_LENGTH);
        }

        out.writeByte(chunkCodec.registrationCode());
        writtenBytes += 1;
        for (int i = 0; i < DELIMITER_LENGTH; i++) {
            out.writeByte(DELIMITER_CONTENT);
            writtenBytes += 1;
        }
        final com.google.protobuf.Message protobuffCollection = collectionBuilder.clone().build();
        // compress the read collection:

        final ByteArrayOutputStream compressedBytes = chunkCodec.encode(protobuffCollection);
        final int serializedSize = compressedBytes.size();

        if (LOG.isTraceEnabled()) {
            LOG.trace("serialized compressed size: " + serializedSize);
        }

        // write the compressed size followed by the compressed stream:
        out.writeInt(serializedSize);
        writtenBytes += 4;
        final byte[] bytes = compressedBytes.toByteArray();
        out.write(bytes);
        writtenBytes += bytes.length;
        compressedBytes.close();
        totalBytesWritten += serializedSize + 4 + DELIMITER_LENGTH;
        if (LOG.isTraceEnabled()) {
            LOG.trace("current offset: " + totalBytesWritten);

        }
        out.flush();
        numAppended = 0;
        collectionBuilder.clear();
    }
}

From source file:org.kuali.mobility.people.controllers.PeopleController.java

@RequestMapping(value = "/image/{hash}", method = RequestMethod.GET)
public void getImage(@PathVariable("hash") String imageKeyHash, Model uiModel, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    byte[] byteArray = (byte[]) request.getSession().getAttribute("People.Image.Email." + imageKeyHash);
    if (byteArray != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(byteArray.length);
        baos.write(byteArray);// ww  w.j  a v  a  2  s.  c om
        if (baos != null) {
            ServletOutputStream sos = null;
            try {
                response.setContentLength(baos.size());
                sos = response.getOutputStream();
                baos.writeTo(sos);
                sos.flush();
            } catch (Exception e) {
                LOG.error("error creating image file", e);
            } finally {
                try {
                    baos.close();
                    sos.close();
                } catch (Exception e1) {
                    LOG.error("error closing output stream", e1);
                }
            }
        }
    }
}