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:nl.b3p.kaartenbalie.service.KBImageTool.java

/** Reads an image from an http input stream.
 *
 * @param is Inputstream//w ww .j  a  v a  2  s . c  o  m
 * @param mime String representing the mime type of the image.
 *
 * @return BufferedImage
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="readImage(GetMethod method, String mime) method.">
public static BufferedImage readImage(InputStream is, String mime, ServiceProviderRequest wmsRequest)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int bytesRead = 0;
    byte[] buffer = new byte[2048];
    while (bytesRead != -1) {
        bytesRead = is.read(buffer, 0, buffer.length);
        if (bytesRead > 0)
            baos.write(buffer, 0, bytesRead);
    }

    if (mime.indexOf(";") != -1) {
        mime = mime.substring(0, mime.indexOf(";"));
    }
    String mimeType = getMimeType(mime);
    if (mimeType == null) {
        String message = baos.toString();
        message = message.replaceAll("(\\r|\\n)", "");
        log.error("Response from server not understood (mime = " + mime + "): " + message);
        throw new Exception("Response from server not understood (mime = " + mime + "): " + message);
    }

    ImageReader ir = getReader(mimeType);
    if (ir == null) {
        log.error("no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1));
        throw new Exception(
                "no reader available for imageformat: " + mimeType.substring(mimeType.lastIndexOf("/") + 1));
    }

    //TODO Make smarter.. Possibly faster... But keep reporting!
    wmsRequest.setBytesReceived(new Long(baos.size()));
    ImageInputStream stream = ImageIO.createImageInputStream(new ByteArrayInputStream(baos.toByteArray()));
    ir.setInput(stream, true);
    try {
        //if image is a png, has no alpha and has a tRNS then make that color transparent.
        BufferedImage i = ir.read(0);
        if (!i.getColorModel().hasAlpha() && ir.getImageMetadata(0) instanceof PNGMetadata) {
            PNGMetadata metadata = (PNGMetadata) ir.getImageMetadata(0);
            if (metadata.tRNS_present) {
                int alphaPix = (metadata.tRNS_red << 16) | (metadata.tRNS_green << 8) | (metadata.tRNS_blue);
                BufferedImage tmp = new BufferedImage(i.getWidth(), i.getHeight(), BufferedImage.TYPE_INT_ARGB);
                for (int x = 0; x < i.getWidth(); x++) {
                    for (int y = 0; y < i.getHeight(); y++) {
                        int rgb = i.getRGB(x, y);
                        rgb = (rgb & 0xFFFFFF) == alphaPix ? alphaPix : rgb;
                        tmp.setRGB(x, y, rgb);
                    }
                }
                i = tmp;
            }
        }
        return i;
    } finally {
        ir.dispose();
    }
}

From source file:com.chanapps.four.multipartmime.Part.java

/**
 * Return the full length of all the data.
 * If you override this method make sure to override 
 * #send(OutputStream) as well//w  ww  .  j  a  v  a  2  s .  c  o  m
 * 
 * @return long The length.
 * @throws IOException If an IO problem occurs
 */
public long length() throws IOException {
    if (DEBUG)
        Log.d(TAG, "enter length()");
    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.dragoniade.deviantart.deviation.SearchRss.java

public List<Collection> getCollections() {
    List<Collection> collections = new ArrayList<Collection>();

    if (search.getCollection() == null) {
        collections.add(null);//from   ww w .  ja  va2s .c o m
        return collections;
    }

    String queryString = "http://" + user + ".deviantart.com/" + search.getCollection() + "/";
    GetMethod method = new GetMethod(queryString);

    try {
        int sc = -1;
        do {
            sc = client.executeMethod(method);
            if (sc != 200) {
                LoggableException ex = new LoggableException(method.getResponseBodyAsString());
                Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), ex);

                int res = DialogHelper.showConfirmDialog(owner,
                        "An error has occured when contacting deviantART : error " + sc + ". Try again?",
                        "Continue?", JOptionPane.YES_NO_OPTION);
                if (res == JOptionPane.NO_OPTION) {
                    return null;
                }
            }
        } while (sc != 200);

        InputStream is = method.getResponseBodyAsStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer = new byte[4096];
        int read = -1;
        while ((read = is.read(buffer)) > -1) {
            baos.write(buffer, 0, read);
            if (baos.size() > 2097152) {
                int res = DialogHelper.showConfirmDialog(owner,
                        "An error has occured: The document is too big (over 2 megabytes) and look suspicious. Abort?",
                        "Continue?", JOptionPane.YES_NO_OPTION);
                if (res == JOptionPane.YES_NO_OPTION) {
                    return null;
                }
            }
        }
        String charsetName = method.getResponseCharSet();
        String body = baos.toString(charsetName);
        String regex = user + ".deviantart.com/" + search.getCollection() + "/([0-9]+)\"[^>]*>([^<]+)<";
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(body);
        while (matcher.find()) {
            String id = matcher.group(1);
            String name = matcher.group(2);
            Collection c = new Collection(Long.parseLong(id), name);
            collections.add(c);
        }
    } catch (IOException e) {
    } finally {
        method.releaseConnection();
    }

    collections.add(null);
    return collections;
}

