List of usage examples for java.io ByteArrayOutputStream size
public synchronized int size()
From source file:org.dataconservancy.packaging.tool.impl.AnnotationDrivenPackageStateSerializerTest.java
@Test public void testArchiveZipLive() throws Exception { underTest.setArchive(true);/*from ww w . j a va 2s . c o m*/ underTest.setArxStreamFactory(new ZipArchiveStreamFactory()); ByteArrayOutputStream result = new ByteArrayOutputStream(); underTest.serialize(state, StreamId.APPLICATION_VERSION, result); assertTrue(result.size() > 1); }
From source file:gov.nih.nci.caarray.domain.MultiPartBlob.java
/** * Method that takes an input stream and breaks it up in to multiple blobs. Note that this method loads each chunk * in to a byte[], while this is not ideal, this will be done by the mysql driver anyway, so we are not adding a new * inefficiency./*from w ww.jav a 2 s .c om*/ * * @param data the input stream to store. * @param compress true to compress the data, false to leave it uncompressed * @param blobPartSize the maximum size of a single blob * @throws IOException on error reading from the stream. */ public void writeData(InputStream data, boolean compress, int blobPartSize) throws IOException { final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); OutputStream writeStream; if (compress) { writeStream = new GZIPOutputStream(byteStream); } else { writeStream = byteStream; } byte[] unwritten = new byte[0]; final byte[] uncompressed = new byte[blobPartSize]; int len = 0; while ((len = data.read(uncompressed)) > 0) { uncompressedSize += len; writeStream.write(uncompressed, 0, len); if (byteStream.size() + unwritten.length >= blobPartSize) { compressedSize += byteStream.size(); unwritten = writeData(ArrayUtils.addAll(unwritten, byteStream.toByteArray()), blobPartSize, false); byteStream.reset(); } } IOUtils.closeQuietly(writeStream); compressedSize += byteStream.size(); writeData(ArrayUtils.addAll(unwritten, byteStream.toByteArray()), blobPartSize, true); }
From source file:com.centurylink.mdw.util.HttpHelper.java
public String mkcol() throws IOException { if (connection == null) { if (proxy == null) connection = (HttpURLConnection) url.openConnection(); else/*from w w w .ja va 2 s.com*/ connection = (HttpURLConnection) url.openConnection(proxy); } prepareConnection(connection); connection.setDoOutput(false); connection.setRequestMethod("MKCOL"); HttpURLConnection.setFollowRedirects(true); InputStream is = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { is = connection.getInputStream(); byte[] buffer = new byte[2048]; while (maxBytes == -1 || baos.size() < maxBytes) { int bytesRead = is.read(buffer); if (bytesRead == -1) break; baos.write(buffer, 0, bytesRead); } } finally { if (is != null) is.close(); connection.disconnect(); responseCode = connection.getResponseCode(); responseMessage = connection.getResponseMessage(); headers = new HashMap<String, String>(); for (String headerKey : connection.getHeaderFields().keySet()) { headers.put(headerKey, connection.getHeaderField(headerKey)); } } return baos.toString(); }
From source file:org.mockftpserver.stub.StubFtpServerIntegrationTest.java
/** * Test GET and PUT of binary files//from www . java 2 s. c om */ public void testTransferBinaryFiles() throws Exception { retrCommandHandler.setFileContents(BINARY_CONTENTS); ftpClientConnect(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // Get File LOG.info("Get File for remotePath [" + FILENAME + "]"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); assertTrue("GET", ftpClient.retrieveFile(FILENAME, outputStream)); LOG.info("GET File length=" + outputStream.size()); assertEquals("File contents", BINARY_CONTENTS, outputStream.toByteArray()); // Put File LOG.info("Put File for local path [" + FILENAME + "]"); ByteArrayInputStream inputStream = new ByteArrayInputStream(BINARY_CONTENTS); assertTrue("PUT", ftpClient.storeFile(FILENAME, inputStream)); InvocationRecord invocationRecord = storCommandHandler.getInvocation(0); byte[] contents = (byte[]) invocationRecord.getObject(StorCommandHandler.FILE_CONTENTS_KEY); LOG.info("PUT File length=" + contents.length); assertEquals("File contents", BINARY_CONTENTS, contents); }
From source file:org.apache.camel.component.exec.impl.DefaultExecCommandExecutor.java
public ExecResult execute(ExecCommand command) { notNull(command, "command"); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); DefaultExecutor executor = prepareDefaultExecutor(command); // handle error and output of the process and write them to the given // out stream PumpStreamHandler handler = new PumpStreamHandler(out, err, command.getInput()); executor.setStreamHandler(handler);//from w ww.ja v a2 s . com CommandLine cl = toCommandLine(command); try { int exitValue = executor.execute(cl); // if the size is zero, we have no output, so construct the result // with null (required by ExecResult) InputStream stdout = out.size() == 0 ? null : new ByteArrayInputStream(out.toByteArray()); InputStream stderr = err.size() == 0 ? null : new ByteArrayInputStream(err.toByteArray()); ExecResult result = new ExecResult(command, stdout, stderr, exitValue); return result; } catch (ExecuteException ee) { LOG.error("ExecException while executing command: " + command.toString() + " - " + ee.getMessage()); throw new ExecException("Failed to execute command " + command, ee); } catch (IOException ioe) { // invalid working dir LOG.error("IOException while executing command: " + command.toString() + " - " + ioe.getMessage()); throw new ExecException("Unable to execute command " + command, ioe); } finally { // the inputStream must be closed after the execution IOUtils.closeQuietly(command.getInput()); } }
From source file:org.chiba.xml.xforms.connector.serializer.FormDataSerializer.java
/** * Serialize instance into multipart/form-data stream as defined in * http://www.w3.org/TR/xforms/slice11.html#serialize-form-data * * @param submission/*from ww w.ja va 2 s .c om*/ * @param instance * @param stream * @param defaultEncoding * @throws Exception on error */ public void serialize(Submission submission, Node instance, OutputStream stream, String defaultEncoding) throws Exception { // sanity checks if (instance == null) return; switch (instance.getNodeType()) { case Node.ELEMENT_NODE: break; case Node.DOCUMENT_NODE: instance = ((Document) instance).getDocumentElement(); break; default: return; } String encoding = defaultEncoding; if (submission.getEncoding() != null) { encoding = submission.getEncoding(); } // generate boundary Random rnd = new Random(System.currentTimeMillis()); String boundary = DigestUtils.md5Hex(getClass().getName() + rnd.nextLong()); // serialize the instance ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(bos, encoding))); serializeElement(writer, (Element) instance, boundary, encoding); writer.print("\r\n--" + boundary + "--"); writer.flush(); // write to the stream String header = "Content-Type: multipart/form-data;\r\n" + "\tcharset=\"" + encoding + "\";\r\n" + "\tboundary=\"" + boundary + "\";\r\n" + "Content-Length: " + bos.size() + "\r\n\r\n"; stream.write(header.getBytes(encoding)); bos.writeTo(stream); }
From source file:net.sf.ehcache.Element.java
/** * The size of this object in serialized form. This is not the same * thing as the memory size, which is JVM dependent. Relative values should be meaningful, * however./*w ww . j a va2 s.c o m*/ * <p/> * Warning: This method can be <b>very slow</b> for values which contain large object graphs. * <p/> * If the key or value of the Element is not Serializable, an error will be logged and 0 will be returned. * @return The serialized size in bytes */ public final long getSerializedSize() { if (!isSerializable()) { return 0; } long size = 0; ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(bout); oos.writeObject(this); size = bout.size(); return size; } catch (IOException e) { LOG.debug( "Error measuring element size for element with key " + key + ". Cause was: " + e.getMessage()); } finally { try { if (oos != null) { oos.close(); } } catch (Exception e) { LOG.error("Error closing ObjectOutputStream"); } } return size; }
From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java
public final void testPurchaseOrderRetransmit() throws Exception { // Create and save a minimally-populated basic PO document for each test. PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS .createPurchaseOrderDocument(); po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN); po.refreshNonUpdateableReferences(); po.prepareForSave();/*w ww .j av a 2s . c om*/ AccountingDocumentTestUtils.saveDocument(po, docService); PurchaseOrderDocument poRetrans = null; try { poRetrans = poService.createAndSavePotentialChangeDocument(po.getDocumentNumber(), PurchaseOrderDocTypes.PURCHASE_ORDER_RETRANSMIT_DOCUMENT, PurchaseOrderStatuses.APPDOC_PENDING_RETRANSMIT); po = poService.getPurchaseOrderByDocumentNumber(po.getDocumentNumber()); } catch (ValidationException ve) { fail("Validation errors creating PO retransmit document: " + dumpMessageMapErrors()); } assertMatchRetransmit(po, poRetrans); ((PurchaseOrderItem) poRetrans.getItem(0)).setItemSelectedForRetransmitIndicator(true); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { poService.retransmitPurchaseOrderPDF(poRetrans, baosPDF); assertTrue(baosPDF.size() > 0); } catch (ValidationException e) { fail("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber() + "\n" + dumpMessageMapErrors()); } finally { if (baosPDF != null) { baosPDF.reset(); } } }
From source file:org.kuali.kfs.module.purap.document.service.PurchaseOrderServiceTest.java
/** * Tests that the PurchaseOrderService would print purchase order quote pdf. * * @throws Exception/*from w w w.j a v a2 s. c om*/ */ public void testPrintPurchaseOrderQuotePDF() throws Exception { PurchaseOrderDocument po = PurchaseOrderDocumentFixture.PO_ONLY_REQUIRED_FIELDS_MULTI_ITEMS .createPurchaseOrderDocument(); po.setApplicationDocumentStatus(PurchaseOrderStatuses.APPDOC_OPEN); po.refreshNonUpdateableReferences(); po.prepareForSave(); AccountingDocumentTestUtils.saveDocument(po, docService); PurchaseOrderVendorQuote vendorQuote = PurchaseOrderVendorQuoteFixture.BASIC_VENDOR_QUOTE_1 .createPurchaseOrderVendorQuote(); vendorQuote.setDocumentNumber(po.getDocumentNumber()); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); try { poService.printPurchaseOrderQuotePDF(po, vendorQuote, baosPDF); assertTrue(baosPDF.size() > 0); LOG.error("Attn From testPrintPurchaseOrderQuotePDF"); LOG.error("baosPDF.size is : " + baosPDF.size()); LOG.error("----------------------------------------"); } catch (Exception e) { LOG.warn("Caught ValidationException while trying to print PO quote pdf with doc id " + po.getDocumentNumber()); } finally { if (baosPDF != null) { baosPDF.reset(); } } }
From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java
/** * Fetches a file from a given URL// w w w .j a va2 s . c o m */ private InputStream fetchFile() throws Exception { InputStream input = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); if (!this.ftpOpen) { try { this.openFtpServer(); } catch (Exception e) { this.logger.error("Could not open ftp server " + e.getCause()); throw new Exception(); } } if (this.f.retrieveFile(this.getCurrentFile(), out)) { input = new ByteArrayInputStream(out.toByteArray()); this.fileSize = out.size(); } return input; }