Example usage for io.netty.buffer ByteBufInputStream ByteBufInputStream

List of usage examples for io.netty.buffer ByteBufInputStream ByteBufInputStream

Introduction

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

Prototype

public ByteBufInputStream(ByteBuf buffer) 

Source Link

Document

Creates a new stream which reads data from the specified buffer starting at the current readerIndex and ending at the current writerIndex .

Usage

From source file:org.atmosphere.nettosphere.BridgeRuntime.java

License:Apache License

private void handleHttp(final ChannelHandlerContext ctx, final Object messageEvent)
        throws URISyntaxException, IOException {

    boolean skipClose = false;
    AtmosphereResponse response = null;/*from   w w  w  . ja  v  a2 s.c o  m*/
    AtmosphereRequest request = null;
    Action a = null;
    boolean resumeOnBroadcast = false;
    boolean keptOpen = false;
    ChannelWriter asyncWriter = null;
    String method = "GET";
    boolean writeHeader = false;
    boolean forceSuspend = false;
    boolean aggregateBodyInMemory = config.aggregateRequestBodyInMemory();

    try {
        if (messageEvent instanceof HttpRequest) {
            final HttpRequest hrequest = (HttpRequest) messageEvent;

            byte[] body = EMPTY;
            if (FullHttpRequest.class.isAssignableFrom(messageEvent.getClass())) {
                ByteBuf b = FullHttpRequest.class.cast(messageEvent).content();
                if (b.isReadable()) {
                    body = new byte[b.readableBytes()];
                    b.readBytes(body);
                }
            }

            // First let's try to see if it's a static resources
            if (!hrequest.getUri().contains(HeaderConfig.X_ATMOSPHERE)) {
                try {
                    hrequest.headers().add(STATIC_MAPPING, "true");
                    super.channelRead(ctx, messageEvent);

                    if (HttpHeaders.getHeader(hrequest, SERVICED) != null) {
                        return;
                    }
                } catch (Exception e) {
                    logger.debug("Unexpected State", e);
                } finally {
                    hrequest.headers().set(STATIC_MAPPING, "false");
                }
            }

            boolean ka = HttpHeaders.isKeepAlive(hrequest);
            asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), true, ka)
                    : new StreamWriter(ctx.channel(), true, ka);

            method = hrequest.getMethod().name();

            request = createAtmosphereRequest(ctx, hrequest, body);
            request.setAttribute(KEEP_ALIVE, new Boolean(ka));

            // Hacky. Is the POST doesn't contains a body, we must not close the connection yet.
            AtmosphereRequestImpl.Body b = request.body();
            if (!aggregateBodyInMemory && !hrequest.getMethod().equals(GET) && !b.isEmpty()
                    && (b.hasString() && b.asString().isEmpty()) || (b.hasBytes() && b.asBytes().length == 0)) {
                forceSuspend = true;
            }
        } else {
            request = State.class.cast(ctx.attr(ATTACHMENT).get()).request;
            boolean isLast = HttpChunkedInput.class.cast(messageEvent).isEndOfInput();
            Boolean ka = (Boolean) request.getAttribute(KEEP_ALIVE);

            asyncWriter = config.supportChunking() ? new ChunkedWriter(ctx.channel(), isLast, ka)
                    : new StreamWriter(ctx.channel(), isLast, ka);
            method = request.getMethod();
            ByteBuf internalBuffer = HttpChunkedInput.class.cast(messageEvent).readChunk(ctx).content();

            if (!aggregateBodyInMemory && internalBuffer.hasArray()) {
                request.body(internalBuffer.array());
            } else {
                logger.trace("Unable to read in memory the request's bytes. Using stream");
                request.body(new ByteBufInputStream(internalBuffer));
            }

            if (!isLast) {
                forceSuspend = true;
            }
        }

        response = new AtmosphereResponseImpl.Builder().asyncIOWriter(asyncWriter).writeHeader(writeHeader)
                .destroyable(false).header("Connection", "Keep-Alive").header("Server", "Nettosphere/3.0")
                .request(request).build();

        if (config.supportChunking()) {
            response.setHeader("Transfer-Encoding", "chunked");
        }

        a = framework.doCometSupport(request, response);
        if (forceSuspend) {
            a.type(Action.TYPE.SUSPEND);
            // leave the stream open
            keptOpen = true;
        }

        String transport = (String) request.getAttribute(FrameworkConfig.TRANSPORT_IN_USE);
        if (transport == null) {
            transport = request.getHeader(X_ATMOSPHERE_TRANSPORT);
        }

        if (a.type() == Action.TYPE.SUSPEND) {
            if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.STREAMING_TRANSPORT)
                    || transport.equalsIgnoreCase(SSE_TRANSPORT))) {
                keptOpen = true;
            } else if (transport != null && (transport.equalsIgnoreCase(HeaderConfig.LONG_POLLING_TRANSPORT)
                    || transport.equalsIgnoreCase(HeaderConfig.JSONP_TRANSPORT))) {
                resumeOnBroadcast = true;
            }
        }

        final Action action = (Action) request.getAttribute(NettyCometSupport.SUSPEND);
        final State state = new State(request, action == null ? Action.CONTINUE : action);

        ctx.attr(ATTACHMENT).set(state);

        if (action != null && action.type() == Action.TYPE.SUSPEND) {
            if (action.timeout() != -1) {
                final AtomicReference<ChannelWriter> w = new AtomicReference<ChannelWriter>(asyncWriter);
                final AtomicReference<Future<?>> f = new AtomicReference<Future<?>>();
                f.set(suspendTimer.scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                        if (!w.get().isClosed()
                                && (System.currentTimeMillis() - w.get().lastTick()) > action.timeout()) {
                            AtmosphereResourceImpl impl = state.resource();
                            if (impl != null) {
                                asynchronousProcessor.endRequest(impl, false);
                                f.get().cancel(true);
                            }
                        }
                    }
                }, action.timeout(), action.timeout(), TimeUnit.MILLISECONDS));
            }
        } else if (action != null && action.type() == Action.TYPE.RESUME) {
            resumeOnBroadcast = false;
        }
    } catch (AtmosphereMappingException ex) {
        if (method.equalsIgnoreCase("GET")) {
            logger.trace("Unable to map the request {}, trying static file", messageEvent);
        }
    } catch (Throwable e) {
        logger.error("Unable to process request", e);
        throw new IOException(e);
    } finally {
        try {
            if (asyncWriter != null && !resumeOnBroadcast && !keptOpen) {
                if (!skipClose && response != null) {
                    asyncWriter.close(response);
                } else {
                    httpChannels.add(ctx.channel());
                }
            }
        } finally {
            if (request != null && a != null && a.type() != Action.TYPE.SUSPEND) {
                request.destroy();
                response.destroy();
                framework.notify(Action.TYPE.DESTROYED, request, response);
            }
        }
    }
}

