Search in sources :

Example 61 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project hadoop by apache.

the class ExceptionHandler method exceptionCaught.

static DefaultFullHttpResponse exceptionCaught(Throwable cause) {
    Exception e = cause instanceof Exception ? (Exception) cause : new Exception(cause);
    if (LOG.isTraceEnabled()) {
        LOG.trace("GOT EXCEPTION", e);
    }
    //Convert exception
    if (e instanceof ParamException) {
        final ParamException paramexception = (ParamException) e;
        e = new IllegalArgumentException("Invalid value for webhdfs parameter \"" + paramexception.getParameterName() + "\": " + e.getCause().getMessage(), e);
    } else if (e instanceof ContainerException || e instanceof SecurityException) {
        e = toCause(e);
    } else if (e instanceof RemoteException) {
        e = ((RemoteException) e).unwrapRemoteException();
    }
    //Map response status
    final HttpResponseStatus s;
    if (e instanceof SecurityException) {
        s = FORBIDDEN;
    } else if (e instanceof AuthorizationException) {
        s = FORBIDDEN;
    } else if (e instanceof FileNotFoundException) {
        s = NOT_FOUND;
    } else if (e instanceof IOException) {
        s = FORBIDDEN;
    } else if (e instanceof UnsupportedOperationException) {
        s = BAD_REQUEST;
    } else if (e instanceof IllegalArgumentException) {
        s = BAD_REQUEST;
    } else {
        LOG.warn("INTERNAL_SERVER_ERROR", e);
        s = INTERNAL_SERVER_ERROR;
    }
    final byte[] js = JsonUtil.toJsonString(e).getBytes(Charsets.UTF_8);
    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, s, Unpooled.wrappedBuffer(js));
    resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8);
    resp.headers().set(CONTENT_LENGTH, js.length);
    return resp;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) AuthorizationException(org.apache.hadoop.security.authorize.AuthorizationException) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) StandbyException(org.apache.hadoop.ipc.StandbyException) ContainerException(com.sun.jersey.api.container.ContainerException) IOException(java.io.IOException) RemoteException(org.apache.hadoop.ipc.RemoteException) FileNotFoundException(java.io.FileNotFoundException) AuthorizationException(org.apache.hadoop.security.authorize.AuthorizationException) ParamException(com.sun.jersey.api.ParamException) ContainerException(com.sun.jersey.api.container.ContainerException) ParamException(com.sun.jersey.api.ParamException) RemoteException(org.apache.hadoop.ipc.RemoteException)

Example 62 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project hadoop by apache.

the class WebHdfsHandler method writeContinueHeader.

private static void writeContinueHeader(ChannelHandlerContext ctx) {
    DefaultHttpResponse r = new DefaultFullHttpResponse(HTTP_1_1, CONTINUE, Unpooled.EMPTY_BUFFER);
    ctx.writeAndFlush(r);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse)

Example 63 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project hadoop by apache.

the class FSImageHandler method exceptionCaught.

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    Exception e = cause instanceof Exception ? (Exception) cause : new Exception(cause);
    final String output = JsonUtil.toJsonString(e);
    ByteBuf content = Unpooled.wrappedBuffer(output.getBytes(Charsets.UTF_8));
    final DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR, content);
    resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8);
    if (e instanceof IllegalArgumentException) {
        resp.setStatus(BAD_REQUEST);
    } else if (e instanceof FileNotFoundException) {
        resp.setStatus(NOT_FOUND);
    } else if (e instanceof IOException) {
        resp.setStatus(FORBIDDEN);
    }
    resp.headers().set(CONTENT_LENGTH, resp.content().readableBytes());
    resp.headers().set(CONNECTION, CLOSE);
    ctx.write(resp).addListener(ChannelFutureListener.CLOSE);
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 64 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse in project hadoop by apache.

the class FSImageHandler method channelRead0.

