Search in sources :

Example 51 with ObjectOutputStream

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

the class DefaultNettyHttpBinding method toNettyResponse.

@Override
public HttpResponse toNettyResponse(Message message, NettyHttpConfiguration configuration) throws Exception {
    LOG.trace("toNettyResponse: {}", message);
    // the message body may already be a Netty HTTP response
    if (message.getBody() instanceof HttpResponse) {
        return (HttpResponse) message.getBody();
    }
    // the response code is 200 for OK and 500 for failed
    boolean failed = message.getExchange().isFailed();
    int defaultCode = failed ? 500 : 200;
    int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class);
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code));
    LOG.trace("HTTP Status Code: {}", code);
    TypeConverter tc = message.getExchange().getContext().getTypeConverter();
    // must use entrySet to ensure case of keys is preserved
    for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();
        // use an iterator as there can be multiple values. (must not use a delimiter)
        final Iterator<?> it = ObjectHelper.createIterator(value, null);
        while (it.hasNext()) {
            String headerValue = tc.convertTo(String.class, it.next());
            if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) {
                LOG.trace("HTTP-Header: {}={}", key, headerValue);
                response.headers().add(key, headerValue);
            }
        }
    }
    Object body = message.getBody();
    Exception cause = message.getExchange().getException();
    // support bodies as native Netty
    ChannelBuffer buffer;
    // if there was an exception then use that as body
    if (cause != null) {
        if (configuration.isTransferException()) {
            // we failed due an exception, and transfer it as java serialized object
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(cause);
            oos.flush();
            IOHelper.close(oos, bos);
            // the body should be the serialized java object of the exception
            body = ChannelBuffers.copiedBuffer(bos.toByteArray());
            // force content type to be serialized java object
            message.setHeader(Exchange.CONTENT_TYPE, NettyHttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
        } else {
            // we failed due an exception so print it as plain text
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            cause.printStackTrace(pw);
            // the body should then be the stacktrace
            body = ChannelBuffers.copiedBuffer(sw.toString().getBytes());
            // force content type to be text/plain as that is what the stacktrace is
            message.setHeader(Exchange.CONTENT_TYPE, "text/plain");
        }
        // and mark the exception as failure handled, as we handled it by returning it as the response
        ExchangeHelper.setFailureHandled(message.getExchange());
    }
    if (body instanceof ChannelBuffer) {
        buffer = (ChannelBuffer) body;
    } else {
        // try to convert to buffer first
        buffer = message.getBody(ChannelBuffer.class);
        if (buffer == null) {
            // fallback to byte array as last resort
            byte[] data = message.getBody(byte[].class);
            if (data != null) {
                buffer = ChannelBuffers.copiedBuffer(data);
            } else {
                // and if byte array fails then try String
                String str;
                if (body != null) {
                    str = message.getMandatoryBody(String.class);
                } else {
                    str = "";
                }
                buffer = ChannelBuffers.copiedBuffer(str.getBytes());
            }
        }
    }
    if (buffer != null) {
        response.setContent(buffer);
        // We just need to reset the readerIndex this time
        if (buffer.readerIndex() == buffer.writerIndex()) {
            buffer.setIndex(0, buffer.writerIndex());
        }
        // TODO How to enable the chunk transport 
        int len = buffer.readableBytes();
        // set content-length
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, len);
        LOG.trace("Content-Length: {}", len);
    }
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        response.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
        LOG.trace("Content-Type: {}", contentType);
    }
    // configure connection to accordingly to keep alive configuration
    // favor using the header from the message
    String connection = message.getHeader(HttpHeaders.Names.CONNECTION, String.class);
    // Read the connection header from the exchange property
    if (connection == null) {
        connection = message.getExchange().getProperty(HttpHeaders.Names.CONNECTION, String.class);
    }
    if (connection == null) {
        // fallback and use the keep alive from the configuration
        if (configuration.isKeepAlive()) {
            connection = HttpHeaders.Values.KEEP_ALIVE;
        } else {
            connection = HttpHeaders.Values.CLOSE;
        }
    }
    response.headers().set(HttpHeaders.Names.CONNECTION, connection);
    // Just make sure we close the channel when the connection value is close
    if (connection.equalsIgnoreCase(HttpHeaders.Values.CLOSE)) {
        message.setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
    }
    LOG.trace("Connection: {}", connection);
    return response;
}
Also used : DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) TypeConverter(org.apache.camel.TypeConverter) StringWriter(java.io.StringWriter) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Example 52 with ObjectOutputStream

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