From source file:com.marklogic.contentpump.CompressedAggXMLReader.java

protected void initStreamReader(InputSplit inSplit) throws IOException, InterruptedException {
    setFile(((FileSplit) inSplit).getPath());
    FSDataInputStream fileIn = fs.open(file);
    String codecString = conf.get(ConfigConstants.CONF_INPUT_COMPRESSION_CODEC,
            CompressionCodec.ZIP.toString());
    if (codecString.equalsIgnoreCase(CompressionCodec.ZIP.toString())) {
        zipIn = new ZipInputStream(fileIn);
        codec = CompressionCodec.ZIP;//from w  w  w.  ja  v a 2  s  . c  om
        while (true) {
            try {
                currZipEntry = ((ZipInputStream) zipIn).getNextEntry();
                if (currZipEntry == null) {
                    break;
                }
                if (currZipEntry.getSize() != 0) {
                    subId = currZipEntry.getName();
                    break;
                }
            } catch (IllegalArgumentException e) {
                LOG.warn("Skipped a zip entry in : " + file.toUri() + ", reason: " + e.getMessage());
            }
        }
        if (currZipEntry == null) { // no entry in zip
            LOG.warn("No valid entry in zip:" + file.toUri());
            return;
        }
        ByteArrayOutputStream baos;
        long size = currZipEntry.getSize();
        if (size == -1) {
            baos = new ByteArrayOutputStream();
        } else {
            baos = new ByteArrayOutputStream((int) size);
        }
        int nb;
        while ((nb = zipIn.read(buf, 0, buf.length)) != -1) {
            baos.write(buf, 0, nb);
        }
        try {
            start = 0;
            end = baos.size();
            xmlSR = f.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()), encoding);
        } catch (XMLStreamException e) {
            LOG.error(e.getMessage(), e);
        }

    } else if (codecString.equalsIgnoreCase(CompressionCodec.GZIP.toString())) {
        zipIn = new GZIPInputStream(fileIn);
        codec = CompressionCodec.GZIP;
        try {
            start = 0;
            end = inSplit.getLength();
            xmlSR = f.createXMLStreamReader(zipIn, encoding);
        } catch (XMLStreamException e) {
            LOG.error(e.getMessage(), e);
        }
    } else {
        throw new UnsupportedOperationException("Unsupported codec: " + codec.name());
    }
    if (useAutomaticId) {
        idGen = new IdGenerator(file.toUri().getPath() + "-" + ((FileSplit) inSplit).getStart());
    }
}

From source file:org.apache.camel.component.atmos.core.AtmosAPIFacade.java

private void downloadSingleFile(String path, Map<String, ByteArrayOutputStream> resultEntries)
        throws AtmosException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] content = null;
    try {//from   www  .  ja  v  a 2 s .  com
        content = AtmosAPIFacade.client.readObject(new ObjectPath(path), byte[].class);
        baos.write(content);
    } catch (IOException e) {
        throw new AtmosException(path + " can't obtain a stream", e);
    }
    if (content != null) {
        resultEntries.put(path, baos);
        LOG.info("downloaded path:" + path + " - baos size:" + baos.size());
    }

}

From source file:org.apache.fop.pdf.PDFLinearization.java