@Override
public void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
    if (request.getMethod() != HttpMethod.GET) {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED);
        resp.headers().set(CONNECTION, CLOSE);
        ctx.write(resp).addListener(ChannelFutureListener.CLOSE);
        return;
    }
    QueryStringDecoder decoder = new QueryStringDecoder(request.getUri());
    final String op = getOp(decoder);
    final String content;
    String path = getPath(decoder);
    switch(op) {
        case "GETFILESTATUS":
            content = image.getFileStatus(path);
            break;
        case "LISTSTATUS":
            content = image.listStatus(path);
            break;
        case "GETACLSTATUS":
            content = image.getAclStatus(path);
            break;
        case "GETXATTRS":
            List<String> names = getXattrNames(decoder);
            String encoder = getEncoder(decoder);
            content = image.getXAttrs(path, names, encoder);
            break;
        case "LISTXATTRS":
            content = image.listXAttrs(path);
            break;
        case "GETCONTENTSUMMARY":
            content = image.getContentSummary(path);
            break;
        default:
            throw new IllegalArgumentException("Invalid value for webhdfs parameter" + " \"op\"");
    }
    LOG.info("op=" + op + " target=" + path);
    DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(content.getBytes(Charsets.UTF_8)));
    resp.headers().set(CONTENT_TYPE, APPLICATION_JSON_UTF8);
    resp.headers().set(CONTENT_LENGTH, resp.content().readableBytes());
    resp.headers().set(CONNECTION, CLOSE);
    ctx.write(resp).addListener(ChannelFutureListener.CLOSE);
}
Also used : QueryStringDecoder(io.netty.handler.codec.http.QueryStringDecoder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse)

Example 65 with DefaultFullHttpResponse

use of io.netty.handler.codec.http.DefaultFullHttpResponse 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();
    }
    Object body = message.getBody();
    Exception cause = message.getExchange().getException();
    // support bodies as native Netty
    ByteBuf buffer;
    // 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);
    LOG.trace("HTTP Status Code: {}", code);
    // 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 = NettyConverter.toByteBuffer(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 = NettyConverter.toByteBuffer(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 ByteBuf) {
        buffer = (ByteBuf) body;
    } else {
        // try to convert to buffer first
        buffer = message.getBody(ByteBuf.class);
        if (buffer == null) {
            // fallback to byte array as last resort
            byte[] data = message.getBody(byte[].class);
            if (data != null) {
                buffer = NettyConverter.toByteBuffer(data);
            } else {
                // and if byte array fails then try String
                String str;
                if (body != null) {
                    str = message.getMandatoryBody(String.class);
                } else {
                    str = "";
                }
                buffer = NettyConverter.toByteBuffer(str.getBytes());
            }
        }
    }
    HttpResponse response = null;
    if (buffer != null) {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(code), 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(HttpHeaderNames.CONTENT_LENGTH.toString(), len);
        LOG.trace("Content-Length: {}", len);
    } else {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(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);
            }
        }
    }
    // set the content type in the response.
    String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        response.headers().set(HttpHeaderNames.CONTENT_TYPE.toString(), 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(HttpHeaderNames.CONNECTION.toString(), String.class);
    // Read the connection header from the exchange property
    if (connection == null) {
        connection = message.getExchange().getProperty(HttpHeaderNames.CONNECTION.toString(), String.class);
    }
    if (connection == null) {
        // fallback and use the keep alive from the configuration
        if (configuration.isKeepAlive()) {
            connection = HttpHeaderValues.KEEP_ALIVE.toString();
        } else {
            connection = HttpHeaderValues.CLOSE.toString();
        }
    }
    response.headers().set(HttpHeaderNames.CONNECTION.toString(), connection);
    // Just make sure we close the channel when the connection value is close
    if (connection.equalsIgnoreCase(HttpHeaderValues.CLOSE.toString())) {
        message.setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true);
    }
    LOG.trace("Connection: {}", connection);
    return response;
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuf(io.netty.buffer.ByteBuf) ObjectOutputStream(java.io.ObjectOutputStream) NoTypeConversionAvailableException(org.apache.camel.NoTypeConversionAvailableException) RuntimeCamelException(org.apache.camel.RuntimeCamelException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TypeConverter(org.apache.camel.TypeConverter) StringWriter(java.io.StringWriter) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Aggregations

DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)72 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)44 ByteBuf (io.netty.buffer.ByteBuf)27 HttpResponse (io.netty.handler.codec.http.HttpResponse)10 HttpResponseStatus (io.netty.handler.codec.http.HttpResponseStatus)8 Test (org.junit.Test)7 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)6 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)5 HttpHeaders (io.netty.handler.codec.http.HttpHeaders)5 HttpRequest (io.netty.handler.codec.http.HttpRequest)5 ChannelFuture (io.netty.channel.ChannelFuture)4 IOException (java.io.IOException)4 Map (java.util.Map)4 HttpContent (io.netty.handler.codec.http.HttpContent)3 LastHttpContent (io.netty.handler.codec.http.LastHttpContent)3 File (java.io.File)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)2 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)2 FullHttpMessage (io.netty.handler.codec.http.FullHttpMessage)2