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:malcolm.HttpProxyBackendHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // TODO what does this to?
    ctx.read();
    ctx.write(Unpooled.EMPTY_BUFFER);
}

From source file:malcolm.HttpProxyBackendHandler.java

License:Apache License

private static void closeOnFlush(final Channel ch) {
    if (ch.isActive()) {
        ch.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }/*from   w w w . ja va  2  s .c o  m*/
}

From source file:me.bigteddy98.mcproxy.protocol.handlers.ServerSideHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    networkManager.serversidePipeline = ctx.pipeline();
    ctx.read();//from  w w w.  ja  v a  2  s.  com
    ctx.write(Unpooled.EMPTY_BUFFER);
}

From source file:me.bigteddy98.movingmotd.ServerSideConnection.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ctx.read();/*from w  w  w.  j a v a 2  s .  c o m*/
    ctx.write(Unpooled.EMPTY_BUFFER);
    this.networkManager.serversidePipeline = ctx.pipeline();
}

From source file:me.ferrybig.javacoding.webmapper.netty.WebServerHandler.java

private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req)
        throws UnsupportedEncodingException {
    // Handle a bad request.
    if (!req.decoderResult().isSuccess()) {
        sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
        return;//from ww w  .  j a  v a 2s  .c  o m
    }

    if (WEBSOCKET_PATH.equals(req.uri())) {
        // Handshake
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(null, null, true);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
            ctx.channel().pipeline().remove("readtimeout");
            this.websocketTmp = new SimpleWebServerRequest(WEBSOCKET_PATH, ctx.channel(),
                    new LazySessionSupplier(sessions::createNewSession), server, listener);
        }
    } else {
        if (req.method() == OPTIONS) {
            FullHttpResponse res1 = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT, Unpooled.EMPTY_BUFFER);
            res1.headers().set("Access-Control-Allow-Headers", "Content-Type");
            res1.headers().set("Access-Control-Allow-Methods", "POST,GET");
            res1.headers().set("Access-Control-Allow-Origin", "*");
            res1.headers().set("Access-Control-Allow-Max-Age", "600");
            sendHttpResponse(ctx, req, res1);
        } else if (req.method() == POST || req.method() == GET || req.method() == HEAD) {
            String url = req.uri();
            if (url.startsWith("/")) {
                url = url.substring(1);
            }
            String host = req.headers().get(HOST);
            if (host.indexOf(':') > -1) {
                host = host.substring(0, host.indexOf(':'));
            }
            String cookie = req.headers().get(HttpHeaderNames.COOKIE, "");
            Optional<String> sessionId = Optional.empty();
            for (String cookiePart : cookie.split(";")) {
                cookiePart = cookiePart.trim();
                String[] split = cookiePart.split("=");
                if (split.length != 2) {
                    continue;
                }
                if (split[0].trim().equals("SESSION")) {
                    sessionId = Optional.of(split[1].trim());
                    break;
                }
            }
            final Optional<String> sessionId0 = sessionId;
            final SessionSupplier t;
            WebServerRequest request = new SimpleWebServerRequest(url, ctx.channel(),
                    t = new LazySessionSupplier(() -> sessions.findOrCreateSession(sessionId0)), server,
                    listener, decodeRequest(Optional.ofNullable(req.headers().get(CONTENT_TYPE)), req.content())
                            .map(Collections::singletonList).orElseGet(Collections::emptyList));

            EndpointResult<?> res;
            try {
                res = this.httpMapper.handleHttpRequest(request);
            } catch (RouteException ex) {
                res = new EndpointResult<>(Result.SERVER_ERROR, "Server error!", ContentType.TEXT);
                Logger.getLogger(WebServerHandler.class.getName()).log(Level.SEVERE, null, ex);
            }

            ByteBuf content = Unpooled.wrappedBuffer(res.asBytes(DEFAULT_CHARSET));
            HttpResponseStatus status;
            switch (res.getResult()) {
            case AUTH_REQUIRED:
                status = FORBIDDEN;
                break;
            case CONFLICT:
                status = CONFLICT;
                break;
            case NO_PERMISSIONS:
                status = FORBIDDEN;
                break;
            case OK:
                status = OK;
                break;
            case SYNTAX_ERROR:
                status = BAD_REQUEST;
                break;
            case UNKNOWN_ENDPOINT:
                status = NOT_FOUND;
                break;
            case SERVER_ERROR:
            default:
                status = INTERNAL_SERVER_ERROR;
                break;
            }

            FullHttpResponse res1 = new DefaultFullHttpResponse(HTTP_1_1, status, content);
            if (t.hasTouchedSession())
                res1.headers().add(SET_COOKIE, "SESSION=" + encode(t.session().getKey(), "UTF-8") + "; "
                        + "domain=" + encode(host, "UTF-8") + "; " + "HttpOnly");
            if (res.getContentType() == EndpointResult.ContentType.HTML) {
                res1.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
            } else if (res.getContentType() == EndpointResult.ContentType.TEXT) {
                res1.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
            } else if (res.getContentType() == EndpointResult.ContentType.JSON) {
                res1.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8");
            } else if (res.getContentType() == EndpointResult.ContentType.CSS) {
                res1.headers().set(CONTENT_TYPE, "text/css; charset=UTF-8");
            } else if (res.getContentType() == EndpointResult.ContentType.JAVASCRIPT) {
                res1.headers().set(CONTENT_TYPE, "text/javascript; charset=UTF-8");
            } else if (res.getContentType() == EndpointResult.ContentType.PNG) {
                res1.headers().set(CONTENT_TYPE, "image/png");
            } else if (res.getContentType() == EndpointResult.ContentType.JPEG) {
                res1.headers().set(CONTENT_TYPE, "image/jpeg");
            } else {

            }
            res1.headers().set("Access-Control-Allow-Headers", "Content-Type");
            res1.headers().set("Access-Control-Allow-Methods", "POST,GET");
            res1.headers().set("Access-Control-Allow-Origin", "*");
            res1.headers().set("Keep-Alive", "timeout=15, max=100");
            res1.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());

            sendHttpResponse(ctx, req, res1);
        } else {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, NOT_ACCEPTABLE));
        }

    }

}