public void outputPages(OutputStream stream) throws IOException {
    Collections.sort(doc.pageObjs, new Comparator<PDFPage>() {
        public int compare(PDFPage o1, PDFPage o2) {
            return ((Integer) o1.pageIndex).compareTo(o2.pageIndex);
        }//w w w.  j a  v a2  s .  c o  m
    });
    doc.objects.addAll(doc.trailerObjects);
    doc.trailerObjects = null;
    if (doc.getStructureTreeElements() != null) {
        doc.objects.addAll(doc.getStructureTreeElements());
        doc.structureTreeElements = null;
    }
    for (int i = 0; i < doc.objects.size() * 2; i++) {
        doc.indirectObjectOffsets.add(0L);
    }
    Set<PDFObject> page1Children = assignNumbers();
    doc.streamIndirectObject(linearDict, new ByteArrayOutputStream());
    for (PDFObject o : page1Children) {
        doc.objects.remove(o);
    }
    int sizeOfRest = doc.objects.size();

    ByteArrayOutputStream fakeHeaderTrailerStream = new ByteArrayOutputStream();
    long topTrailer = doc.position;
    doc.writeTrailer(fakeHeaderTrailerStream, sizeOfRest, page1Children.size() + 1,
            page1Children.size() + sizeOfRest + 1, Long.MAX_VALUE, 0);
    doc.position += fakeHeaderTrailerStream.size();

    ByteArrayOutputStream pageStream = new ByteArrayOutputStream();
    writeObjects(page1Children, pageStream, sizeOfRest + 1);
    long trailerOffset = doc.position;
    ByteArrayOutputStream footerTrailerStream = new ByteArrayOutputStream();
    doc.writeTrailer(footerTrailerStream, 0, sizeOfRest, sizeOfRest, 0, topTrailer);
    doc.position += footerTrailerStream.size();

    linearDict.put("/L", doc.position);

    PDFDocument.outputIndirectObject(linearDict, stream);
    CountingOutputStream realTrailer = new CountingOutputStream(stream);
    doc.writeTrailer(realTrailer, sizeOfRest, page1Children.size() + 1, page1Children.size() + sizeOfRest + 1,
            trailerOffset, 0);
    writePadding(fakeHeaderTrailerStream.size() - realTrailer.getCount(), stream);
    for (PDFObject o : page1Children) {
        PDFDocument.outputIndirectObject(o, stream);
        if (o instanceof HintTable) {
            break;
        }
    }
    stream.write(pageStream.toByteArray());
    stream.write(footerTrailerStream.toByteArray());
}

From source file:org.jactr.tools.async.message.ast.BaseASTMessage.java

private void writeObject(java.io.ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();/*www  . j a va  2 s.  c  o  m*/
    if (_ast != null) {
        out.writeBoolean(true);
        out.writeBoolean(_compress);

        if (_compress) {
            /*
             * go to a GZIPOutputStream
             */
            ByteArrayOutputStream baos = _localBAOS.get();
            if (baos == null) {
                baos = new ByteArrayOutputStream();
                _localBAOS.set(baos);
            }
            baos.reset();

            DataOutputStream zip = new DataOutputStream(new GZIPOutputStream(baos));
            Serializer.write(_ast, zip);
            zip.flush();
            zip.close();
            // byte[] bytes = baos.toByteArray();

            if (LOGGER.isDebugEnabled())
                LOGGER.debug(String.format("Writing %d compressed bytes", baos.size()));

            out.writeInt(baos.size());
            baos.writeTo(out);

            // if (LOGGER.isDebugEnabled())
            // LOGGER.debug("Compressed AST to "+bytes.length);
            // out.writeInt(bytes.length);
            // out.write(bytes);
        } else
            Serializer.write(_ast, out);
    } else
        out.writeBoolean(false);
}

From source file:net.solarnetwork.node.io.rxtx.SerialPortSupport.java

