List of usage examples for java.io ByteArrayOutputStream flush
public void flush() throws IOException
From source file:microsoft.exchange.webservices.data.core.EwsUtilities.java
/** * ./*from w ww. ja v a2 s .c o m*/ * * @param entryKind the entry kind * @param logEntry the log entry * @return the string * @throws XMLStreamException the XML stream exception * @throws IOException signals that an I/O exception has occurred. */ public static String formatLogMessage(String entryKind, String logEntry) throws XMLStreamException, IOException { String lineSeparator = System.getProperty("line.separator"); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = factory.createXMLStreamWriter(outStream); EwsUtilities.writeTraceStartElement(writer, entryKind, false); writer.writeCharacters(lineSeparator); writer.writeCharacters(logEntry); writer.writeCharacters(lineSeparator); writer.writeEndElement(); writer.writeCharacters(lineSeparator); writer.flush(); writer.close(); outStream.flush(); String formattedLogMessage = outStream.toString(); formattedLogMessage = formattedLogMessage.replaceAll("'", "'"); formattedLogMessage = formattedLogMessage.replaceAll(""", "\""); formattedLogMessage = formattedLogMessage.replaceAll(">", ">"); formattedLogMessage = formattedLogMessage.replaceAll("<", "<"); formattedLogMessage = formattedLogMessage.replaceAll("&", "&"); outStream.close(); return formattedLogMessage; }
From source file:edu.cmu.sei.ams.cloudlet.impl.CloudletCommandExecutorImpl.java
/** * Gets a file from the response and stores it into a file. Returns the MD5 hash of the file. * @param response//from w w w . j a v a 2 s . c o m * @param decryptResponse * @return */ private String getResponseFile(final HttpResponse response, boolean decryptResponse, File outputFile) throws CloudletException { String responseText = ""; if (response == null) { return responseText; } try { HttpEntity entity = response.getEntity(); if (entity != null && entity.getContentLength() > 0) { // To compute the md5 hash. MessageDigest md = MessageDigest.getInstance("MD5"); final InputStream is = entity.getContent(); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); // Get data and store it into a byte array output stream. byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) > 0) { md.update(buffer, 0, len); bos.write(buffer, 0, len); } bos.flush(); bos.close(); is.close(); // Decrypt if needed. byte[] fileData = bos.toByteArray(); if (this.encryptionEnabled && decryptResponse) { fileData = this.encrypter.decrypt(new String(bos.toByteArray())); } // Move from the byte array into the output file. final OutputStream os = new FileOutputStream(outputFile); os.write(fileData, 0, fileData.length); os.flush(); os.close(); responseText = bytesToHex(md.digest()); } else { //Server didn't return a file for some reason, even though we were expecting one. throw new CloudletException("Server did not return a file"); } } catch (IOException e) { log.error("IO Exception in the response!", e); } catch (NoSuchAlgorithmException e) { log.error("NoSuchAlgorithmException Exception in the response!", e); } catch (EncryptionException e) { log.error("EncryptionException in the response!", e); } return responseText; }
From source file:ispok.pres.bb.NewVisitor.java
/** * * @return/*ww w . ja va 2 s .co m*/ */ public String addVisitor() { PostalCodeDto postalCodeDto = new PostalCodeDto(postalCode); postalCodeService.savePostalCode(postalCodeDto); CityDto cityDto = new CityDto(city); cityService.saveCity(cityDto); RegionDto regionDto = new RegionDto(region); regionService.saveRegion(regionDto); DomicileDto domicileDto = new DomicileDto(); domicileDto.setAddress1(address); domicileDto.setCityId(cityDto.getId()); domicileDto.setPostalCodeId(postalCodeDto.getId()); logger.debug("Country: {}", countryId); domicileDto.setCountryId(countryId); domicileDto.setRegionId(regionDto.getId()); domicileService.saveDomicile(domicileDto); VisitorDto visitorDto = new VisitorDto(); visitorDto.setFirstName(firstName); visitorDto.setLastName(lastName); visitorDto.setBirthDate(birthDate); visitorDto.setNin(nin); visitorDto.setNickname(nickname); visitorDto.setTelephone(telephone); visitorDto.setEmail(email); visitorDto.setSex(sex); visitorDto.setPassword(password); visitorDto.setBonusPoints(0); logger.debug("Citizenship: {}", citizenshipId); if (citizenshipId == null) { citizenshipId = countryId; } visitorDto.setCitizenshipId(citizenshipId); visitorDto.setDomicileId(domicileDto.getId()); try { logger.trace("Read photo file"); logger.debug("Photo name: {}", photoFile.getFileName()); BufferedImage originalPhotoImage = ImageIO.read(photoFile.getInputstream()); int width = originalPhotoImage.getWidth(); int height = originalPhotoImage.getHeight(); float scaleFactorNormalize; float scaleFactorThumb; if (height > width) { scaleFactorThumb = (float) 200 / height; scaleFactorNormalize = (float) 500 / height; } else { scaleFactorThumb = (float) 200 / width; scaleFactorNormalize = (float) 500 / width; } logger.debug("Scale factor for normalized photo: {}", scaleFactorNormalize); logger.debug("Scale factor for photo thumbnail: {}", scaleFactorThumb); // Image scaledImage = bi.getScaledInstance((int) (width * scaleFactor), (int) (height * scaleFactor), Image.SCALE_SMOOTH); // BufferedImage resizedImage = new BufferedImage((int) (width * scaleFactor), (int) (height * scaleFactor), bi.getType()); // Graphics2D g = resizedImage.createGraphics(); // g.drawImage(scaledImage, 0, 0, new Color(0, 0, 0), null); // g.dispose(); // // BufferedImage resizedImage = bi.getScaledInstance(width, height, width) // AffineTransform at = AffineTransform.getScaleInstance(scaleFactor, scaleFactor); // AffineTransformOp ato = new AffineTransformOp(at, null); // Graphics2D g = bi.createGraphics(); // g.drawImage(bi, ato, 0, 0); // g.dispose(); // int normalizedWidth = (int) (width * scaleFactorNormalize); int normalizeHeight = (int) (height * scaleFactorNormalize); logger.debug("Normalized Width: {}", normalizedWidth); logger.debug("Normalized Height: {}", normalizeHeight); int thumbWidth = (int) (width * scaleFactorThumb); int thumbHeight = (int) (height * scaleFactorThumb); logger.debug("Thumb width: {}", thumbWidth); logger.debug("Thumb height: {}", thumbHeight); BufferedImage normalizedPhotoImage = ImageUtil.resizeImage(originalPhotoImage, normalizedWidth, normalizeHeight); logger.debug("Width of normalized photo: {}", normalizedPhotoImage.getWidth()); logger.debug("Height of normalized photo: {}", normalizedPhotoImage.getHeight()); BufferedImage thumbPhotoImage = ImageUtil.resizeImage(originalPhotoImage, thumbWidth, thumbHeight); logger.debug("Width of thumb photo: {}", thumbPhotoImage.getWidth()); logger.debug("Height of thumb photo: {}", thumbPhotoImage.getHeight()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(normalizedPhotoImage, "png", baos); baos.flush(); normalizedPhotoData = baos.toByteArray(); baos = new ByteArrayOutputStream(); ImageIO.write(thumbPhotoImage, "png", baos); baos.flush(); thumbPhotoData = baos.toByteArray(); } catch (IOException ex) { logger.catching(ex); } if (photoFile != null) { visitorDto.setPhoto(normalizedPhotoData); } else { visitorDto.setPhoto(new byte[0]); } if ("".equals(password)) { password = RandomString.getRandomString(6); } visitorService.addVisitor(visitorDto); id = visitorDto.getId(); return "/admin/management/visitors/confirmNew.xhtml"; }
From source file:it.govpay.web.rs.dars.anagrafica.uo.UnitaOperativeHandler.java
@Override public UnitaOperativa creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd) throws WebApplicationException, ConsoleException { String methodName = "creaEntry " + this.titoloServizio; UnitaOperativa entry = null;//w w w .j a v a2 s. c om try { this.log.info("Esecuzione " + methodName + " in corso..."); // Operazione consentita solo ai ruoli con diritto di scrittura this.darsService.checkDirittiServizioScrittura(bd, this.funzionalita); JsonConfig jsonConfig = new JsonConfig(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Utils.copy(is, baos); baos.flush(); baos.close(); JSONObject jsonObject = JSONObject.fromObject(baos.toString()); jsonConfig.setRootClass(UnitaOperativa.class); entry = (UnitaOperativa) JSONObject.toBean(jsonObject, jsonConfig); //jsonObjectIntermediario = JSONObject.fromObject( baos.toString() ); jsonConfig.setRootClass(Anagrafica.class); Anagrafica anagrafica = (Anagrafica) JSONObject.toBean(jsonObject, jsonConfig); anagrafica.setCodUnivoco(entry.getCodUo()); entry.setAnagrafica(anagrafica); this.log.info("Esecuzione " + methodName + " completata."); return entry; } catch (WebApplicationException e) { throw e; } catch (Exception e) { throw new ConsoleException(e); } }
From source file:com.webpagebytes.cms.controllers.FlatStorageImporterExporter.java
protected void exportFiles(ZipOutputStream zos, String path) throws WPBIOException { try {/*from w ww.ja va 2 s . co m*/ List<WPBFile> files = dataStorage.getAllRecords(WPBFile.class); for (WPBFile file : files) { String fileXmlPath = path + file.getExternalKey() + "/" + "metadata.xml"; Map<String, Object> map = new HashMap<String, Object>(); exporter.export(file, map); ZipEntry metadataZe = new ZipEntry(fileXmlPath); zos.putNextEntry(metadataZe); exportToXMLFormat(map, zos); zos.closeEntry(); String contentPath = String.format(PATH_FILE_CONTENT, file.getExternalKey()); ZipEntry contentZe = new ZipEntry(contentPath); zos.putNextEntry(contentZe); zos.closeEntry(); if (file.getDirectoryFlag() == null || file.getDirectoryFlag() != 1) { try { String filePath = contentPath + file.getFileName(); WPBFilePath cloudFile = new WPBFilePath(PUBLIC_BUCKET, file.getBlobKey()); InputStream is = cloudFileStorage.getFileContent(cloudFile); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(is, bos); bos.flush(); byte[] content = bos.toByteArray(); ZipEntry fileZe = new ZipEntry(filePath); zos.putNextEntry(fileZe); zos.write(content); zos.closeEntry(); } catch (Exception e) { log.log(Level.SEVERE, " Exporting file :" + file.getExternalKey(), e); // do nothing, we do not abort the export because of a failure, but we need to log this as warning } } } } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); throw new WPBIOException("Cannot export files to Zip", e); } }
From source file:nl.b3p.viewer.stripes.SldActionBean.java
private void getSldXmlOrCreateNewSld() throws Exception { if (id != null) { StyleLibrary sld = Stripersist.getEntityManager().find(StyleLibrary.class, id); if (sld == null) { throw new IllegalArgumentException("Can't find SLD in Flamingo service registry with id " + id); }/*from w w w .ja v a 2 s . c o m*/ if (sld.getExternalUrl() == null) { sldXml = sld.getSldBody().getBytes("UTF8"); } else { // retrieve external sld try { InputStream externalSld = new URL(sld.getExternalUrl()).openStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(externalSld, bos); externalSld.close(); bos.flush(); bos.close(); sldXml = bos.toByteArray(); } catch (IOException e) { throw new IOException("Error retrieving external SLD from URL " + sld.getExternalUrl(), e); } } } else { // No SLD from database or external SLD; create new empty SLD newSld = sldFactory.createStyledLayerDescriptor(); FilterFactory2 filterFactory = CommonFactoryFinder.getFilterFactory2(); String[] layers = null; String[] filters = null; String[] styles = null; String[] colors = null; if (layer != null) { layers = layer.split(","); } if (filter != null) { try { JSONArray jsonFilters = new JSONArray(filter); filters = new String[jsonFilters.length()]; for (int i = 0; i < jsonFilters.length(); i++) { filters[i] = jsonFilters.getString(i); } } catch (JSONException je) { log.warn("error while parsing filters to JSON", je); filters = filter.split(","); } } if (color != null) { colors = color.split(","); } if (style != null) { styles = style.split(","); } Filter andFilter = null; Filter orFilter = null; if (commonAndFilter != null) { //GeoServer encodes the sld url even if its a valid url if (commonAndFilter.indexOf("%") > 0) { commonAndFilter = URI.decode(commonAndFilter); } andFilter = ECQL.toFilter(commonAndFilter); } if (commonOrFilter != null) { //GeoServer encodes the sld url even if its a valid url if (commonOrFilter.indexOf("%") > 0) { commonOrFilter = URI.decode(commonOrFilter); } orFilter = ECQL.toFilter(commonOrFilter); } if (layers != null) { for (int i = 0; i < layers.length; i++) { Filter filter = null; if (filters != null && i < filters.length && !"none".equals(filters[i]) && filters[i].length() > 0) { filter = ECQL.toFilter(filters[i]); } NamedLayer nl = sldFactory.createNamedLayer(); nl.setName(layers[i]); newSld.addStyledLayer(nl); //Combine filter with allAndFilter and allOrFilter if (andFilter != null) { if (filter == null) { filter = andFilter; } else { filter = filterFactory.and(filter, andFilter); } } if (orFilter != null) { if (filter == null) { filter = orFilter; } else { filter = filterFactory.or(filter, orFilter); } } if (styles != null && i < styles.length && !"none".equals(styles[i])) { NamedStyle ns = sldFactory.createNamedStyle(); ns.setName(styles[i]); nl.addStyle(ns); } else if (colors != null && i < colors.length) { //create featureTypeStyle FeatureTypeStyle fts = sldFactory.createFeatureTypeStyle(); Rule r = sldFactory.createRule(); if (useRuleFilter && filter != null) { r.setFilter(filter); } PolygonSymbolizer ps = createPolygonSymbolizer(sldFactory, colors[i]); r.symbolizers().add(ps); fts.rules().add(r); // add style to namedlayer Style style = sldFactory.createStyle(); style.setDefault(true); style.setName("default"); style.featureTypeStyles().add(fts); nl.addStyle(style); } else { NamedStyle ns = sldFactory.createNamedStyle(); ns.setName("default"); nl.addStyle(ns); } //if no featuretypestyle (created with color) then make featuretypeconstraint if (!useRuleFilter && filter != null) { // XXX name should be a feature type name from DescribeLayer response // use extra parameter... FeatureTypeConstraint ftc = sldFactory.createFeatureTypeConstraint(layers[i], filter, new Extent[] {}); nl.setLayerFeatureConstraints(new FeatureTypeConstraint[] { ftc }); } } } } }
From source file:com.indeed.imhotep.iql.cache.S3QueryCache.java
@Override public OutputStream getOutputStream(final String cachedFileName) throws IOException { if (!enabled) { throw new IllegalStateException("Can't send data to S3 cache as it is disabled"); }//from ww w . j a v a 2 s .c om final ByteArrayOutputStream os = new ByteArrayOutputStream(); // Wrap the returned OutputStream so that we can write to buffer and do actual write on close() return new OutputStream() { private boolean closed = false; @Override public void write(byte[] b) throws IOException { os.write(b); } @Override public void write(byte[] b, int off, int len) throws IOException { os.write(b, off, len); } @Override public void flush() throws IOException { os.flush(); } @Override public void write(int b) throws IOException { os.write(b); } @Override public void close() throws IOException { if (closed) { return; } closed = true; os.close(); // do actual write byte[] csvData = os.toByteArray(); ByteArrayInputStream is = new ByteArrayInputStream(csvData); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(csvData.length); client.putObject(bucket, cachedFileName, is, metadata); } }; }
From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java
/** * uploads measurements data as a batch file * @param dbIterator/* w ww . ja v a 2s. c om*/ * @param latLonFormat * @param count * @param max * @return number of uploaded measurements */ private int uploadMeasurementsBatch(MeasurementsDBIterator dbIterator, NumberFormat latLonFormat, int count, int max) { writeToLog("uploadMeasurementsBatch(" + count + ", " + max + ")"); try { StringBuilder sb = new StringBuilder( "lat,lon,mcc,mnc,lac,cellid,signal,measured_at,rating,speed,direction,act\n"); int thisBatchSize = 0; while (thisBatchSize < MEASUREMENTS_BATCH_SIZE && dbIterator.hasNext() && uploadThreadRunning) { Measurement meassurement = dbIterator.next(); sb.append(latLonFormat.format(meassurement.getLat())).append(","); sb.append(latLonFormat.format(meassurement.getLon())).append(","); sb.append(meassurement.getMcc()).append(","); sb.append(meassurement.getMnc()).append(","); sb.append(meassurement.getLac()).append(","); sb.append(meassurement.getCellid()).append(","); sb.append(meassurement.getGsmSignalStrength()).append(","); sb.append(meassurement.getTimestamp()).append(","); sb.append((meassurement.getAccuracy() != null) ? meassurement.getAccuracy() : "").append(","); sb.append((int) meassurement.getSpeed()).append(","); sb.append((int) meassurement.getBearing()).append(","); sb.append((meassurement.getNetworkType() != null) ? meassurement.getNetworkType() : ""); sb.append("\n"); thisBatchSize++; } HttpResponse response = null; writeToLog("Upload request URL: " + httppost.getURI()); if (uploadThreadRunning) { String csv = sb.toString(); writeToLog("Upload data: " + csv); MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart("key", new StringBody(apiKey)); mpEntity.addPart("appId", new StringBody(appId)); mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(csv.getBytes()), "text/csv", MULTIPART_FILENAME)); ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); // reqEntity is the MultipartEntity instance mpEntity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(false); bArrEntity.setContentEncoding(mpEntity.getContentEncoding()); bArrEntity.setContentType(mpEntity.getContentType()); httppost.setEntity(bArrEntity); response = httpclient.execute(httppost); if (response == null) { writeToLog("Upload: null HTTP-response"); throw new IllegalStateException("no HTTP-response from server"); } HttpEntity resEntity = response.getEntity(); writeToLog( "Upload: " + response.getStatusLine().getStatusCode() + " - " + response.getStatusLine()); if (resEntity != null) { resEntity.consumeContent(); } if (response.getStatusLine() == null) { writeToLog(": " + "null HTTP-status-line"); throw new IllegalStateException("no HTTP-status returned"); } if (response.getStatusLine().getStatusCode() != 200) { throw new IllegalStateException( "HTTP-status code returned : " + response.getStatusLine().getStatusCode()); } } return count + thisBatchSize; } catch (IOException e) { throw new IllegalStateException("IO-Error: " + e.getMessage()); } }
From source file:org.signserver.client.cli.performance.PerformanceTestPDFServlet.java
License:asdf
/** * Creates a new PDF document by adding the same paragraph over and over. * @param requestSize is the requested size of the PDF in bytes *///from w ww. ja v a2 s.co m private byte[] createTestPDF(int requestSize) throws Exception { // Create a sample PDF-file ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document pdfDocument = new Document(PageSize.A4, 50, 50, 50, 50); PdfWriter.getInstance(pdfDocument, baos); pdfDocument.open(); pdfDocument.add(new Paragraph(PDF_CONTENT)); final String DUMMYTEXT = "qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxc"; int maxIteration = requestSize / 20; for (int i = 0; i < maxIteration; i++) { pdfDocument.add(new Paragraph(DUMMYTEXT)); } pdfDocument.close(); baos.flush(); System.out.println("Created new PDF-document of " + baos.toByteArray().length + " bytes."); return baos.toByteArray(); }