Example usage for io.netty.buffer Unpooled EMPTY_BUFFER

List of usage examples for io.netty.buffer Unpooled EMPTY_BUFFER

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled EMPTY_BUFFER.

Prototype

ByteBuf EMPTY_BUFFER

To view the source code for io.netty.buffer Unpooled EMPTY_BUFFER.

Click Source Link

Document

A buffer whose capacity is 0 .

Usage

From source file:io.liveoak.common.codec.ResourceCodecManager.java

License:Open Source License

public ResourceState decode(MediaType mediaType, ByteBuf buf) throws Exception {
    if (buf == null) {
        buf = Unpooled.EMPTY_BUFFER;
    }// w w w. java2 s  .  c  o  m
    if (MediaType.OCTET_STREAM.equals(mediaType)) {
        return new DefaultBinaryResourceState(buf.retain());
    }

    ResourceCodec codec = getResourceCodec(mediaType);
    if (codec == null || !codec.hasDecoder()) {
        throw new UnsupportedMediaTypeException(MediaTypeMatcher.singleton(mediaType));
    }
    return codec.decode(buf);
}

From source file:io.liveoak.container.protocols.http.HttpResourceResponseEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, DefaultResourceResponse msg, List<Object> out)
        throws Exception {

    int responseStatusCode = 0;
    String responseMessage = null;
    HttpHeaders responseHeaders = new DefaultHttpHeaders();

    boolean shouldEncodeState = false;
    boolean shouldCheckForHtmlApp = true;
    switch (msg.responseType()) {
    case CREATED:
        responseStatusCode = HttpResponseStatus.CREATED.code();
        responseMessage = HttpResponseStatus.CREATED.reasonPhrase();
        shouldEncodeState = true;/*from   w  ww  .ja  v a 2  s  .c  om*/
        break;
    case READ:
        responseStatusCode = HttpResponseStatus.OK.code();
        responseMessage = HttpResponseStatus.OK.reasonPhrase();
        shouldEncodeState = true;
        break;
    case UPDATED:
        responseStatusCode = HttpResponseStatus.OK.code();
        responseMessage = HttpResponseStatus.OK.reasonPhrase();
        shouldEncodeState = true;
        break;
    case DELETED:
        responseStatusCode = HttpResponseStatus.OK.code();
        responseMessage = HttpResponseStatus.OK.reasonPhrase();
        shouldEncodeState = true;
        break;
    case ERROR:
        if (msg instanceof ResourceErrorResponse) {
            shouldEncodeState = true;
            shouldCheckForHtmlApp = false;
            switch (((DefaultResourceErrorResponse) msg).errorType()) {
            case NOT_AUTHORIZED:
                responseStatusCode = HttpResponseStatus.UNAUTHORIZED.code();
                responseMessage = HttpResponseStatus.UNAUTHORIZED.reasonPhrase();
                break;
            case FORBIDDEN:
                responseStatusCode = HttpResponseStatus.FORBIDDEN.code();
                responseMessage = HttpResponseStatus.FORBIDDEN.reasonPhrase();
                break;
            case NOT_ACCEPTABLE:
                responseStatusCode = HttpResponseStatus.NOT_ACCEPTABLE.code();
                responseMessage = HttpResponseStatus.NOT_ACCEPTABLE.reasonPhrase();
                break;
            case NO_SUCH_RESOURCE:
                responseStatusCode = HttpResponseStatus.NOT_FOUND.code();
                responseMessage = HttpResponseStatus.NOT_FOUND.reasonPhrase();
                break;
            case RESOURCE_ALREADY_EXISTS:
                responseStatusCode = HttpResponseStatus.NOT_ACCEPTABLE.code();
                responseMessage = HttpResponseStatus.NOT_ACCEPTABLE.reasonPhrase();
                break;
            case CREATE_NOT_SUPPORTED:
                responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code();
                responseMessage = "Create not supported";
                break;
            case READ_NOT_SUPPORTED:
                responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code();
                responseMessage = "Read not supported";
                break;
            case UPDATE_NOT_SUPPORTED:
                responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code();
                responseMessage = "UpdateStep not supported";
                break;
            case DELETE_NOT_SUPPORTED:
                responseStatusCode = HttpResponseStatus.METHOD_NOT_ALLOWED.code();
                responseMessage = "Delete not supported";
                break;
            case INTERNAL_ERROR:
                responseStatusCode = HttpResponseStatus.INTERNAL_SERVER_ERROR.code();
                responseMessage = HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase();
                break;
            }

            //TODO: add content values here to return proper error messages to the client
            // eg unique error id, short error message, link to page with more information, etc...
            //response.content().writeBytes(...)

        }
        break;
    case MOVED:
        if (msg instanceof ResourceMovedResponse) {
            ResourceMovedResponse resourceMovedResponse = (ResourceMovedResponse) msg;

            switch (resourceMovedResponse.movedType()) {
            case MOVED_PERMANENTLY:
                responseStatusCode = HttpResponseStatus.MOVED_PERMANENTLY.code();
                responseMessage = HttpResponseStatus.MOVED_PERMANENTLY.reasonPhrase();
                break;
            case MOVED_TEMPORARILY:
                responseStatusCode = HttpResponseStatus.FOUND.code();
                responseMessage = HttpResponseStatus.FOUND.reasonPhrase();
                break;
            }

            Integer maxAge = resourceMovedResponse.maxAge();
            if (maxAge != null) {
                responseHeaders.add(HttpHeaders.Names.CACHE_CONTROL, "max-age=" + maxAge);
            }

            responseHeaders.add(HttpHeaders.Names.LOCATION, ((ResourceMovedResponse) msg).redirectURL());
        }
        break;
    }

    DefaultHttpResponse response;
    HttpResponseStatus responseStatus;

    EncodingResult encodingResult = null;
    if (shouldEncodeState) {
        MediaTypeMatcher matcher = msg.inReplyTo().mediaTypeMatcher();

        if (shouldCheckForHtmlApp) {
            Application app = msg.inReplyTo().requestContext().application();
            if (app != null && app instanceof InternalApplication) {
                ResourcePath htmlAppPath = ((InternalApplication) app).htmlApplicationResourcePath();
                if ((!(msg.resource() instanceof BinaryResource)) && (htmlAppPath != null)) {
                    MediaType bestMatch = matcher.findBestMatch(this.codecManager.mediaTypes());
                    if (bestMatch == MediaType.HTML) {
                        // HTML was requested and we have an HTML app
                        ResourceRequest htmlAppRequest = new DefaultResourceRequest.Builder(RequestType.READ,
                                htmlAppPath).mediaTypeMatcher(msg.inReplyTo().mediaTypeMatcher())
                                        .requestAttributes(msg.inReplyTo().requestContext().requestAttributes())
                                        .build();
                        ctx.channel().pipeline().fireChannelRead(htmlAppRequest);
                        return;
                    }
                }
            }
        }

        try {
            encodingResult = encodeState(msg.inReplyTo().requestContext(), matcher, msg);
        } catch (IncompatibleMediaTypeException e) {
            log.error("Incompatible media type", e);
            responseStatus = new HttpResponseStatus(HttpResponseStatus.NOT_ACCEPTABLE.code(), e.getMessage());
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
            response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
            out.add(response);
            return;
        } catch (Throwable e) {
            log.error("Could not encode HTTP response", e);
            responseStatus = new HttpResponseStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(),
                    HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase());
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
            response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
            out.add(response);
            return;
        }
    }

    responseStatus = new HttpResponseStatus(responseStatusCode, responseMessage);

    if (encodingResult != null) {

        if (msg.resource() instanceof BinaryResource) {
            BinaryResource bin = (BinaryResource) msg.resource();
            if (bin.contentLength() == 0) {
                response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
                response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
            } else {
                response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
                response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, bin.contentLength());
                response.headers().add(HttpHeaders.Names.LOCATION, msg.resource().uri().toString());
                response.headers().add(HttpHeaders.Names.CONTENT_TYPE, bin.mediaType());

                final HttpResponse res = response;
                bin.readContent(msg.inReplyTo().requestContext(), new BinaryContentSink() {
                    {
                        ctx.write(res);
                    }

                    @Override
                    public void close() {
                        ctx.writeAndFlush(new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER));
                        ctx.pipeline().fireUserEventTriggered(new RequestCompleteEvent(msg.requestId()));
                    }

                    @Override
                    public void accept(ByteBuf byteBuf) {
                        ctx.write(new DefaultHttpContent(byteBuf));
                    }
                });
                return;
            }
        } else {
            ByteBuf content = encodingResult.encoded();

            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, content);
            response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
            if (msg.resource() != null) {
                response.headers().add(HttpHeaders.Names.LOCATION, msg.resource().uri().toString());
            } else {
                response.headers().add(HttpHeaders.Names.LOCATION, msg.inReplyTo().resourcePath().toString());
            }
            response.headers().add(HttpHeaders.Names.CONTENT_TYPE, encodingResult.mediaType());
        }
    } else {
        response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus);
        response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, 0);
    }

    response.headers().add(responseHeaders);

    out.add(response);
    ctx.fireUserEventTriggered(new RequestCompleteEvent(msg.requestId()));
}