private boolean handleSerialEventWithoutTimeout(SerialPortEvent event, InputStream in,
        ByteArrayOutputStream sink, byte[] magicBytes, byte[] eofBytes) {
    int sinkSize = sink.size();
    boolean append = sinkSize > 0;
    byte[] buf = new byte[1024];
    if (eventLog.isTraceEnabled()) {
        eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
    }/* w w  w.  ja  v  a2 s  . c o m*/
    try {
        int len = -1;
        final int max = Math.min(in.available(), buf.length);
        eventLog.trace("Attempting to read {} bytes from serial port", max);
        while (max > 0 && (len = in.read(buf, 0, max)) > 0) {
            sink.write(buf, 0, len);
            sinkSize += len;

            if (append) {
                // look for eofBytes, starting where we last appended
                if (findEOFBytes(sink, len, eofBytes)) {
                    if (eventLog.isDebugEnabled()) {
                        eventLog.debug("Found desired EOF bytes: {}", asciiDebugValue(eofBytes));
                    }
                    return true;
                }
                eventLog.debug("Looking for EOF bytes {}", asciiDebugValue(eofBytes));
                return false;
            } else {
                eventLog.trace("Looking for {} magic bytes {} in buffer {}", new Object[] { magicBytes.length,
                        asciiDebugValue(magicBytes), asciiDebugValue(sink.toByteArray()) });
            }

            // look for magic in the buffer
            int magicIdx = 0;
            byte[] sinkBuf = sink.toByteArray();
            boolean found = false;
            for (; magicIdx < (sinkBuf.length - magicBytes.length + 1); magicIdx++) {
                found = true;
                for (int j = 0; j < magicBytes.length; j++) {
                    if (sinkBuf[magicIdx + j] != magicBytes[j]) {
                        found = false;
                        break;
                    }
                }
                if (found) {
                    break;
                }
            }

            if (found) {
                // magic found!
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Found magic bytes " + asciiDebugValue(magicBytes) + " at buffer index "
                            + magicIdx);
                }

                int count = buf.length;
                count = Math.min(buf.length, sinkBuf.length - magicIdx);
                sink.reset();
                sink.write(sinkBuf, magicIdx, count);
                sinkSize = count;
                if (eventLog.isTraceEnabled()) {
                    eventLog.trace("Sink contains {} bytes: {}", sinkSize, asciiDebugValue(sink.toByteArray()));
                }
                if (findEOFBytes(sink, len, eofBytes)) {
                    // we got all the data here... we're done
                    return true;
                }
                append = true;
            } else if (sinkBuf.length > magicBytes.length) {
                // haven't found the magic yet, and the sink is larger than magic size, so 
                // trim sink down to just magic size
                sink.reset();
                sink.write(sinkBuf, sinkBuf.length - magicBytes.length, magicBytes.length);
                sinkSize = magicBytes.length;
            }
        }
    } catch (IOException e) {
        log.error("Error reading from serial port: {}", e.getMessage());
        throw new RuntimeException(e);
    }

    if (eventLog.isTraceEnabled()) {
        eventLog.debug("Looking for bytes {}, buffer: {}",
                (append ? asciiDebugValue(eofBytes) : asciiDebugValue(magicBytes)),
                asciiDebugValue(sink.toByteArray()));
    }
    return false;
}

From source file:com.esri.gpt.agp.multipart2.MPart.java

/**
 * Determine the length of the part in bytes (-1 if unknown).
 * @return the length of the part//from w  ww.  jav a2  s  . c om
 * @throws IOException if an exception occurs
 */
public long partLength() throws IOException {
    if (dataLength() < 0) {
        return -1;
    }
    ByteArrayOutputStream overhead = new ByteArrayOutputStream();
    sendStart(overhead);
    sendDispositionHeader(overhead);
    sendContentTypeHeader(overhead);
    sendTransferEncodingHeader(overhead);
    sendEndOfHeader(overhead);
    sendEnd(overhead);
    //System.err.println(new String(overhead.toByteArray()));
    return overhead.size() + dataLength();
}

From source file:org.exoplatform.forum.service.ForumServiceTestCase.java

public void testExportXML() throws Exception {
    Category cat = createCategory(getId(Utils.CATEGORY));
    forumService_.saveCategory(cat, true);
    cat = forumService_.getCategory(cat.getId());
    Forum forum = createdForum();// ww  w  . j a va2  s  .  c  om
    forumService_.saveForum(cat.getId(), forum, true);
    forum = forumService_.getForum(cat.getId(), forum.getId());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    forumService_.exportXML(cat.getId(), forum.getId(), new ArrayList<String>(), forum.getPath(), bos, false);
    assertEquals("can't export Forum into XML file", bos.size() > 0, true);
}