List of usage examples for java.io ByteArrayOutputStream flush
public void flush() throws IOException
From source file:com.googlecode.esms.provider.Tim.java
/** * Perform stream to array conversion.//w ww . j a v a 2 s . c o m * @param is Stream to be converted. * @return An array of bytes. */ private byte[] toByteArray(InputStream is) throws IOException { int read; byte[] data = new byte[16 * 1024]; // 16 kB ByteArrayOutputStream buffer = new ByteArrayOutputStream(); while ((read = is.read(data, 0, data.length)) != -1) buffer.write(data, 0, read); buffer.flush(); return buffer.toByteArray(); }
From source file:org.apache.tez.dag.history.events.TestHistoryEventsProtoConversion.java
private HistoryEvent testProtoConversion(HistoryEvent event) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); HistoryEvent deserializedEvent = null; event.toProtoStream(os);//from w w w . ja va 2s . com os.flush(); os.close(); deserializedEvent = ReflectionUtils.createClazzInstance(event.getClass().getName()); LOG.info("Serialized event to byte array" + ", eventType=" + event.getEventType() + ", bufLen=" + os.toByteArray().length); deserializedEvent.fromProtoStream(new ByteArrayInputStream(os.toByteArray())); return deserializedEvent; }
From source file:com.adaptris.core.AdaptrisMessageCase.java
@Test public void testReaderWithCharEncoding() throws Exception { AdaptrisMessage msg1 = createMessage("ISO-8859-1"); Reader in = msg1.getReader(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out, "ISO-8859-1"); out.flush(); assertTrue(Arrays.equals(msg1.getPayload(), out.toByteArray())); }
From source file:org.coronastreet.gpxconverter.GarminForm.java
public void upload() { httpClient = HttpClientBuilder.create().build(); localContext = new BasicHttpContext(); cookieStore = new BasicCookieStore(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); //httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (doLogin()) { try {//w w w . j a v a 2 s. com HttpGet get = new HttpGet("http://connect.garmin.com/transfer/upload#"); HttpResponse formResponse = httpClient.execute(get, localContext); HttpEntity formEntity = formResponse.getEntity(); EntityUtils.consume(formEntity); HttpPost request = new HttpPost( "http://connect.garmin.com/proxy/upload-service-1.1/json/upload/.tcx"); request.setHeader("Referer", "http://connect.garmin.com/api/upload/widget/manualUpload.faces?uploadServiceVersion=1.1"); request.setHeader("Accept", "text/html, application/xhtml+xml, */*"); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("data", new InputStreamBody(document2InputStream(outDoc), "application/octet-stream", "temp.tcx")); // Need to do this bit because without it you can't disable chunked encoding ByteArrayOutputStream bArrOS = new ByteArrayOutputStream(); entity.writeTo(bArrOS); bArrOS.flush(); ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray()); bArrOS.close(); bArrEntity.setChunked(false); bArrEntity.setContentEncoding(entity.getContentEncoding()); bArrEntity.setContentType(entity.getContentType()); request.setEntity(bArrEntity); HttpResponse response = httpClient.execute(request, localContext); if (response.getStatusLine().getStatusCode() != 200) { log("Failed to Upload"); HttpEntity en = response.getEntity(); if (en != null) { String output = EntityUtils.toString(en); log(output); } } else { HttpEntity ent = response.getEntity(); if (ent != null) { String output = EntityUtils.toString(ent); output = "[" + output + "]"; //OMG Garmin Sucks at JSON..... JSONObject uploadResponse = new JSONArray(output).getJSONObject(0); JSONObject importResult = uploadResponse.getJSONObject("detailedImportResult"); try { int uploadID = importResult.getInt("uploadId"); log("Success! UploadID is " + uploadID); } catch (Exception e) { JSONArray failures = (JSONArray) importResult.get("failures"); JSONObject failure = (JSONObject) failures.get(0); JSONArray errorMessages = failure.getJSONArray("messages"); JSONObject errorMessage = errorMessages.getJSONObject(0); String content = errorMessage.getString("content"); log("Upload Failed! Error: " + content); } } } httpClient.close(); } catch (Exception ex) { log("Exception? " + ex.getMessage()); ex.printStackTrace(); // handle exception here } } else { log("Failed to upload!"); } }
From source file:org.apache.tez.dag.history.events.TestHistoryEventsProtoConversion.java
private HistoryEvent testSummaryProtoConversion(HistoryEvent historyEvent) throws IOException { SummaryEvent event = (SummaryEvent) historyEvent; ByteArrayOutputStream os = new ByteArrayOutputStream(); HistoryEvent deserializedEvent = null; event.toSummaryProtoStream(os);/*from w ww. jav a2 s . co m*/ os.flush(); os.close(); LOG.info("Serialized event to byte array" + ", eventType=" + historyEvent.getEventType() + ", bufLen=" + os.toByteArray().length); SummaryEventProto summaryEventProto = SummaryEventProto .parseDelimitedFrom(new ByteArrayInputStream(os.toByteArray())); deserializedEvent = ReflectionUtils.createClazzInstance(event.getClass().getName()); ((SummaryEvent) deserializedEvent).fromSummaryProtoStream(summaryEventProto); return deserializedEvent; }
From source file:com.aurel.track.admin.customize.lists.BlobBL.java
/** * Saves the uploaded file on the disk and in the database as blob * // w w w . ja v a 2 s. c o m * @param blobID * @param inputStream * @return */ public static Integer saveFileInDB(Integer blobID, InputStream inputStream) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { TBLOBBean blobBean = null; if (blobID != null) { blobBean = loadByPrimaryKey(blobID); } if (blobBean == null) { blobBean = new TBLOBBean(); } // retrieve the file data byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) { byteArrayOutputStream.write(buffer, 0, bytesRead); } blobBean.setBLOBValue(byteArrayOutputStream.toByteArray()); blobID = save(blobBean); } catch (FileNotFoundException fnfe) { LOGGER.error("Storing the iconFile on disk failed with FileNotFoundException", fnfe); } catch (IOException ioe) { LOGGER.error("Storing the attachment on disk failed: IOException", ioe); } finally { // flush and close the streams if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (byteArrayOutputStream != null) { try { byteArrayOutputStream.flush(); byteArrayOutputStream.close(); } catch (Exception e) { } } } return blobID; }
From source file:com.polyvi.xface.extension.XAppExt.java
private String drawableToBase64(Drawable drawable) { int width = drawable.getIntrinsicWidth(); int height = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, width, height); drawable.draw(canvas);/*from ww w . j a va 2 s . c om*/ String result = null; ByteArrayOutputStream baos = null; try { if (bitmap != null) { baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); baos.flush(); baos.close(); byte[] bitmapBytes = baos.toByteArray(); result = XBase64.encodeToString(bitmapBytes, Base64.DEFAULT); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (baos != null) { baos.flush(); baos.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; }
From source file:com.netsteadfast.greenstep.bsc.command.KpiReportExcelCommand.java
private int putCharts(XSSFWorkbook wb, XSSFSheet sh, Context context) throws Exception { String pieBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("pieCanvasToData")); String barBase64Content = SimpleUtils.getPNGBase64Content((String) context.get("barCanvasToData")); BufferedImage pieImage = SimpleUtils.decodeToImage(pieBase64Content); BufferedImage barImage = SimpleUtils.decodeToImage(barBase64Content); ByteArrayOutputStream pieBos = new ByteArrayOutputStream(); ImageIO.write(pieImage, "png", pieBos); pieBos.flush(); ByteArrayOutputStream barBos = new ByteArrayOutputStream(); ImageIO.write(barImage, "png", barBos); barBos.flush();//from w w w .jav a2 s . com SimpleUtils.setCellPicture(wb, sh, pieBos.toByteArray(), 0, 0); SimpleUtils.setCellPicture(wb, sh, barBos.toByteArray(), 0, 6); return 25; }
From source file:org.apache.synapse.transport.jms.JMSSender.java
/** * Create a JMS Message from the given MessageContext and using the given * session// www. j av a 2s .com * * @param msgContext the MessageContext * @param session the JMS session * @return a JMS message from the context and session * @throws JMSException on exception * @throws AxisFault on exception */ private Message createJMSMessage(MessageContext msgContext, Session session) throws JMSException, AxisFault { Message message = null; String msgType = getProperty(msgContext, JMSConstants.JMS_MESSAGE_TYPE); // check the first element of the SOAP body, do we have content wrapped using the // default wrapper elements for binary (BaseConstants.DEFAULT_BINARY_WRAPPER) or // text (BaseConstants.DEFAULT_TEXT_WRAPPER) ? If so, do not create SOAP messages // for JMS but just get the payload in its native format String jmsPayloadType = guessMessageType(msgContext); if (jmsPayloadType == null) { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = null; try { messageFormatter = TransportUtils.getMessageFormatter(msgContext); } catch (AxisFault axisFault) { throw new JMSException("Unable to get the message formatter to use"); } String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { messageFormatter.writeTo(msgContext, format, baos, true); baos.flush(); } catch (IOException e) { handleException("IO Error while creating BytesMessage", e); } if (msgType != null && JMSConstants.JMS_BYTE_MESSAGE.equals(msgType) || contentType.indexOf(HTTPConstants.HEADER_ACCEPT_MULTIPART_RELATED) > -1) { message = session.createBytesMessage(); BytesMessage bytesMsg = (BytesMessage) message; bytesMsg.writeBytes(baos.toByteArray()); } else { message = session.createTextMessage(); // default TextMessage txtMsg = (TextMessage) message; txtMsg.setText(new String(baos.toByteArray())); } message.setStringProperty(BaseConstants.CONTENT_TYPE, contentType); } else if (JMSConstants.JMS_BYTE_MESSAGE.equals(jmsPayloadType)) { message = session.createBytesMessage(); BytesMessage bytesMsg = (BytesMessage) message; OMElement wrapper = msgContext.getEnvelope().getBody() .getFirstChildWithName(BaseConstants.DEFAULT_BINARY_WRAPPER); OMNode omNode = wrapper.getFirstOMChild(); if (omNode != null && omNode instanceof OMText) { Object dh = ((OMText) omNode).getDataHandler(); if (dh != null && dh instanceof DataHandler) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ((DataHandler) dh).writeTo(baos); } catch (IOException e) { handleException("Error serializing binary content of element : " + BaseConstants.DEFAULT_BINARY_WRAPPER, e); } bytesMsg.writeBytes(baos.toByteArray()); } } } else if (JMSConstants.JMS_TEXT_MESSAGE.equals(jmsPayloadType)) { message = session.createTextMessage(); TextMessage txtMsg = (TextMessage) message; txtMsg.setText(msgContext.getEnvelope().getBody() .getFirstChildWithName(BaseConstants.DEFAULT_TEXT_WRAPPER).getText()); } // set the JMS correlation ID if specified String correlationId = getProperty(msgContext, JMSConstants.JMS_COORELATION_ID); if (correlationId == null && msgContext.getRelatesTo() != null) { correlationId = msgContext.getRelatesTo().getValue(); } if (correlationId != null) { message.setJMSCorrelationID(correlationId); } if (msgContext.isServerSide()) { // set SOAP Action as a property on the JMS message setProperty(message, msgContext, BaseConstants.SOAPACTION); } else { String action = msgContext.getOptions().getAction(); if (action != null) { message.setStringProperty(BaseConstants.SOAPACTION, action); } } JMSUtils.setTransportHeaders(msgContext, message); return message; }
From source file:com.liferay.mobile.android.http.file.FileUploadTest.java
@Test public void addFileEntry() throws Exception { DLAppService service = new DLAppService(session); long repositoryId = props.getGroupId(); long folderId = DLAppServiceTest.PARENT_FOLDER_ID; String fileName = DLAppServiceTest.SOURCE_FILE_NAME; String mimeType = DLAppServiceTest.MIME_TYPE; InputStream is = new ByteArrayInputStream("Hello".getBytes(StandardCharsets.UTF_8)); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileProgressCallback callback = new FileProgressCallback() { @Override/* w w w. j a v a 2s . c om*/ public void onBytes(byte[] bytes) { try { baos.write(bytes); } catch (IOException ioe) { fail(ioe.getMessage()); } } @Override public void onProgress(int totalBytes) { if (totalBytes == 5) { try { baos.flush(); } catch (IOException ioe) { fail(ioe.getMessage()); } } } }; UploadData data = new UploadData(is, mimeType, fileName, callback); _file = service.addFileEntry(repositoryId, folderId, fileName, mimeType, fileName, "", "", data, null); assertEquals(fileName, _file.get(DLAppServiceTest.TITLE)); assertEquals(5, callback.getTotal()); assertEquals(5, baos.size()); }