From source file:io.liveoak.stomp.common.DefaultStompMessage.java

License:Open Source License

public DefaultStompMessage(Headers headers) {
    this(headers, Unpooled.EMPTY_BUFFER, false);
}

From source file:io.liveoak.stomp.common.DefaultStompMessage.java

License:Open Source License

public DefaultStompMessage(boolean error) {
    this(new HeadersImpl(), Unpooled.EMPTY_BUFFER, error);
}

From source file:io.liveoak.stomp.common.StompFrameDecoder.java

License:Open Source License

protected ByteBuf readUntilNull(ByteBuf buffer) {
    int nonNullBytes = buffer.bytesBefore((byte) 0x00);

    ByteBuf content = null;/*from w  w  w  .ja  v a 2s .  c  o m*/
    if (nonNullBytes == 0) {
        content = Unpooled.EMPTY_BUFFER;
    } else {
        content = buffer.readBytes(nonNullBytes);
    }

    buffer.readByte();
    return content;
}

From source file:io.moquette.interception.RxBusTest.java

License:Open Source License

@SuppressWarnings("CheckReturnValue")
@Test/*from w  ww  . j  a v  a2 s . c om*/
public void test() {
    AtomicBoolean testRun = new AtomicBoolean(false);

    RxBus bus = new RxBus();

    bus.getEvents().filter(msg -> msg instanceof InterceptPublishMessage).cast(InterceptPublishMessage.class)
            .subscribe(msg -> {
                assertThat(msg.getUsername()).isEqualTo("username");
                assertThat(msg.getTopic().toString()).isEqualTo("topic");
                testRun.set(true);
            });

    MqttPublishMessage msg = MqttMessageBuilders.publish().topicName("topic").qos(MqttQoS.AT_LEAST_ONCE)
            .payload(Unpooled.EMPTY_BUFFER).build();
    bus.publish(new InterceptPublishMessage(msg, "clientID", "username", new Topic("topic")));

    assertThat(testRun.get()).isTrue();
}

From source file:io.netty.example.http.cors.OkResponseHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) {
    final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
            Unpooled.EMPTY_BUFFER);
    response.headers().set("custom-response-header", "Some value");
    ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}

From source file:io.netty.example.http.file.HttpStaticFileServerHandler.java

License:Apache License

private void sendRedirect(ChannelHandlerContext ctx, String newUri) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND, Unpooled.EMPTY_BUFFER);
    response.headers().set(HttpHeaderNames.LOCATION, newUri);

    this.sendAndCleanupConnection(ctx, response);
}

From source file:io.netty.example.http.file.HttpStaticFileServerHandler.java

License:Apache License

/**
 * When file timestamp is the same as what the browser is sending up, send a "304 Not Modified"
 *
 * @param ctx//w ww.  j  av  a 2s  .  c  om
 *            Context
 */
private void sendNotModified(ChannelHandlerContext ctx) {
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED, Unpooled.EMPTY_BUFFER);
    setDateHeader(response);

    this.sendAndCleanupConnection(ctx, response);
}

From source file:io.netty.example.http.snoop.HttpSnoopClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*from  w ww  .ja va2 s . com*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath(),
                Unpooled.EMPTY_BUFFER);
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Set some example cookies.
        request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT
                .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}