List of usage examples for java.io ByteArrayOutputStream size
public synchronized int size()
From source file:OutSimplePdf.java
public void makePdf(HttpServletRequest request, HttpServletResponse response, String methodGetPost) { try {// www. j ava 2 s .c o m Document document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfWriter.getInstance(document, baos); document.open(); document.add(new Paragraph("some text")); document.close(); response.setHeader("Expires", "0"); response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0"); response.setHeader("Pragma", "public"); response.setContentType("application/pdf"); response.setContentLength(baos.size()); ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush(); } catch (Exception e2) { System.out.println("Error in " + getClass().getName() + "\n" + e2); } }
From source file:org.lnicholls.galleon.util.Tools.java
public static void cacheImage(Image image, int width, int height, String key) { if (image != null) { try {/*from w w w . ja v a 2s. com*/ // TODO What if not bufferedimage?? if (image instanceof BufferedImage) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(byteArrayOutputStream); encoder.encode((BufferedImage) image); byteArrayOutputStream.close(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( byteArrayOutputStream.toByteArray()); if (byteArrayOutputStream.size() < 102400) { BlobImpl blob = new BlobImpl(byteArrayInputStream, byteArrayOutputStream.size()); Thumbnail thumbnail = null; try { List list = ThumbnailManager.findByKey(key); if (list != null && list.size() > 0) thumbnail = (Thumbnail) list.get(0); } catch (HibernateException ex) { log.error("Thumbnail create failed", ex); } try { if (thumbnail == null) { thumbnail = new Thumbnail("Cached", "jpg", key); thumbnail.setImage(blob); thumbnail.setDateModified(new Date()); ThumbnailManager.createThumbnail(thumbnail); } else { thumbnail.setImage(blob); thumbnail.setDateModified(new Date()); ThumbnailManager.updateThumbnail(thumbnail); } } catch (HibernateException ex) { log.error("Thumbnail create failed", ex); } } } image.flush(); image = null; } catch (Exception ex) { Tools.logException(Tools.class, ex, key); } } }
From source file:org.guvnor.m2repo.backend.server.FileServlet.java
protected void processAttachmentDownload(String path, HttpServletResponse response) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(m2RepoService.loadJar(path), output); String fileName = m2RepoService.getJarName(path); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.setContentLength(output.size()); response.getOutputStream().write(output.toByteArray()); response.getOutputStream().flush();/*from w w w .j a v a 2s.c om*/ }
From source file:org.rro.inventory.rest.InventoryResourceRESTService.java
@POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) // public Response uploadFile(MultipartFormDataInput input) { // @Consumes(MediaType.APPLICATION_OCTET_STREAM) // public Response insertInventoryItem(InputStream is) { public Response put(Map<String, InputStream> data) { String fileName = ""; log.info("output = eccomi"); for (String key : data.keySet()) { fileName += "," + key; log.info(key + " = " + data.get(key)); InputStream is = data.get(key); ByteArrayOutputStream baos = null; try {// w w w. j a va2s . c o m baos = new ByteArrayOutputStream(); Utilities.rushStreams(is, baos); log.info("output = " + baos.size()); services.addPicture(key, baos.toByteArray()); } catch (IOException e) { e.printStackTrace(); return Response.status(HttpStatus.SC_METHOD_FAILURE).entity(e.getMessage() + " " + fileName) .build(); } catch (UserException e) { e.printStackTrace(); return Response.status(HttpStatus.SC_METHOD_FAILURE).entity(e.getMessage() + " " + fileName) .build(); } finally { if (baos != null) { try { baos.close(); } catch (IOException eIgnored) { } } } } return Response.status(HttpStatus.SC_OK).entity("uploadFile is called, Uploaded file name : " + fileName) .build(); // ByteArrayOutputStream baos = null; // try { // baos = new ByteArrayOutputStream(); // Utilities.rushStreams(is, baos); // String xml = new String(baos.toByteArray()); // log.info("output = " + xml.length()); // } catch (IOException e) { // e.printStackTrace(); // } finally { // if (baos != null) { // try { // baos.close(); // } catch (IOException eIgnored) { // } // } // } // // Map<String, List<InputPart>> uploadForm = input.getFormDataMap(); // // if (uploadForm != null) { // for (String partName : uploadForm.keySet()) { // log.info("Upload........................ part id="+partName); // } // } // List<InputPart> inputParts = uploadForm.get("uploadedFile"); // // for (InputPart inputPart : inputParts) { // // try { // // MultivaluedMap<String, String> header = inputPart.getHeaders(); // fileName = getFileName(header); // // //convert the uploaded file to inputstream // InputStream inputStream = inputPart.getBody(InputStream.class,null); // // byte [] bytes = IOUtils.toByteArray(inputStream); // // //constructs upload file path // fileName = UPLOADED_FILE_PATH + fileName; // // writeFile(bytes,fileName); // // System.out.println("Done"); // // } catch (IOException e) { // e.printStackTrace(); // } // // } // return Response.status(200) // .entity("uploadFile is called, Uploaded file name : " + fileName).build(); }
From source file:org.fusesource.hawtjni.generator.HawtJNI.java
private void generate(JNIGenerator gen, ArrayList<JNIClass> classes, File target) throws IOException { gen.setOutputName(name);//from ww w .j a v a2 s . c om gen.setClasses(classes); gen.setCopyright(getCopyright()); gen.setProgressMonitor(progress); ByteArrayOutputStream out = new ByteArrayOutputStream(); gen.setOutput(new PrintStream(out)); gen.generate(); if (out.size() > 0) { if (target.getName().endsWith(".c") && gen.isCPP) { target = new File(target.getParentFile(), target.getName() + "pp"); } if (FileSupport.write(out.toByteArray(), target)) { progress("Wrote: " + target); } } }
From source file:com.linkedin.pinot.query.aggregation.DistinctCountHLLTest.java
private int getSerializedSize(Serializable ser) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = null; try {// w ww .j a v a 2 s . c o m oos = new ObjectOutputStream(baos); oos.writeObject(ser); oos.close(); return baos.size(); } catch (IOException e) { e.printStackTrace(); } return -1; }
From source file:gov.utah.dts.det.ccl.actions.reports.ReportsPrintAction.java
@Action(value = "print-expired-licenses") public void doPrintExpiredLicenses() { Person person = null;/*w w w . j a va 2 s.c om*/ if (specialistId != null) { person = personService.getPerson(specialistId); } if (person == null || person.getId() == null) { return; } try { List<FacilityLicenseView> licenses = facilityService.getExpiringLicensesBySpecialist(new Date(), specialistId); ByteArrayOutputStream ba = ExpiredLicensesReport.generate(person, licenses); if (ba != null && ba.size() > 0) { // This is where the response is set String filename = ""; if (person != null) { if (StringUtils.isNotBlank(person.getFirstName())) { filename += person.getFirstName(); } if (StringUtils.isNotBlank(person.getLastName())) { if (filename.length() > 0) { filename += "_"; } filename += person.getLastName(); } } if (filename.length() > 0) { filename += "_"; } filename += "expired_licenses.pdf"; sendToResponse(ba, filename); } } catch (Exception ex) { generateErrorPdf(); } }
From source file:gov.utah.dts.det.ccl.actions.reports.ReportsPrintAction.java
@Action(value = "print-open-applications") public void doPrintOpenApplications() { Person person = null;//from w w w. ja v a2s.c o m if (specialistId != null) { person = personService.getPerson(specialistId); } if (person == null || person.getId() == null) { return; } try { List<SortableFacilityView> facilities = facilityService.getOpenApplicationsBySpecialist(specialistId); ByteArrayOutputStream ba = OpenApplicationsReport.generate(person, facilities); if (ba != null && ba.size() > 0) { // This is where the response is set String filename = ""; if (person != null) { if (StringUtils.isNotBlank(person.getFirstName())) { filename += person.getFirstName(); } if (StringUtils.isNotBlank(person.getLastName())) { if (filename.length() > 0) { filename += "_"; } filename += person.getLastName(); } } if (filename.length() > 0) { filename += "_"; } filename += "open_applications.pdf"; sendToResponse(ba, filename); } } catch (Exception ex) { generateErrorPdf(); } }
From source file:com.wifi.brainbreaker.mydemo.http.ModAssetServer.java
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { AbstractHttpEntity body = null;//from w w w . j a v a 2s . co m final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } final String url = URLDecoder.decode(request.getRequestLine().getUri()); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length); } final String location = "www" + (url.equals("/") ? "/index.htm" : url); response.setStatusCode(HttpStatus.SC_OK); try { Log.i(TAG, "Requested: \"" + url + "\""); // Compares the Last-Modified date header (if present) with the If-Modified-Since date if (request.containsHeader("If-Modified-Since")) { try { Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue()); if (date.compareTo(mServer.mLastModified) <= 0) { // The file has not been modified response.setStatusCode(HttpStatus.SC_NOT_MODIFIED); return; } } catch (DateParseException e) { e.printStackTrace(); } } // We determine if the asset is compressed try { AssetFileDescriptor afd = mAssetManager.openFd(location); // The asset is not compressed FileInputStream fis = new FileInputStream(afd.getFileDescriptor()); fis.skip(afd.getStartOffset()); body = new InputStreamEntity(fis, afd.getDeclaredLength()); Log.d(TAG, "Serving uncompressed file " + "www" + url); } catch (FileNotFoundException e) { // The asset may be compressed // AAPT compresses assets so first we need to uncompress them to determine their length InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING); ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000); byte[] tmp = new byte[4096]; int length = 0; while ((length = stream.read(tmp)) != -1) buffer.write(tmp, 0, length); body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size()); stream.close(); Log.d(TAG, "Serving compressed file " + "www" + url); } body.setContentType(getMimeMediaType(url) + "; charset=UTF-8"); response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified)); } catch (IOException e) { // File does not exist response.setStatusCode(HttpStatus.SC_NOT_FOUND); body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("File "); writer.write("www" + url); writer.write(" not found"); writer.write("</h1></body></html>"); writer.flush(); } }); Log.d(TAG, "File " + "www" + url + " not found"); body.setContentType("text/html; charset=UTF-8"); } response.setEntity(body); }
From source file:caarray.client.test.java.JavaApiFacade.java
public Integer copyFileContentsZipUtils(String api, List<CaArrayEntityReference> fileReferences, boolean compressed) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); dataApiUtils.copyFileContentsZipToOutputStream(fileReferences, out); return out.size(); }