From source file:net.tomp2p.storage.AlternativeCompositeByteBuf.java

License:Apache License

@Override
public ByteBuf readBytes(int length) {
    checkReadableBytes(length);//from ww  w  .j a  v  a2  s. c  o  m
    if (length == 0) {
        return Unpooled.EMPTY_BUFFER;
    }

    // Use an unpooled heap buffer because there's no way to mandate a user
    // to free the returned buffer.
    ByteBuf buf = Unpooled.buffer(length, maxCapacity());
    buf.writeBytes(this, readerIndex, length);
    readerIndex += length;
    return buf;
}

From source file:net.tomp2p.storage.AlternativeCompositeByteBuf.java

License:Apache License

@Override
public ByteBuf slice(int index, int length) {
    if (length == 0) {
        return Unpooled.EMPTY_BUFFER;
    }//from  www .j a  v  a2  s  . co m

    return new SlicedByteBuf(this, index, length);
}

From source file:nikoladasm.aspark.server.ServerHandler.java

License:Open Source License

private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    WebSocketContextImpl wctx = ctx.channel().attr(WEBSOCKET_CONTEXT_ATTR_KEY).get();
    WebSocketHandler wsHandler = ctx.channel().attr(WEBSOCKET_HANDLER_ATTR_KEY).get();
    if (frame instanceof CloseWebSocketFrame) {
        WebSocketServerHandshaker handshaker = ctx.channel().attr(HANDSHAKER_ATTR_KEY).get();
        if (handshaker != null) {
            frame.retain();/* ww  w. ja  v  a 2 s.  com*/
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame);
            if (wsHandler != null) {
                ctx.channel().attr(WEBSOCKET_HANDLER_ATTR_KEY).remove();
                ctx.channel().attr(WEBSOCKET_CONTEXT_ATTR_KEY).remove();
                String reason = ((CloseWebSocketFrame) frame).reasonText();
                int statusCode = ((CloseWebSocketFrame) frame).statusCode();
                wsHandler.onClose(wctx, statusCode, reason);
            }
        } else {
            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
        return;
    }
    if (wsHandler == null)
        return;
    if (frame instanceof PingWebSocketFrame) {
        frame.content().retain();
        ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content()));
        return;
    }
    if (frame instanceof PongWebSocketFrame) {
        return;
    }
    if (frame instanceof TextWebSocketFrame) {
        wctx.textFrameBegin(true);
        String request = ((TextWebSocketFrame) frame).text();
        if (frame.isFinalFragment()) {
            wsHandler.onMessage(wctx, request);
        } else {
            wctx.stringBuilder().append(request);
        }
        return;
    }
    if (frame instanceof BinaryWebSocketFrame) {
        wctx.textFrameBegin(false);
        byte[] request = new byte[((BinaryWebSocketFrame) frame).content().readableBytes()];
        ((BinaryWebSocketFrame) frame).content().readBytes(request);
        if (frame.isFinalFragment()) {
            wsHandler.onMessage(wctx, request);
        } else {
            wctx.frameBuffer().writeBytes(request);
        }
        return;
    }
    if (frame instanceof ContinuationWebSocketFrame) {
        if (wctx.textFrameBegin()) {
            String request = ((ContinuationWebSocketFrame) frame).text();
            wctx.stringBuilder().append(request);
            if (frame.isFinalFragment()) {
                wsHandler.onMessage(wctx, wctx.stringBuilder().toString());
                wctx.stringBuilder(new StringBuilder());
            }
        } else {
            byte[] request = new byte[((BinaryWebSocketFrame) frame).content().readableBytes()];
            ((BinaryWebSocketFrame) frame).content().readBytes(request);
            wctx.frameBuffer().writeBytes(request);
            if (frame.isFinalFragment()) {
                request = new byte[wctx.frameBuffer().readableBytes()];
                wctx.frameBuffer().readBytes(request);
                wsHandler.onMessage(wctx, request);
                wctx.frameBuffer().clear();
            }
        }
        return;
    }
}