From source file:org.bridje.http.impl.HttpBridletRequestImpl.java

License:Apache License

@Override
public InputStream getInputStream() {
    if (inputStream == null) {
        if (buffer != null) {
            inputStream = new ByteBufInputStream(buffer);
        } else {//from  w w  w  .  j a v  a 2s .c o  m
            inputStream = new ByteArrayInputStream("".getBytes());
        }
    }
    return inputStream;
}

From source file:org.bridje.http.impl.UploadedFileImpl.java

License:Apache License

@Override
public InputStream getInputStream() throws IOException {
    return new ByteBufInputStream(fileUpload.getByteBuf());
}

From source file:org.deephacks.vertxrs.VertxHttpRequest.java

License:Apache License

public VertxHttpRequest(Buffer body, HttpServerRequest request, VertxHttpResponse response,
        SynchronousDispatcher dispatcher) {
    super(new ResteasyUriInfo(request.absoluteURI()));
    this.request = request;
    this.executionContext = new VertxExecutionContext(this, response, dispatcher);
    this.body = new ByteBufInputStream(body.getByteBuf());
}

From source file:org.gameoss.gridcast.p2p.serialization.ProtostuffDecoder.java

License:Apache License

/**
 * Expose deserializer for unit testing.
 *
 * @param registry// w ww.j  ava 2  s. co m
 * @param buf
 * @return
 * @throws IOException
 */
