List of usage examples for java.io ByteArrayOutputStream flush
public void flush() throws IOException
From source file:dtw.webmail.util.FormdataMultipart.java
/** * Returns the value of a parameter by extracting it * from the <tt>InputStream</tt> that represents the content * of the (parameter) part./*from ww w . j a va 2 s . co m*/ * * @param in <tt>InputStream</tt> that reads from the content * of the (parameter) part. * * @return the value of the parameter as <tt>String</tt>. * * @throws IOException if reading from the stream fails. */ private String extractValue(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); int i = 0; while ((i = in.read()) != -1) { out.write(i); } out.flush(); out.close(); in.close(); //JwmaKernel.getReference().debugLog().write("Retrieved value="+out.toString()); //apply a little bit of magic when returning return out.toString("iso-8859-1"); }
From source file:it.govpay.web.rs.dars.base.BaseDarsService.java
@POST @Path("/{id}/esporta") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_OCTET_STREAM }) public Response esportaDettaglio(@PathParam("id") long id, InputStream is, @Context UriInfo uriInfo) throws Exception { String methodName = "esporta " + this.getNomeServizio() + "[" + id + "]"; this.initLogger(methodName); BasicBD bd = null;/*from w w w .j av a 2 s. c o m*/ DarsResponse darsResponse = new DarsResponse(); darsResponse.setCodOperazione(this.codOperazione); try { bd = BasicBD.newInstance(this.codOperazione); bd.setIdOperatore(this.getOperatoreByPrincipal(bd).getId()); ByteArrayOutputStream baosIn = new ByteArrayOutputStream(); Utils.copy(is, baosIn); baosIn.flush(); baosIn.close(); JSONObject jsonObjectFormExport = JSONObject.fromObject(baosIn.toString()); List<RawParamValue> rawValues = new ArrayList<RawParamValue>(); for (Object key : jsonObjectFormExport.keySet()) { String value = jsonObjectFormExport.getString((String) key); if (StringUtils.isNotEmpty(value) && !"null".equals(value)) rawValues.add(new RawParamValue((String) key, value)); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zout = new ZipOutputStream(baos); String fileName = this.getDarsHandler().esporta(id, rawValues, uriInfo, bd, zout); this.log.info("Richiesta " + methodName + " evasa con successo, creato file: " + fileName); return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename=\"" + fileName + "\"").build(); } catch (WebApplicationException e) { this.log.error("Riscontrato errore di autorizzazione durante l'esecuzione del metodo " + methodName + ":" + e.getMessage(), e); throw e; } catch (Exception e) { this.log.error( "Riscontrato errore durante l'esecuzione del metodo " + methodName + ":" + e.getMessage(), e); if (bd != null) bd.rollback(); return Response.serverError().build(); } finally { this.response.setHeader("Access-Control-Allow-Origin", "*"); this.response.setHeader("Access-Control-Expose-Headers", "content-disposition"); if (bd != null) bd.closeConnection(); } }
From source file:de.thm.arsnova.ImageUtils.java
/** * Rescales an image represented by a Base64-encoded {@link String} * * @param originalImageString/*from www .j a v a2 s . c o m*/ * The original image represented by a Base64-encoded * {@link String} * @param width * the new width * @param height * the new height * @return The rescaled Image as Base64-encoded {@link String}, returns null * if the passed-on image isn't in a valid format (a Base64-Image). */ public String createCover(String originalImageString, final int width, final int height) { if (!isBase64EncodedImage(originalImageString)) { return null; } else { final String[] imgInfo = extractImageInfo(originalImageString); // imgInfo isn't null and contains two fields, this is checked by "isBase64EncodedImage"-Method final String extension = imgInfo[0]; final String base64String = imgInfo[1]; byte[] imageData = Base64.decodeBase64(base64String); try { BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imageData)); BufferedImage newImage = new BufferedImage(width, height, originalImage.getType()); Graphics2D g = newImage.createGraphics(); final double ratio = ((double) originalImage.getWidth()) / ((double) originalImage.getHeight()); int x = 0, y = 0, w = width, h = height; if (originalImage.getWidth() > originalImage.getHeight()) { final int newWidth = (int) Math.round((float) height * ratio); x = -(newWidth - width) >> 1; w = newWidth; } else if (originalImage.getWidth() < originalImage.getHeight()) { final int newHeight = (int) Math.round((float) width / ratio); y = -(newHeight - height) >> 1; h = newHeight; } g.drawImage(originalImage, x, y, w, h, null); g.dispose(); StringBuilder result = new StringBuilder(); result.append("data:image/"); result.append(extension); result.append(";base64,"); ByteArrayOutputStream output = new ByteArrayOutputStream(); ImageIO.write(newImage, extension, output); output.flush(); output.close(); result.append(Base64.encodeBase64String(output.toByteArray())); return result.toString(); } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); return null; } } }
From source file:com.excilys.sugadroid.services.impl.ksoap2.HttpClientTransportAndroid.java
@Override public void call(String soapAction, SoapEnvelope envelope) throws IOException, XmlPullParserException { if (soapAction == null) { soapAction = "\"\""; }/*from w w w.j a v a 2 s. co m*/ byte[] requestData = createRequestData(envelope); requestDump = debug ? new String(requestData) : null; responseDump = null; HttpPost method = new HttpPost(url); method.addHeader("User-Agent", "kSOAP/2.0-Excilys"); method.addHeader("SOAPAction", soapAction); method.addHeader("Content-Type", "text/xml"); HttpEntity entity = new ByteArrayEntity(requestData); method.setEntity(entity); HttpResponse response = httpClient.execute(method); InputStream inputStream = response.getEntity().getContent(); if (debug) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[256]; while (true) { int rd = inputStream.read(buf, 0, 256); if (rd == -1) { break; } bos.write(buf, 0, rd); } bos.flush(); buf = bos.toByteArray(); responseDump = new String(buf); inputStream.close(); inputStream = new ByteArrayInputStream(buf); } parseResponse(envelope, inputStream); inputStream.close(); }
From source file:com.tcl.lzhang1.mymusic.MusicUtil.java
/** * ??Post//ww w.j a v a 2s.c om * * @param post * @return * @throws AppException */ public static byte[] doHttpPost(HttpPost post) throws AppException { DefaultHttpClient httpclient = new DefaultHttpClient(); if (null == post) { return null; } HttpResponse response; HttpEntity httpentity = null; InputStream ins = null; ByteArrayOutputStream baos = null; try { response = httpclient.execute(post); httpentity = response.getEntity(); ins = httpentity.getContent(); baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = ins.read(buffer)) != -1) { baos.write(buffer, 0, len); } baos.flush(); httpentity.consumeContent(); ins.close(); baos.close(); } catch (Exception e) { e.printStackTrace(); if (e instanceof AppException) { throw (AppException) e; } } finally { ins = null; httpentity = null; httpclient = null; } return baos.toByteArray(); }
From source file:org.openremote.java.console.controller.connector.SingleThreadHttpConnector.java
@Override protected void doRequest(String url, final ControllerCallback callback, Integer timeout) { boolean doHead = false; if (callback.command == Command.GET_RESOURCE) { // Determine if we should load data if not do a head request Object[] data = (Object[]) callback.data; boolean loadData = (Boolean) data[2]; if (!loadData) { doHead = true;/*from w w w.j a va 2 s. c om*/ } } HttpUriRequest http; if (doHead) { HttpHead httpHead = new HttpHead(url); httpHead.setConfig(RequestConfig.custom().setSocketTimeout(timeout).setConnectionRequestTimeout(timeout) .setConnectTimeout(timeout).build()); http = httpHead; } else { HttpGet httpGet = new HttpGet(url); httpGet.addHeader("Accept", "application/json"); httpGet.setConfig(RequestConfig.custom().setSocketTimeout(timeout).setConnectionRequestTimeout(timeout) .setConnectTimeout(timeout).build()); http = httpGet; } try { HttpResponse response = client.execute(http); byte[] responseData = null; if (response.getEntity() != null) { InputStream is = response.getEntity().getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int read = 0; while ((read = is.read(buffer, 0, buffer.length)) != -1) { baos.write(buffer, 0, read); } baos.flush(); is.close(); responseData = baos.toByteArray(); } // java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); // String responseStr = s.hasNext() ? s.next() : ""; if (callback.command == Command.LOGOUT) { creds.clear(); } handleResponse(callback, response.getStatusLine().getStatusCode(), response.getAllHeaders(), responseData); } catch (Exception e) { if (callback.command == Command.DO_SENSOR_POLLING && e instanceof SocketTimeoutException) { callback.callback.onSuccess(null); return; } callback.callback.onFailure(ControllerResponseCode.UNKNOWN_ERROR); } }
From source file:com.netsteadfast.greenstep.bsc.command.KpisDashboardExcelCommand.java
@SuppressWarnings("unchecked") private int putCharts(XSSFWorkbook wb, XSSFSheet sh, Context context, int row) throws Exception { String barBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("barChartsData")); BufferedImage barImage = SimpleUtils.decodeToImage(barBase64Content); ByteArrayOutputStream barBos = new ByteArrayOutputStream(); ImageIO.write(barImage, "png", barBos); barBos.flush(); SimpleUtils.setCellPicture(wb, sh, barBos.toByteArray(), row, 0); //int row = 28; row = row + 32;/*from w w w . ja va2 s .com*/ List<Map<String, Object>> chartDatas = (List<Map<String, Object>>) context.get("chartDatas"); String year = (String) context.get("dateRangeLabel"); XSSFCellStyle cellHeadStyle = wb.createCellStyle(); cellHeadStyle.setFillForegroundColor(new XSSFColor(SimpleUtils.getColorRGB4POIColor("#f5f5f5"))); cellHeadStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); XSSFFont cellHeadFont = wb.createFont(); cellHeadFont.setBold(true); cellHeadStyle.setFont(cellHeadFont); int titleCellSize = 9; Row headRow = sh.createRow(row); for (int i = 0; i < titleCellSize; i++) { Cell headCell = headRow.createCell(i); headCell.setCellStyle(cellHeadStyle); headCell.setCellValue("KPIs metrics gauge ( " + year + " )"); } sh.addMergedRegion(new CellRangeAddress(row, row, 0, titleCellSize - 1)); row = row + 1; int cellLeft = 5; int rowSpace = 17; for (Map<String, Object> data : chartDatas) { Map<String, Object> nodeData = (Map<String, Object>) ((List<Object>) data.get("datas")).get(0); String pngImageData = SimpleUtils.getPNGBase64Content((String) nodeData.get("outerHTML")); BufferedImage imageData = SimpleUtils.decodeToImage(pngImageData); ByteArrayOutputStream imgBos = new ByteArrayOutputStream(); ImageIO.write(imageData, "png", imgBos); imgBos.flush(); SimpleUtils.setCellPicture(wb, sh, imgBos.toByteArray(), row, 0); XSSFColor bgColor = new XSSFColor(SimpleUtils.getColorRGB4POIColor((String) nodeData.get("bgColor"))); XSSFColor fnColor = new XSSFColor(SimpleUtils.getColorRGB4POIColor((String) nodeData.get("fontColor"))); XSSFCellStyle cellStyle = wb.createCellStyle(); cellStyle.setFillForegroundColor(bgColor); cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); XSSFFont cellFont = wb.createFont(); cellFont.setBold(true); cellFont.setColor(fnColor); cellStyle.setFont(cellFont); int perTitleCellSize = 4; Row nowRow = sh.createRow(row); for (int i = 0; i < perTitleCellSize; i++) { Cell cell1 = nowRow.createCell(cellLeft); cell1.setCellStyle(cellStyle); cell1.setCellValue((String) nodeData.get("name")); } sh.addMergedRegion(new CellRangeAddress(row, row, cellLeft, cellLeft + perTitleCellSize - 1)); nowRow = sh.createRow(row + 1); Cell cell2 = nowRow.createCell(cellLeft); cell2.setCellValue("Maximum: " + String.valueOf(nodeData.get("max"))); nowRow = sh.createRow(row + 2); Cell cell3 = nowRow.createCell(cellLeft); cell3.setCellValue("Target: " + String.valueOf(nodeData.get("target"))); nowRow = sh.createRow(row + 3); Cell cell4 = nowRow.createCell(cellLeft); cell4.setCellValue("Min: " + String.valueOf(nodeData.get("min"))); nowRow = sh.createRow(row + 4); Cell cell5 = nowRow.createCell(cellLeft); cell5.setCellValue("Score: " + String.valueOf(nodeData.get("score"))); row += rowSpace; } return row; }
From source file:it.govpay.web.rs.dars.base.BaseDarsService.java
@POST @Path("/esporta") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM }) public Response esporta(InputStream is, @Context UriInfo uriInfo) throws Exception { String methodName = "esporta " + this.getNomeServizio(); //+ "[" + sb.toString() + "]"; this.initLogger(methodName); BasicBD bd = null;// w w w. j a v a2 s.c o m DarsResponse darsResponse = new DarsResponse(); darsResponse.setCodOperazione(this.codOperazione); String idsAsString = null; try { bd = BasicBD.newInstance(this.codOperazione); bd.setIdOperatore(this.getOperatoreByPrincipal(bd).getId()); ByteArrayOutputStream baosIn = new ByteArrayOutputStream(); Utils.copy(is, baosIn); baosIn.flush(); baosIn.close(); JSONObject jsonObjectFormExport = JSONObject.fromObject(baosIn.toString()); JSONArray jsonIDS = jsonObjectFormExport.getJSONArray(IDS_TO_EXPORT_PARAMETER_ID); List<RawParamValue> rawValues = new ArrayList<RawParamValue>(); for (Object key : jsonObjectFormExport.keySet()) { String value = jsonObjectFormExport.getString((String) key); if (StringUtils.isNotEmpty(value) && !"null".equals(value)) rawValues.add(new RawParamValue((String) key, value)); } idsAsString = Utils.getValue(rawValues, IDS_TO_EXPORT_PARAMETER_ID); this.log.info("Richiesto export degli elementi con id " + idsAsString + ""); List<Long> idsToExport = new ArrayList<Long>(); if (jsonIDS != null && jsonIDS.size() > 0) for (int i = 0; i < jsonIDS.size(); i++) { long id = jsonIDS.getLong(i); idsToExport.add(id); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zout = new ZipOutputStream(baos); String fileName = this.getDarsHandler().esporta(idsToExport, rawValues, uriInfo, bd, zout); this.log.info("Richiesta " + methodName + " evasa con successo, creato file: " + fileName); return Response.ok(baos.toByteArray(), MediaType.APPLICATION_OCTET_STREAM) .header("content-disposition", "attachment; filename=\"" + fileName + "\"").build(); } catch (ExportException e) { this.log.info("Esito operazione " + methodName + " [" + idsAsString + "] : " + e.getEsito() + ", causa: " + e.getMessaggi()); darsResponse.setEsitoOperazione(e.getEsito()); darsResponse.setDettaglioEsito(e.getMessaggi()); return Response.ok(darsResponse, MediaType.APPLICATION_JSON).build(); } catch (WebApplicationException e) { this.log.error("Riscontrato errore di autorizzazione durante l'esecuzione del metodo " + methodName + ":" + e.getMessage(), e); throw e; } catch (Exception e) { this.log.error("Esito operazione " + methodName + " [" + idsAsString + "], causa: " + e.getMessage(), e); if (bd != null) bd.rollback(); return Response.serverError().build(); } finally { this.response.setHeader("Access-Control-Allow-Origin", "*"); this.response.setHeader("Access-Control-Expose-Headers", "content-disposition"); if (bd != null) bd.closeConnection(); } }
From source file:gov.nih.nci.cacis.nav.DefaultDocumentReferenceValidator.java
@Override public void validate(Node reference, XDSDocumentResolver resolver) throws DocumentReferenceValidationException { // Pull out the necessary information final String alg; final String digestValue; final String documentId; try {/*from www . jav a 2 s.com*/ alg = NAVUtils.getDigestAlgorithm(reference); digestValue = NAVUtils.getDigestValue(reference); documentId = NAVUtils.getDocumentId(reference); // CHECKSTYLE:OFF - All NAVUtils errors handled the same way. } catch (Exception ex) { // CHECKSTYLE:ON throw new DocumentReferenceValidationException( "Error extracting info from Reference: " + ex.getMessage(), ex); } if (!getSupportedAlgorithms().containsKey(alg)) { throw new DocumentReferenceValidationException("Unsupported digest algorithm: " + alg); } if (digestValue == null) { throw new DocumentReferenceValidationException("No DigestValue provided."); } // Resolve the document final InputStream in; try { in = resolver.resolve(documentId); } catch (XDSDocumentResolutionException ex) { throw new DocumentReferenceValidationException(ex); } // Generate the digest final byte[] bytes; final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); final byte[] data = new byte[16384]; int nRead; try { while ((nRead = in.read(data, 0, data.length)) != -1) { // NOPMD buffer.write(data, 0, nRead); } buffer.flush(); bytes = buffer.toByteArray(); } catch (IOException ex) { throw new DocumentReferenceValidationException(ex); } final MessageDigest digest; try { digest = MessageDigest.getInstance(getSupportedAlgorithms().get(alg)); } catch (NoSuchAlgorithmException ex) { throw new DocumentReferenceValidationException(ex); } digest.reset(); final byte[] out = digest.digest(bytes); // BASE64 encode it final String outEnc = new String(Base64.encodeBase64(out)); // Compare it if (!outEnc.equals(digestValue)) { throw new DocumentReferenceValidationException("Digests do not match."); } }
From source file:com.actelion.research.mapReduceExecSpark.executors.MapReduceExecutorSparkProxy.java
public Map<K, V> execute(final Collection<T> elements, final IMapReduce<T, K, V> mapReduce) { String serUUID = UUID.randomUUID().toString(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] bytes = null; try {/* w w w . ja va 2s . co m*/ ObjectOutputStream oos = new ObjectOutputStream(outputStream); oos.writeObject(mapReduce); oos.writeObject(elements); outputStream.flush(); bytes = outputStream.toByteArray(); System.out.println("serialization done"); } catch (IOException e) { e.printStackTrace(); } writeToSMB(serUUID, bytes); System.out.println("executing task on cluster"); try { deployTask(serUUID, elements.size(), resultDir); System.out.println("task deployment successfull"); } catch (IOException e) { e.printStackTrace(); } return null; }