From source file:openbns.commons.net.codec.sts.HttpObjectDecoder.java

License:Apache License

private StsContent invalidChunk(Exception cause) {
    checkpoint(State.BAD_MESSAGE);
    StsContent chunk = new DefaultStsContent(Unpooled.EMPTY_BUFFER);
    chunk.setDecoderResult(DecoderResult.failure(cause));
    return chunk;
}

From source file:openbns.commons.net.codec.sts.HttpObjectDecoder.java

License:Apache License

private LastStsContent readTrailingHeaders(ByteBuf buffer) {
    headerSize = 0;/*from  w  w  w  . j a  va  2 s .c o m*/
    AppendableCharSequence line = readHeader(buffer);
    String lastHeader = null;
    if (line.length() > 0) {
        LastStsContent trailer = new DefaultLastStsContent(Unpooled.EMPTY_BUFFER, validateHeaders);
        do {
            char firstChar = line.charAt(0);
            if (lastHeader != null && (firstChar == ' ' || firstChar == '\t')) {
                List<String> current = trailer.trailingHeaders().getAll(lastHeader);
                if (!current.isEmpty()) {
                    int lastPos = current.size() - 1;
                    String newString = current.get(lastPos) + line.toString().trim();
                    current.set(lastPos, newString);
                } else {
                    // Content-Length, Transfer-Encoding, or Trailer
                }
            } else {
                String[] header = splitHeader(line);
                String name = header[0];
                if (!StsHeaders.equalsIgnoreCase(name, StsHeaders.Names.CONTENT_LENGTH)) {
                    trailer.trailingHeaders().add(name, header[1]);
                }
                lastHeader = name;
            }

            line = readHeader(buffer);
        } while (line.length() > 0);

        return trailer;
    }

    return LastStsContent.EMPTY_LAST_CONTENT;
}