Search in sources :

Example 11 with OutputStream

use of java.io.OutputStream in project camel by apache.

the class IOConverterTest method testToOutputStreamFile.

public void testToOutputStreamFile() throws Exception {
    template.sendBodyAndHeader("file://target/test", "Hello World", Exchange.FILE_NAME, "hello.txt");
    File file = new File("target/test/hello.txt");
    OutputStream os = IOConverter.toOutputStream(file);
    assertIsInstanceOf(BufferedOutputStream.class, os);
    os.close();
}
Also used : OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) File(java.io.File)

Example 12 with OutputStream

use of java.io.OutputStream in project camel by apache.

the class MessageHelperTest method testResetStreamCache.

/*
     * Tests the {@link MessageHelper#resetStreamCache(Message)} method
     */
public void testResetStreamCache() throws Exception {
    // should not throw exceptions when Message or message body is null
    MessageHelper.resetStreamCache(null);
    MessageHelper.resetStreamCache(message);
    // handle StreamCache
    final ValueHolder<Boolean> reset = new ValueHolder<Boolean>(Boolean.FALSE);
    message.setBody(new StreamCache() {

        @SuppressWarnings("deprecation")
        public void reset() {
            reset.set(Boolean.TRUE);
        }

        public void writeTo(OutputStream os) throws IOException {
        // noop
        }

        public StreamCache copy(Exchange exchange) throws IOException {
            return null;
        }

        public boolean inMemory() {
            return true;
        }

        @Override
        public long length() {
            return 0;
        }
    });
    MessageHelper.resetStreamCache(message);
    assertTrue("Should have reset the stream cache", reset.get());
}
Also used : DefaultExchange(org.apache.camel.impl.DefaultExchange) Exchange(org.apache.camel.Exchange) StreamCache(org.apache.camel.StreamCache) OutputStream(java.io.OutputStream) IOException(java.io.IOException)

Example 13 with OutputStream

use of java.io.OutputStream in project camel by apache.

the class DefaultHttpBinding method doWriteDirectResponse.

protected void doWriteDirectResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException {
    // if content type is serialized Java object, then serialize and write it to the response
    String contentType = message.getHeader(Exchange.CONTENT_TYPE, String.class);
    if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
        if (allowJavaSerializedObject || isTransferException()) {
            try {
                Object object = message.getMandatoryBody(Serializable.class);
                HttpHelper.writeObjectToServletResponse(response, object);
                // object is written so return
                return;
            } catch (InvalidPayloadException e) {
                throw new IOException(e);
            }
        } else {
            throw new RuntimeCamelException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed");
        }
    }
    // prefer streaming
    InputStream is = null;
    if (checkChunked(message, exchange)) {
        is = message.getBody(InputStream.class);
    } else {
        // try to use input stream first, so we can copy directly
        if (!isText(contentType)) {
            is = exchange.getContext().getTypeConverter().tryConvertTo(InputStream.class, message.getBody());
        }
    }
    if (is != null) {
        ServletOutputStream os = response.getOutputStream();
        if (!checkChunked(message, exchange)) {
            CachedOutputStream stream = new CachedOutputStream(exchange);
            try {
                // copy directly from input stream to the cached output stream to get the content length
                int len = copyStream(is, stream, response.getBufferSize());
                // we need to setup the length if message is not chucked
                response.setContentLength(len);
                OutputStream current = stream.getCurrentStream();
                if (current instanceof ByteArrayOutputStream) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Streaming (direct) response in non-chunked mode with content-length {}");
                    }
                    ByteArrayOutputStream bos = (ByteArrayOutputStream) current;
                    bos.writeTo(os);
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Streaming response in non-chunked mode with content-length {} and buffer size: {}", len, len);
                    }
                    copyStream(stream.getInputStream(), os, len);
                }
            } finally {
                IOHelper.close(is, os);
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Streaming response in chunked mode with buffer size {}", response.getBufferSize());
            }
            copyStream(is, os, response.getBufferSize());
        }
    } else {
        // not convertable as a stream so fallback as a String
        String data = message.getBody(String.class);
        if (data != null) {
            // set content length and encoding before we write data
            String charset = IOHelper.getCharsetName(exchange, true);
            final int dataByteLength = data.getBytes(charset).length;
            response.setCharacterEncoding(charset);
            response.setContentLength(dataByteLength);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Writing response in non-chunked mode as plain text with content-length {} and buffer size: {}", dataByteLength, response.getBufferSize());
            }
            try {
                response.getWriter().print(data);
            } finally {
                response.getWriter().flush();
            }
        }
    }
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) CachedOutputStream(org.apache.camel.converter.stream.CachedOutputStream) RuntimeCamelException(org.apache.camel.RuntimeCamelException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvalidPayloadException(org.apache.camel.InvalidPayloadException) Endpoint(org.apache.camel.Endpoint) CachedOutputStream(org.apache.camel.converter.stream.CachedOutputStream)

Example 14 with OutputStream

use of java.io.OutputStream in project camel by apache.

the class SessionReflectionHandler method handle.

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    HttpSession session = request.getSession();
    OutputStream os = response.getOutputStream();
    baseRequest.setHandled(true);
    if (session.getAttribute("foo") == null) {
        session.setAttribute("foo", "bar");
        os.write("New ".getBytes());
    } else {
        os.write("Old ".getBytes());
    }
    IOHelper.copyAndCloseInput(request.getInputStream(), os);
    response.setStatus(HttpServletResponse.SC_OK);
}
Also used : HttpSession(javax.servlet.http.HttpSession) OutputStream(java.io.OutputStream)

Example 15 with OutputStream

use of java.io.OutputStream in project camel by apache.

the class Utility method setSecurityPolicy.

public static synchronized void setSecurityPolicy(String policyResourceName, String tmpFileName) throws IOException {
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(policyResourceName);
    if (in == null) {
        throw new IOException("Unable to find the resource policy.all on classpath");
    }
    File outfile = new File(tmpFileName);
    OutputStream out = new FileOutputStream(outfile);
    byte[] tmp = new byte[8192];
    int len = 0;
    while (true) {
        len = in.read(tmp);
        if (len <= 0) {
            break;
        }
        out.write(tmp, 0, len);
    }
    out.close();
    in.close();
    System.setProperty("java.security.policy", outfile.getAbsolutePath());
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File)

Aggregations

OutputStream (java.io.OutputStream)3717 IOException (java.io.IOException)1470 FileOutputStream (java.io.FileOutputStream)1192 InputStream (java.io.InputStream)1171 File (java.io.File)808 ByteArrayOutputStream (java.io.ByteArrayOutputStream)751 Test (org.junit.Test)681 BufferedOutputStream (java.io.BufferedOutputStream)418 FileInputStream (java.io.FileInputStream)380 Socket (java.net.Socket)362 ByteArrayInputStream (java.io.ByteArrayInputStream)201 OutputStreamWriter (java.io.OutputStreamWriter)201 URL (java.net.URL)193 HttpURLConnection (java.net.HttpURLConnection)162 BufferedInputStream (java.io.BufferedInputStream)151 InputStreamReader (java.io.InputStreamReader)149 FileNotFoundException (java.io.FileNotFoundException)143 Path (org.apache.hadoop.fs.Path)143 Path (java.nio.file.Path)138 BufferedReader (java.io.BufferedReader)133