List of usage examples for org.apache.commons.io.output ByteArrayOutputStream write
public synchronized int write(InputStream in) throws IOException
From source file:org.jcodec.common.io.ReaderBE.java
public static byte[] readAll(InputStream input) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b;/*from w ww . j av a2s.com*/ while ((b = input.read()) != -1) baos.write(b); return baos.toByteArray(); }
From source file:org.mule.routing.MessageChunkAggregator.java
@Override protected EventCorrelatorCallback getCorrelatorCallback(MuleContext muleContext) { return new CollectionCorrelatorCallback(muleContext, persistentStores, storePrefix) { /**/*from w w w . ja va 2s . c o m*/ * This method is invoked if the shouldAggregate method is called and * returns true. Once this method returns an aggregated message the event * group is removed from the router * * @param events the event group for this request * @return an aggregated message * @throws org.mule.routing.AggregationException if the aggregation * fails. in this scenario the whole event group is removed * and passed to the exception handler for this componenet */ @Override public MuleEvent aggregateEvents(EventGroup events) throws AggregationException { MuleEvent[] collectedEvents; try { collectedEvents = events.toArray(false); } catch (ObjectStoreException e) { throw new AggregationException(events, MessageChunkAggregator.this, e); } MuleEvent firstEvent = collectedEvents[0]; Arrays.sort(collectedEvents, eventComparator); ByteArrayOutputStream baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE); try { for (MuleEvent event : collectedEvents) { baos.write(event.getMessageAsBytes()); } MuleMessage message; // try to deserialize message, since ChunkingRouter might have // serialized // the object... try { // must deserialize in correct classloader final Object deserialized = SerializationUtils.deserialize(baos.toByteArray(), muleContext); message = new DefaultMuleMessage(deserialized, firstEvent.getMessage(), muleContext); } catch (SerializationException e) { message = new DefaultMuleMessage(baos.toByteArray(), firstEvent.getMessage(), muleContext); } message.setCorrelationGroupSize(-1); message.setCorrelationSequence(-1); return new DefaultMuleEvent(message, firstEvent, getMergedSession(events.toArray())); } catch (Exception e) { throw new AggregationException(events, MessageChunkAggregator.this, e); } finally { IOUtils.closeQuietly(baos); } } }; }
From source file:org.mule.transport.jms.integration.JmsTransformersTestCase.java
@Test public void testCompressedBytesMessage() throws Exception { RequestContext.setEvent(getTestEvent("test")); // use GZIP/*www . j a va 2 s . c o m*/ CompressionStrategy compressor = new GZipCompression(); // create compressible data ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i = 0; i < 5000; i++) { baos.write(i); } byte[] originalBytes = baos.toByteArray(); byte[] compressedBytes = compressor.compressByteArray(originalBytes); assertTrue("Source compressedBytes should be compressed", compressor.isCompressed(compressedBytes)); // now create a BytesMessage from the compressed byte[] AbstractJmsTransformer trans = new SessionEnabledObjectToJMSMessage(session); trans.setReturnDataType(DataTypeFactory.create(BytesMessage.class)); initialiseObject(trans); Object result2 = trans.transform(compressedBytes); assertTrue("Transformed object should be a Bytes message", result2 instanceof BytesMessage); // check whether the BytesMessage contains the compressed bytes BytesMessage intermediate = (BytesMessage) result2; intermediate.reset(); byte[] intermediateBytes = new byte[(int) (intermediate.getBodyLength())]; int intermediateSize = intermediate.readBytes(intermediateBytes); assertTrue("Intermediate bytes must be compressed", compressor.isCompressed(intermediateBytes)); assertTrue("Intermediate bytes must be equal to compressed source", Arrays.equals(compressedBytes, intermediateBytes)); assertEquals("Intermediate bytes and compressed source must have same size", compressedBytes.length, intermediateSize); // now test the other way around: getting the byte[] from a manually created // BytesMessage AbstractJmsTransformer trans2 = createObject(JMSMessageToObject.class); trans2.setReturnDataType(DataTypeFactory.BYTE_ARRAY); BytesMessage bMsg = session.createBytesMessage(); bMsg.writeBytes(compressedBytes); Object result = trans2.transform(bMsg); assertTrue("Transformed object should be a byte[]", result instanceof byte[]); assertTrue("Result should be compressed", compressor.isCompressed((byte[]) result)); assertTrue("Source and result should be equal", Arrays.equals(compressedBytes, (byte[]) result)); }
From source file:org.mule.transport.soap.axis.extensions.MuleHttpSender.java
/** * Reads the SOAP response back from the server * * @param msgContext message context//from ww w . j a va 2 s. c om * @throws IOException */ private InputStream readFromSocket(SocketHolder socketHolder, MessageContext msgContext, InputStream inp, Hashtable headers) throws IOException { Message outMsg = null; byte b; Integer rc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE); int returnCode = 0; if (rc != null) { returnCode = rc.intValue(); } else { // No return code?? Should have one by now. } /* All HTTP headers have been read. */ String contentType = (String) headers.get(HEADER_CONTENT_TYPE_LC); contentType = (null == contentType) ? null : contentType.trim(); String location = (String) headers.get(HEADER_LOCATION_LC); location = (null == location) ? null : location.trim(); if ((returnCode > 199) && (returnCode < 300)) { if (returnCode == 202) { return inp; } // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall through, since the range of // valid result codes is much greater } else if ((contentType != null) && !contentType.startsWith("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so fall through } else if ((location != null) && ((returnCode == 302) || (returnCode == 307))) { // Temporary Redirect (HTTP: 302/307) // close old connection inp.close(); socketHolder.getSocket().close(); // remove former result and set new target url msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE); msgContext.setProperty(MessageContext.TRANS_URL, location); // next try invoke(msgContext); return inp; } else if (returnCode == 100) { msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_CODE); msgContext.removeProperty(HTTPConstants.MC_HTTP_STATUS_MESSAGE); readHeadersFromSocket(socketHolder, msgContext, inp, headers); return readFromSocket(socketHolder, msgContext, inp, headers); } else { // Unknown return code - so wrap up the content into a // SOAP Fault. ByteArrayOutputStream buf = new ByteArrayOutputStream(4097); while (-1 != (b = (byte) inp.read())) { buf.write(b); } String statusMessage = msgContext.getStrProp(HTTPConstants.MC_HTTP_STATUS_MESSAGE); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); fault.setFaultDetailString(Messages.getMessage("return01", String.valueOf(returnCode), buf.toString())); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } String contentLocation = (String) headers.get(HEADER_CONTENT_LOCATION_LC); contentLocation = (null == contentLocation) ? null : contentLocation.trim(); String contentLength = (String) headers.get(HEADER_CONTENT_LENGTH_LC); contentLength = (null == contentLength) ? null : contentLength.trim(); String transferEncoding = (String) headers.get(HEADER_TRANSFER_ENCODING_LC); if (null != transferEncoding) { transferEncoding = transferEncoding.trim().toLowerCase(); if (transferEncoding.equals(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) { inp = new ChunkedInputStream(inp); } } outMsg = new Message(new SocketInputStream(inp, socketHolder.getSocket()), false, contentType, contentLocation); // Transfer HTTP headers of HTTP message to MIME headers of SOAP message MimeHeaders mimeHeaders = outMsg.getMimeHeaders(); for (Enumeration e = headers.keys(); e.hasMoreElements();) { String key = (String) e.nextElement(); mimeHeaders.addHeader(key, ((String) headers.get(key)).trim()); } outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { if (null == contentLength) { log.debug(SystemUtils.LINE_SEPARATOR + Messages.getMessage("no00", "Content-Length")); } log.debug(SystemUtils.LINE_SEPARATOR + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPEnvelope().toString()); } // if we are maintaining session state, // handle cookies (if any) if (msgContext.getMaintainSession()) { handleCookie(HTTPConstants.HEADER_COOKIE, HTTPConstants.HEADER_SET_COOKIE, headers, msgContext); handleCookie(HTTPConstants.HEADER_COOKIE2, HTTPConstants.HEADER_SET_COOKIE2, headers, msgContext); } return inp; }
From source file:org.pentaho.platform.plugin.services.pluginmgr.PluginResourceLoader.java
public byte[] getResourceAsBytes(Class<? extends Object> clazz, String resourcePath) { InputStream in = getResourceAsStream(clazz, resourcePath); if (in == null) { return null; }/*from w w w. j a va 2 s .com*/ ByteArrayOutputStream out = new ByteArrayOutputStream(); try { out.write(in); } catch (IOException e) { Logger.debug(this, "Cannot open stream to resource", e); //$NON-NLS-1$ return null; } finally { IOUtils.closeQuietly(in); } return out.toByteArray(); }
From source file:org.richfaces.request.FileUploadValueParamTest.java
@Test public void testLongParam() throws Exception { StringBuilder sb = new StringBuilder(); CharsetEncoder charsetEncoder = Charset.forName("UTF-8").newEncoder(); for (int i = 0; i < 256; i++) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int count = new Random().nextInt(128) + 128; while (count != 0) { char c = (char) new Random().nextInt(Character.MAX_VALUE); if (charsetEncoder.canEncode(c)) { baos.write(charsetEncoder.encode(CharBuffer.wrap(new char[] { c })).array()); count--;/*w w w. ja va 2 s . c o m*/ } } byte[] bs = baos.toByteArray(); param.handle(bs, bs.length); sb.append(new String(bs, "UTF-8")); } param.complete(); assertEquals(sb.toString(), param.getValue()); }
From source file:uk.co.tfd.sm.proxy.ProxyServletVivoMan.java
@Test public void testVivoFeed() throws Exception { when(request.getPathInfo()).thenReturn("/tests/vivo"); when(request.getHeaderNames()).thenReturn(headerNames.elements()); Map<String, String[]> requestParameters = ImmutableMap.of("id", new String[] { "n7934" }); when(request.getParameterMap()).thenReturn(requestParameters); final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); when(response.getOutputStream()).thenReturn(new ServletOutputStream() { @Override//from w ww. j av a 2 s . co m public void write(int v) throws IOException { byteArrayOutputStream.write(v); } }); long s = System.currentTimeMillis(); servlet.service(request, response); LOGGER.info("Took {} ", (System.currentTimeMillis() - s)); verify(response, Mockito.atMost(0)).sendError(404); String output = byteArrayOutputStream.toString("UTF-8"); LOGGER.info("Got Response {} ", output); }
From source file:voldemort.rest.coordinator.admin.CoordinatorAdminRequestHandler.java
public HttpResponse sendResponse(HttpResponseStatus responseCode, String responseBody) { String actualResponseBody = responseBody + "\n"; HttpResponse response = new DefaultHttpResponse(HTTP_1_1, responseCode); response.setHeader(CONTENT_LENGTH, actualResponseBody.length()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {// w w w . java 2s. c o m outputStream.write(actualResponseBody.getBytes()); } catch (IOException e) { logger.error("IOException while trying to write the outputStream for an admin response", e); throw new RuntimeException(e); } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(outputStream.toByteArray()); response.setContent(responseContent); if (logger.isDebugEnabled()) { logger.debug("Sent " + response); } return response; }
From source file:xc.mst.bo.record.Record.java
public void setMode(String mode) { if (!mode.equals(this.mode)) { if (mode.equals(STRING_MODE)) { if (this.oaiXmlEl != null) { this.oaiXml = xmlHelper.getString(this.oaiXmlEl); } else { this.oaiXml = null; }/* w w w . j a v a 2 s . c o m*/ } else if (mode.equals(JDOM_MODE)) { if (this.oaiXml != null) { try { TimingLogger.start("getJDomDocument()"); org.jdom.Document d = xmlHelper.getJDomDocument(this.oaiXml); TimingLogger.stop("getJDomDocument()"); this.oaiXmlEl = d.detachRootElement(); } catch (Throwable t) { LOG.error("this.oaiXml.getBytes()"); LOG.error("", t); System.out.println("error!!!"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { baos.write(this.oaiXml.getBytes("UTF-8")); baos.writeTo(System.out); } catch (Throwable t2) { LOG.error("", t2); } System.out.println("error!!!"); this.oaiXmlEl = null; } } else { this.oaiXmlEl = null; } } else { throw new RuntimeException("invalid mode!!!"); } this.mode = mode; } }