List of usage examples for java.io ByteArrayOutputStream size
public synchronized int size()
From source file:org.mrgeo.vector.mrsvector.VectorTileCleaner.java
@Override public void printstats() { int totalsize = 0; int size = 0; if (strings != null) { for (final String s : strings) { size += s.length();//from www. jav a 2 s . co m } totalsize += size; System.out.println("strings: " + strings.length + " (" + human(size) + ")"); } { try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(nodes); size = bytes.size(); totalsize += size; System.out.println("nodes: " + nodes.length + " (" + human(size) + ")"); } catch (final IOException e) { e.printStackTrace(); } } try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(ways); size = bytes.size(); totalsize += size; System.out.println("ways: " + ways.length + " (" + human(size) + ")"); } catch (final IOException e) { e.printStackTrace(); } try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(relations); size = bytes.size(); totalsize += size; System.out.println("relations: " + relations.length + " (" + human(size) + ")"); } catch (final IOException e) { e.printStackTrace(); } System.out.println("cleaner: "); { size = 0; for (final ObjectIntCursor<String> c : stringmap) { size += c.key.length() + RasterUtils.INT_BYTES; } totalsize += size; System.out.println(" stringtable: " + stringmap.size() + " (" + human(size) + ")"); } { try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(chunkstringmap); size = bytes.size(); totalsize += size; System.out.println(" stringmap: " + chunkstringmap.length + " (" + human(size) + ")"); } catch (final IOException e) { e.printStackTrace(); } } { size = nodemap.size() * 2 * RasterUtils.LONG_BYTES; totalsize += size; System.out.println(" nodemap: " + nodemap.size() + " (" + human(size) + ")"); } { size = waymap.size() * 2 * RasterUtils.LONG_BYTES; totalsize += size; System.out.println(" waymap: " + waymap.size() + " (" + human(size) + ")"); } { size = relationmap.size() * 2 * RasterUtils.LONG_BYTES; totalsize += size; System.out.println(" relationmap: " + relationmap.size() + " (" + human(size) + ")"); } { try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(orphanWays); size = bytes.size(); totalsize += size; System.out.println(" orphaned ways: " + orphanWays.length + " (" + human(size) + ")"); } catch (final IOException e) { e.printStackTrace(); } } { try { final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); final ObjectOutputStream out = new ObjectOutputStream(bytes); out.writeObject(orphanRelations); size = bytes.size(); totalsize += size; System.out.println(" orphaned relations: " + orphanRelations.length + " (" + human(size) + ")"); } catch (final IOException e) { e.printStackTrace(); } } System.out.println("total size: " + human(totalsize)); }
From source file:com.sim2dial.dialer.ChatFragment.java
private void uploadAndSendImage(final String filePath, final Bitmap image, final ImageSize size) { uploadLayout.setVisibility(View.VISIBLE); textLayout.setVisibility(View.GONE); uploadThread = new Thread(new Runnable() { @Override//w w w.ja v a2 s . co m public void run() { Bitmap bm = null; String url = null; if (!uploadThread.isInterrupted()) { if (filePath != null) { bm = BitmapFactory.decodeFile(filePath); if (bm != null && size != ImageSize.REAL) { int pixelsMax = size == ImageSize.SMALL ? SIZE_SMALL : size == ImageSize.MEDIUM ? SIZE_MEDIUM : SIZE_LARGE; if (bm.getWidth() > bm.getHeight() && bm.getWidth() > pixelsMax) { bm = Bitmap.createScaledBitmap(bm, pixelsMax, (pixelsMax * bm.getHeight()) / bm.getWidth(), false); } else if (bm.getHeight() > bm.getWidth() && bm.getHeight() > pixelsMax) { bm = Bitmap.createScaledBitmap(bm, (pixelsMax * bm.getWidth()) / bm.getHeight(), pixelsMax, false); } } } else if (image != null) { bm = image; } } // Rotate the bitmap if possible/needed, using EXIF data try { if (filePath != null) { ExifInterface exif = new ExifInterface(filePath); int pictureOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0); Matrix matrix = new Matrix(); if (pictureOrientation == 6) { matrix.postRotate(90); } else if (pictureOrientation == 3) { matrix.postRotate(180); } else if (pictureOrientation == 8) { matrix.postRotate(270); } bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true); } } catch (Exception e) { e.printStackTrace(); } ByteArrayOutputStream outStream = new ByteArrayOutputStream(); if (bm != null) { bm.compress(CompressFormat.JPEG, COMPRESSOR_QUALITY, outStream); } if (!uploadThread.isInterrupted() && bm != null) { url = uploadImage(filePath, bm, COMPRESSOR_QUALITY, outStream.size()); File file = new File(Environment.getExternalStorageDirectory(), getString(R.string.temp_photo_name)); file.delete(); } if (!uploadThread.isInterrupted()) { final Bitmap fbm = bm; final String furl = url; mHandler.post(new Runnable() { @Override public void run() { uploadLayout.setVisibility(View.GONE); textLayout.setVisibility(View.VISIBLE); progressBar.setProgress(0); if (furl != null) { sendImageMessage(furl, fbm); } else { Toast.makeText(getActivity(), getString(R.string.error), Toast.LENGTH_LONG).show(); } } }); } } }); uploadThread.start(); }
From source file:org.egov.api.controller.ComplaintController.java
/** * This will download the support document of the complaint. * * @param complaintNo//from w w w. ja v a2s . com * @param fileNo * @param isThumbnail * @return file */ @RequestMapping(value = ApiUrl.COMPLAINT_DOWNLOAD_SUPPORT_DOCUMENT, method = GET) public void getComplaintDoc(@PathVariable final String complaintNo, @RequestParam(value = "fileNo", required = false) Integer fileNo, @RequestParam(value = "isThumbnail", required = false, defaultValue = "false") final boolean isThumbnail, final HttpServletResponse response) throws IOException { try { final Complaint complaint = complaintService.getComplaintByCRN(complaintNo); final Set<FileStoreMapper> files = complaint.getSupportDocs(); int i = 1; final Iterator<FileStoreMapper> it = files.iterator(); Integer noOfFiles = fileNo; if (noOfFiles == null) noOfFiles = files.size(); File downloadFile; while (it.hasNext()) { final FileStoreMapper fm = it.next(); if (i == noOfFiles) { downloadFile = fileStoreService.fetch(fm.getFileStoreId(), PGRConstants.MODULE_NAME); final ByteArrayOutputStream thumbImg = new ByteArrayOutputStream(); long contentLength = downloadFile.length(); if (isThumbnail) { final BufferedImage img = Thumbnails.of(downloadFile).size(200, 200).asBufferedImage(); ImageIO.write(img, "jpg", thumbImg); thumbImg.close(); contentLength = thumbImg.size(); } response.setHeader("Content-Length", String.valueOf(contentLength)); response.setHeader("Content-Disposition", "attachment;filename=" + fm.getFileName()); response.setContentType(Files.probeContentType(downloadFile.toPath())); final OutputStream out = response.getOutputStream(); IOUtils.write( isThumbnail ? thumbImg.toByteArray() : FileUtils.readFileToByteArray(downloadFile), out); break; } i++; } } catch (final Exception e) { LOGGER.error(EGOV_API_ERROR, e); throw new IOException(); } }
From source file:org.commoncrawl.util.CompressedURLFPListV2.java
public static void validateURLFPFlagSerializationRootDomain() { TreeMultimap<Long, URLFPV2> sourceMap = TreeMultimap.create(); TreeMultimap<Long, URLFPV2> destMap = TreeMultimap.create(); ;// w w w. j ava 2s .c om ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); Builder firstBuilder = new Builder(FLAG_ARCHIVE_SEGMENT_ID | FLAG_SERIALIZE_URLFP_FLAGS); for (int i = 0; i < 12; ++i) { insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "0_" + i, 1, (255 | (65535 << 16))); insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "1_" + i, 2, (255 | (65535 << 16))); insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "2_" + i, 3, (255 | (65535 << 16))); insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "3_" + i, 4, 0); insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "4_" + i, 5, 0); insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "5_" + i, 6, 0); insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "6_" + i, 7, (255 | (65535 << 16))); insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "7_" + i, 8, 255); } insertURLFPItem(sourceMap, DOMAIN_2_SUBDOMAIN_1_URL_1 + "8", 8, 255); addMapToBuilder(firstBuilder, sourceMap); try { // flush to byte stream ... firstBuilder.flush(byteStream); // now set up to read the stream ByteArrayInputStream inputStream = new ByteArrayInputStream(byteStream.toByteArray(), 0, byteStream.size()); Reader reader = new Reader(inputStream); while (reader.hasNext()) { URLFPV2 fp = reader.next(); destMap.put(fp.getRootDomainHash(), fp); } reader.close(); Assert.assertTrue(sourceMap.equals(destMap)); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.gmail.nagamatu.radiko.installer.RadikoInstallerActivity.java
private byte[] createRequest() { try {//from w w w. jav a2s .c o m String packageName = PACKAGE_NAME; int baseLen; ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write(10); writeString(os, mLoginInfo.get("Auth")); os.write(16); os.write(1); os.write(24); writeInt32(os, 2009011); os.write(34); writeString(os, mDeviceId); os.write(42); writeString(os, "passion:9"); os.write(50); writeString(os, "en"); os.write(58); writeString(os, "us"); os.write(66); writeString(os, "DoCoMo"); os.write(74); writeString(os, "DoCoMo"); os.write(82); writeString(os, "44010"); os.write(90); writeString(os, "44010"); baseLen = os.size() + 1 - 3; // reduce three bytes - one marker (10) plus 2 bytes for baseLen os.write(19); os.write(82); writeInt32(os, packageName.length() + 2); os.write(10); writeString(os, packageName); os.write(20); os.flush(); os.close(); ByteArrayOutputStream request = new ByteArrayOutputStream(); request.write(10); writeInt32(request, baseLen + 2); request.write(os.toByteArray(), 0, os.size()); return request.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.commoncrawl.util.CompressedURLFPList.java
public static void validateURLFPFlagSerializationMultipleSubDomains() { TreeMultimap<Integer, URLFP> sourceMap = TreeMultimap.create(); TreeMultimap<Integer, URLFP> destMap = TreeMultimap.create(); ;// ww w. jav a 2 s .c o m ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); Builder firstBuilder = new Builder(FLAG_ARCHIVE_SEGMENT_ID | FLAG_SERIALIZE_URLFP_FLAGS); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "0", 1, 255); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "1", 2, 255); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "2", 3, 255); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "3", 4, 0); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "4", 1, 255); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "5", 2, 255); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "6", 3, 255); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "7", 4, 0); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "8", 1, 255); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "9", 2, 255); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_1_URL_1 + "10", 3, 255); insertURLFPItem(sourceMap, DOMAIN_3_SUBDOMAIN_2_URL_1 + "11", 4, 0); addMapToBuilder(firstBuilder, sourceMap); try { // flush to byte stream ... firstBuilder.flush(byteStream); // now set up to read the stream ByteArrayInputStream inputStream = new ByteArrayInputStream(byteStream.toByteArray(), 0, byteStream.size()); Reader reader = new Reader(inputStream); while (reader.hasNext()) { URLFP fp = reader.next(); destMap.put(fp.getRootDomainHash(), fp); } reader.close(); Assert.assertTrue(sourceMap.equals(destMap)); } catch (IOException e) { e.printStackTrace(); } }
From source file:gate.crowdsource.rest.CrowdFlowerClient.java
protected JsonElement request(String method, String uri, String... formData) throws IOException { if (log.isDebugEnabled()) { log.debug("URI: " + uri + ", formData: " + Arrays.toString(formData)); }/*from ww w . j ava 2 s. com*/ URL cfUrl = new URL(CF_ENDPOINT + uri + "?key=" + apiKey); HttpURLConnection connection = (HttpURLConnection) cfUrl.openConnection(); connection.setRequestMethod(method); connection.setRequestProperty("Accept", "application/json"); if (formData != null && formData.length > 0) { // send the form data, URL encoded connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // annoyingly CrowdFlower doesn't support chunked streaming of // POSTs so we have to accumulate the content in a buffer, work // out its size and then POST with a Content-Length header ByteArrayOutputStream buffer = new ByteArrayOutputStream(4096); PrintWriter writer = new PrintWriter(new OutputStreamWriter(buffer, "UTF-8")); try { for (int i = 0; i < formData.length; i++) { String fieldName = formData[i]; String fieldValue = formData[++i]; if (i > 0) { writer.write("&"); } writer.write(URLEncoder.encode(fieldName, "UTF-8")); writer.write("="); writer.write(URLEncoder.encode(fieldValue, "UTF-8")); } } finally { writer.close(); } connection.setFixedLengthStreamingMode(buffer.size()); OutputStream connectionStream = connection.getOutputStream(); buffer.writeTo(connectionStream); connectionStream.close(); } // parse the response as JSON JsonParser parser = new JsonParser(); Reader responseReader = new InputStreamReader(connection.getInputStream(), "UTF-8"); try { return parser.parse(responseReader); } finally { responseReader.close(); } }
From source file:org.nuxeo.ecm.platform.xmlrpc.connector.NuxeoXmlRpcServletServer.java
@Override public void execute(XmlRpcStreamRequestConfig pConfig, ServerStreamConnection pConnection) throws XmlRpcException { ServletStreamConnection ssc = (ServletStreamConnection) pConnection; String uri = ssc.getRequest().getRequestURI(); String handlerPrefix = ""; if (!uri.endsWith("/rpc") && !uri.endsWith("/rpc/")) { String[] urlParts = uri.split("/"); handlerPrefix = urlParts[urlParts.length - 1]; }/*from w w w . j av a2s .c o m*/ log.debug("execute: ->"); try { Object result; Throwable error; InputStream istream = null; try { istream = getInputStream(pConfig, pConnection); XmlRpcRequest request = getRequest(pConfig, istream, handlerPrefix); result = execute(request); istream.close(); istream = null; error = null; log.debug("execute: Request performed successfully"); } catch (Throwable t) { log.error("execute: Error while performing request", t); result = null; error = t; } finally { if (istream != null) { try { istream.close(); } catch (Throwable ignore) { } } } boolean contentLengthRequired = isContentLengthRequired(pConfig); ByteArrayOutputStream baos; OutputStream ostream; if (contentLengthRequired) { baos = new ByteArrayOutputStream(); ostream = baos; } else { baos = null; ostream = pConnection.newOutputStream(); } ostream = getOutputStream(pConnection, pConfig, ostream); try { if (error == null) { writeResponse(pConfig, ostream, result); } else { writeError(pConfig, ostream, error); } ostream.close(); ostream = null; } finally { if (ostream != null) { try { ostream.close(); } catch (Throwable ignore) { } } } if (baos != null) { OutputStream dest = getOutputStream(pConfig, pConnection, baos.size()); try { baos.writeTo(dest); dest.close(); dest = null; } finally { if (dest != null) { try { dest.close(); } catch (Throwable ignore) { } } } } pConnection.close(); pConnection = null; } catch (IOException e) { throw new XmlRpcException("I/O error while processing request: " + e.getMessage(), e); } finally { if (pConnection != null) { try { pConnection.close(); } catch (Throwable ignore) { } } } log.debug("execute: <-"); }
From source file:org.apache.pdfbox.examples.util.PDFMergerExample.java
/** * Creates a compound PDF document from a list of input documents. * <p>//from w w w . j a v a2s .co m * The merged document is PDF/A-1b compliant, provided the source documents are as well. It * contains document properties title, creator and subject, currently hard-coded. * * @param sources list of source PDF document streams. * @return compound PDF document as a readable input stream. * @throws IOException if anything goes wrong during PDF merge. */ public InputStream merge(final List<InputStream> sources) throws IOException { String title = "My title"; String creator = "Alexander Kriegisch"; String subject = "Subject with umlauts "; ByteArrayOutputStream mergedPDFOutputStream = null; COSStream cosStream = null; try { // If you're merging in a servlet, you can modify this example to use the outputStream only // as the response as shown here: http://stackoverflow.com/a/36894346/535646 mergedPDFOutputStream = new ByteArrayOutputStream(); cosStream = new COSStream(); PDFMergerUtility pdfMerger = createPDFMergerUtility(sources, mergedPDFOutputStream); // PDF and XMP properties must be identical, otherwise document is not PDF/A compliant PDDocumentInformation pdfDocumentInfo = createPDFDocumentInfo(title, creator, subject); PDMetadata xmpMetadata = createXMPMetadata(cosStream, title, creator, subject); pdfMerger.setDestinationDocumentInformation(pdfDocumentInfo); pdfMerger.setDestinationMetadata(xmpMetadata); LOG.info("Merging " + sources.size() + " source documents into one PDF"); pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly()); LOG.info("PDF merge successful, size = {" + mergedPDFOutputStream.size() + "} bytes"); return new ByteArrayInputStream(mergedPDFOutputStream.toByteArray()); } catch (BadFieldValueException e) { throw new IOException("PDF merge problem", e); } catch (TransformerException e) { throw new IOException("PDF merge problem", e); } finally { for (InputStream source : sources) { IOUtils.closeQuietly(source); } IOUtils.closeQuietly(cosStream); IOUtils.closeQuietly(mergedPDFOutputStream); } }
From source file:com.marklogic.contentpump.CompressedAggXMLReader.java
@Override public boolean nextKeyValue() throws IOException, InterruptedException { if (zipIn == null || xmlSR == null) { hasNext = false;//from www. j av a 2s. c o m return false; } try { if (codec.equals(CompressionCodec.ZIP)) { ZipInputStream zis = (ZipInputStream) zipIn; if (xmlSR.hasNext()) { hasNext = nextRecordInAggregate(); if (hasNext) { return true; } } // xmlSR does not hasNext, // if there is next zipEntry, close xmlSR then create a new one ByteArrayOutputStream baos; while (true) { try { currZipEntry = ((ZipInputStream) zipIn).getNextEntry(); if (currZipEntry == null) { break; } if (currZipEntry.getSize() == 0) { continue; } subId = currZipEntry.getName(); long size = currZipEntry.getSize(); if (size == -1) { baos = new ByteArrayOutputStream(); } else { baos = new ByteArrayOutputStream((int) size); } int nb; while ((nb = zis.read(buf, 0, buf.length)) != -1) { baos.write(buf, 0, nb); } xmlSR.close(); start = 0; end = baos.size(); xmlSR = f.createXMLStreamReader(new ByteArrayInputStream(baos.toByteArray()), encoding); nameSpaces.clear(); baos.close(); return nextRecordInAggregate(); } catch (IllegalArgumentException e) { LOG.warn("Skipped a zip entry in : " + file.toUri() + ", reason: " + e.getMessage()); } } // end of zip if (iterator != null && iterator.hasNext()) { //close previous zip and streams close(); initStreamReader(iterator.next()); return nextRecordInAggregate(); } //current split doesn't have more zip return false; } else if (codec.equals(CompressionCodec.GZIP)) { if (nextRecordInAggregate()) { return true; } // move to next gzip file in this split if (iterator != null && iterator.hasNext()) { // close previous zip and streams close(); initStreamReader(iterator.next()); return nextRecordInAggregate(); } return false; } } catch (XMLStreamException e) { LOG.error(e.getMessage(), e); } return true; }