the class RabbitMQInOutIntTest method testSerializableObject.

@Test
public void testSerializableObject() throws IOException {
    TestSerializableObject foo = new TestSerializableObject();
    foo.setName("foobar");
    byte[] body = null;
    try (ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o = new ObjectOutputStream(b)) {
        o.writeObject(foo);
        body = b.toByteArray();
    }
    TestSerializableObject newFoo = null;
    try (InputStream b = new ByteArrayInputStream(body);
        ObjectInputStream o = new ObjectInputStream(b)) {
        newFoo = (TestSerializableObject) o.readObject();
    } catch (IOException | ClassNotFoundException e) {
    }
    assertEquals(foo.getName(), newFoo.getName());
}
Also used : TestSerializableObject(org.apache.camel.component.rabbitmq.testbeans.TestSerializableObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectInputStream(java.io.ObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ObjectOutputStream(java.io.ObjectOutputStream) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Example 53 with ObjectOutputStream

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

the class ShiroSecurityHelper method encrypt.

public static ByteSource encrypt(ShiroSecurityToken securityToken, byte[] passPhrase, CipherService cipherService) throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ObjectOutput serialStream = new ObjectOutputStream(stream);
    try {
        serialStream.writeObject(securityToken);
        return cipherService.encrypt(stream.toByteArray(), passPhrase);
    } finally {
        close(serialStream);
        IOHelper.close(stream);
    }
}
Also used : ObjectOutput(java.io.ObjectOutput) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream)

Example 54 with ObjectOutputStream

use of java.io.ObjectOutputStream in project okio by square.

the class TestUtil method reserialize.

/** Serializes original to bytes, then deserializes those bytes and returns the result. */
// Assume serialization doesn't change types.
@SuppressWarnings("unchecked")
public static <T extends Serializable> T reserialize(T original) throws Exception {
    Buffer buffer = new Buffer();
    ObjectOutputStream out = new ObjectOutputStream(buffer.outputStream());
    out.writeObject(original);
    ObjectInputStream in = new ObjectInputStream(buffer.inputStream());
    return (T) in.readObject();
}
Also used : ObjectOutputStream(java.io.ObjectOutputStream) ObjectInputStream(java.io.ObjectInputStream)

Example 55 with ObjectOutputStream

use of java.io.ObjectOutputStream in project hazelcast by hazelcast.

the class MulticastDiscoverySender method initDatagramPacket.

private void initDatagramPacket() throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out;
    out = new ObjectOutputStream(bos);
    out.writeObject(multicastMemberInfo);
    byte[] yourBytes = bos.toByteArray();
    datagramPacket = new DatagramPacket(yourBytes, yourBytes.length, InetAddress.getByName(group), port);
}
Also used : ObjectOutput(java.io.ObjectOutput) DatagramPacket(java.net.DatagramPacket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream)

Aggregations

ObjectOutputStream (java.io.ObjectOutputStream)1102 ByteArrayOutputStream (java.io.ByteArrayOutputStream)760 ObjectInputStream (java.io.ObjectInputStream)428 ByteArrayInputStream (java.io.ByteArrayInputStream)375 IOException (java.io.IOException)358 FileOutputStream (java.io.FileOutputStream)161 Test (org.junit.Test)161 File (java.io.File)96 BufferedOutputStream (java.io.BufferedOutputStream)52 ObjectOutput (java.io.ObjectOutput)47 OutputStream (java.io.OutputStream)37 HashMap (java.util.HashMap)37 ArrayList (java.util.ArrayList)33 FileInputStream (java.io.FileInputStream)25 InputStream (java.io.InputStream)23 FileNotFoundException (java.io.FileNotFoundException)22 Serializable (java.io.Serializable)17 GZIPOutputStream (java.util.zip.GZIPOutputStream)16 Test (org.testng.annotations.Test)15 NotSerializableException (java.io.NotSerializableException)14