public static Object deserializeFromByteBuf(MessageRegistry registry, ByteBuf buf) throws IOException {
    // get message class
    int typeIdx = buf.readInt();
    Class<?> clazz = registry.getClassFromId(typeIdx);

    // decode rest of array into object
    Schema schema = RuntimeSchema.getSchema(clazz);
    Object obj = schema.newMessage();
    ProtostuffIOUtil.mergeFrom(new ByteBufInputStream(buf), obj, schema);

    return obj;
}

From source file:org.glassfish.jersey.netty.httpserver.JerseyHttp2ServerHandler.java

License:Open Source License

/**
 * Process incoming data./*from  www  . java 2  s  .c om*/
 */
private void onDataRead(ChannelHandlerContext ctx, Http2DataFrame data) throws Exception {
    isList.add(new ByteBufInputStream(data.content()));
    if (data.isEndStream()) {
        isList.add(NettyInputStream.END_OF_INPUT);
    }
}

From source file:org.glassfish.jersey.netty.httpserver.JerseyServerHandler.java

License:Open Source License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) {

    if (msg instanceof HttpRequest) {
        final HttpRequest req = (HttpRequest) msg;

        if (HttpUtil.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
        }/*from   ww  w  .  j  av a2 s. c  o m*/

        isList.clear(); // clearing the content - possible leftover from previous request processing.
        final ContainerRequest requestContext = createContainerRequest(ctx, req);

        requestContext.setWriter(new NettyResponseWriter(ctx, req, container));

        // must be like this, since there is a blocking read from Jersey
        container.getExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                container.getApplicationHandler().handle(requestContext);
            }
        });
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();

        if (content.isReadable()) {
            isList.add(new ByteBufInputStream(content));
        }

        if (msg instanceof LastHttpContent) {
            isList.add(NettyInputStream.END_OF_INPUT);
        }
    }
}

From source file:org.graylog2.gelfclient.encoder.GelfCompressionEncoderTest.java

License:Apache License

@Test
public void testEncode() throws Exception {
    final EmbeddedChannel channel = new EmbeddedChannel(new GelfCompressionEncoder());
    final String message = "Test string";

    assertTrue(channel.writeOutbound(Unpooled.wrappedBuffer(message.getBytes(StandardCharsets.UTF_8))));
    assertTrue(channel.finish());// w w w .  j a v a 2 s.  c  om

    final ByteBufInputStream byteBufInputStream = new ByteBufInputStream((ByteBuf) channel.readOutbound());
    final GZIPInputStream gzipInputStream = new GZIPInputStream(byteBufInputStream);

    byte[] bytes = new byte[message.length()];

    assertEquals(message.length(), gzipInputStream.read(bytes, 0, message.length()));
    assertEquals(message, new String(bytes, StandardCharsets.UTF_8));
}

From source file:org.jooby.internal.netty.NettyRequest.java

License:Apache License

@Override
public InputStream in() throws IOException {
    ByteBuf content = ((HttpContent) req).content();
    return new ByteBufInputStream(content);
}

From source file:org.lanternpowered.server.network.buffer.LanternByteBuffer.java

License:MIT License

@Nullable
@Override/*  ww  w.  j  ava 2 s . c o m*/
public DataView readLimitedDataView(int maximumDepth, int maxBytes) {
    final int index = this.buf.readerIndex();
    if (this.buf.readByte() == 0) {
        return null;
    }
    this.buf.readerIndex(index);
    try {
        try (NbtDataContainerInputStream input = new NbtDataContainerInputStream(
                new LimitInputStream(new ByteBufInputStream(this.buf), maxBytes), false, maximumDepth)) {
            return input.read();
        }
    } catch (IOException e) {
        throw new CodecException(e);
    }
}