Example usage for io.netty.handler.codec.http2 Http2Stream setProperty

List of usage examples for io.netty.handler.codec.http2 Http2Stream setProperty

Introduction

In this page you can find the example usage for io.netty.handler.codec.http2 Http2Stream setProperty.

Prototype

<V> V setProperty(Http2Connection.PropertyKey key, V value);

Source Link

Document

Associates the application-defined data with this stream.

Usage

From source file:com.turo.pushy.apns.AbstractMockApnsServerHandler.java

License:Open Source License

@Override
public void onHeadersRead(final ChannelHandlerContext context, final int streamId, final Http2Headers headers,
        final int padding, final boolean endOfStream) throws Http2Exception {
    if (this.emulateInternalErrors) {
        context.channel().writeAndFlush(new InternalServerErrorResponse(streamId));
    } else {/*  ww w.j  av a 2  s.com*/
        final Http2Stream stream = this.connection().stream(streamId);

        UUID apnsId = null;

        try {
            {
                final CharSequence apnsIdSequence = headers.get(APNS_ID_HEADER);

                if (apnsIdSequence != null) {
                    try {
                        apnsId = UUID.fromString(apnsIdSequence.toString());
                    } catch (final IllegalArgumentException e) {
                        throw new RejectedNotificationException(ErrorReason.BAD_MESSAGE_ID);
                    }
                } else {
                    // If the client didn't send us a UUID, make one up (for now)
                    apnsId = UUID.randomUUID();
                }
            }

            if (!HttpMethod.POST.asciiName()
                    .contentEquals(headers.get(Http2Headers.PseudoHeaderName.METHOD.value()))) {
                throw new RejectedNotificationException(ErrorReason.METHOD_NOT_ALLOWED);
            }

            if (endOfStream) {
                throw new RejectedNotificationException(ErrorReason.PAYLOAD_EMPTY);
            }

            this.verifyHeaders(headers);

            // At this point, we've made it through all of the headers without an exception and know we're waiting
            // for a data frame. The data frame handler will want the APNs ID in case it needs to send an error
            // response.
            stream.setProperty(this.apnsIdPropertyKey, apnsId);
        } catch (final RejectedNotificationException e) {
            context.channel().writeAndFlush(new RejectNotificationResponse(streamId, apnsId, e.getErrorReason(),
                    e.getDeviceTokenExpirationTimestamp()));
        }
    }
}

From source file:com.turo.pushy.apns.ApnsClientHandler.java

License:Open Source License

@Override
public void onHeadersRead(final ChannelHandlerContext context, final int streamId, final Http2Headers headers,
        final int padding, final boolean endOfStream) {
    log.trace("Received headers from APNs gateway on stream {}: {}", streamId, headers);
    final Http2Stream stream = this.connection().stream(streamId);

    if (endOfStream) {
        this.handleEndOfStream(context, stream, headers, null);
    } else {//  w w  w  . java 2  s.c  om
        stream.setProperty(this.responseHeadersPropertyKey, headers);
    }
}

From source file:com.turo.pushy.apns.ApnsClientHandler.java

License:Open Source License

@Override
public void onStreamAdded(final Http2Stream stream) {
    stream.setProperty(ApnsClientHandler.this.responsePromisePropertyKey,
            this.unattachedResponsePromisesByStreamId.remove(stream.id()));
}

From source file:com.turo.pushy.apns.ApnsClientHandler.java

License:Open Source License

@Override
protected void onStreamError(final ChannelHandlerContext context, final boolean isOutbound,
        final Throwable cause, final Http2Exception.StreamException streamException) {
    final Http2Stream stream = this.connection().stream(streamException.streamId());
    stream.setProperty(this.streamErrorCausePropertyKey, streamException);

    super.onStreamError(context, isOutbound, cause, streamException);
}

From source file:com.turo.pushy.apns.server.MockApnsServerHandler.java

License:Open Source License

@Override
public int onDataRead(final ChannelHandlerContext context, final int streamId, final ByteBuf data,
        final int padding, final boolean endOfStream) {
    final int bytesProcessed = data.readableBytes() + padding;

    final Http2Stream stream = this.connection().stream(streamId);

    if (stream.getProperty(this.payloadPropertyKey) == null) {
        stream.setProperty(this.payloadPropertyKey, data.alloc().heapBuffer(MAX_CONTENT_LENGTH));
    }/*from  w ww. ja v  a  2  s . co  m*/

    ((ByteBuf) stream.getProperty(this.payloadPropertyKey)).writeBytes(data);

    if (endOfStream) {
        this.handleEndOfStream(context, stream);
    }

    return bytesProcessed;
}

From source file:com.turo.pushy.apns.server.MockApnsServerHandler.java

License:Open Source License

@Override
public void onHeadersRead(final ChannelHandlerContext context, final int streamId, final Http2Headers headers,
        final int padding, final boolean endOfStream) {
    final Http2Stream stream = this.connection().stream(streamId);
    stream.setProperty(this.headersPropertyKey, headers);

    if (endOfStream) {
        this.handleEndOfStream(context, stream);
    }// w ww .ja va  2  s .co m
}

From source file:io.gatling.http.client.impl.Http2AppHandler.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    HttpTx tx = (HttpTx) msg;//from   w  w  w . ja v  a2 s .  c  o  m
    nextStreamId += 2;

    if (tx.requestTimeout.isDone()) {
        channelPool.offer(ctx.channel());
        return;
    }

    try {
        WritableRequest request = WritableRequestBuilder.buildRequest(tx.request, ctx.alloc(), config, true);
        tx.closeConnection = HttpUtils.isConnectionClose(request.getRequest().headers());
        LOGGER.debug("Write request {}", request);

        request.write(ctx).addListener(f -> {
            if (f.isSuccess()) {
                Http2Stream stream = connection.stream(nextStreamId);
                stream.setProperty(propertyKey, tx);
            } else {
                crash(ctx, f.cause(), tx.listener, true);
            }
        });
    } catch (Exception e) {
        crash(ctx, e, tx.listener, true);
    }
}

From source file:io.grpc.netty.NettyClientHandler.java

License:Apache License

private void createStreamTraced(final int streamId, final NettyClientStream.TransportState stream,
        final Http2Headers headers, boolean isGet, final boolean shouldBeCountedForInUse,
        final ChannelPromise promise) {
    // Create an intermediate promise so that we can intercept the failure reported back to the
    // application.
    ChannelPromise tempPromise = ctx().newPromise();
    encoder().writeHeaders(ctx(), streamId, headers, 0, isGet, tempPromise)
            .addListener(new ChannelFutureListener() {
                @Override//  w  ww .  j a  va2s .  co m
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        // The http2Stream will be null in case a stream buffered in the encoder
                        // was canceled via RST_STREAM.
                        Http2Stream http2Stream = connection().stream(streamId);
                        if (http2Stream != null) {
                            stream.getStatsTraceContext().clientOutboundHeaders();
                            http2Stream.setProperty(streamKey, stream);

                            // This delays the in-use state until the I/O completes, which technically may
                            // be later than we would like.
                            if (shouldBeCountedForInUse) {
                                inUseState.updateObjectInUse(http2Stream, true);
                            }

                            // Attach the client stream to the HTTP/2 stream object as user data.
                            stream.setHttp2Stream(http2Stream);
                        }
                        // Otherwise, the stream has been cancelled and Netty is sending a
                        // RST_STREAM frame which causes it to purge pending writes from the
                        // flow-controller and delete the http2Stream. The stream listener has already
                        // been notified of cancellation so there is nothing to do.

                        // Just forward on the success status to the original promise.
                        promise.setSuccess();
                    } else {
                        final Throwable cause = future.cause();
                        if (cause instanceof StreamBufferingEncoder.Http2GoAwayException) {
                            StreamBufferingEncoder.Http2GoAwayException e = (StreamBufferingEncoder.Http2GoAwayException) cause;
                            lifecycleManager.notifyShutdown(statusFromGoAway(e.errorCode(), e.debugData()));
                            promise.setFailure(lifecycleManager.getShutdownThrowable());
                        } else {
                            promise.setFailure(cause);
                        }
                    }
                }
            });
}

From source file:io.grpc.netty.NettyServerHandler.java

License:Apache License

private void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers)
        throws Http2Exception {
    if (!teWarningLogged && !TE_TRAILERS.contentEquals(headers.get(TE_HEADER))) {
        logger.warning(String.format(
                "Expected header TE: %s, but %s is received. This means "
                        + "some intermediate proxy may not support trailers",
                TE_TRAILERS, headers.get(TE_HEADER)));
        teWarningLogged = true;/*from w w  w .ja  va  2 s .  co m*/
    }

    try {

        // Remove the leading slash of the path and get the fully qualified method name
        CharSequence path = headers.path();

        if (path == null) {
            respondWithHttpError(ctx, streamId, 404, Status.Code.UNIMPLEMENTED, "Expected path but is missing");
            return;
        }

        if (path.charAt(0) != '/') {
            respondWithHttpError(ctx, streamId, 404, Status.Code.UNIMPLEMENTED,
                    String.format("Expected path to start with /: %s", path));
            return;
        }

        String method = path.subSequence(1, path.length()).toString();

        // Verify that the Content-Type is correct in the request.
        CharSequence contentType = headers.get(CONTENT_TYPE_HEADER);
        if (contentType == null) {
            respondWithHttpError(ctx, streamId, 415, Status.Code.INTERNAL,
                    "Content-Type is missing from the request");
            return;
        }
        String contentTypeString = contentType.toString();
        if (!GrpcUtil.isGrpcContentType(contentTypeString)) {
            respondWithHttpError(ctx, streamId, 415, Status.Code.INTERNAL,
                    String.format("Content-Type '%s' is not supported", contentTypeString));
            return;
        }

        if (!HTTP_METHOD.contentEquals(headers.method())) {
            respondWithHttpError(ctx, streamId, 405, Status.Code.INTERNAL,
                    String.format("Method '%s' is not supported", headers.method()));
            return;
        }

        // The Http2Stream object was put by AbstractHttp2ConnectionHandler before calling this
        // method.
        Http2Stream http2Stream = requireHttp2Stream(streamId);

        Metadata metadata = Utils.convertHeaders(headers);
        StatsTraceContext statsTraceCtx = StatsTraceContext.newServerContext(streamTracerFactories, method,
                metadata);

        NettyServerStream.TransportState state = new NettyServerStream.TransportState(this,
                ctx.channel().eventLoop(), http2Stream, maxMessageSize, statsTraceCtx, transportTracer, method);

        PerfMark.startTask("NettyServerHandler.onHeadersRead", state.tag());
        try {
            String authority = getOrUpdateAuthority((AsciiString) headers.authority());
            NettyServerStream stream = new NettyServerStream(ctx.channel(), state, attributes, authority,
                    statsTraceCtx, transportTracer);
            transportListener.streamCreated(stream, method, metadata);
            state.onStreamAllocated();
            http2Stream.setProperty(streamKey, state);
        } finally {
            PerfMark.stopTask("NettyServerHandler.onHeadersRead", state.tag());
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Exception in onHeadersRead()", e);
        // Throw an exception that will get handled by onStreamError.
        throw newStreamException(streamId, e);
    }
}

From source file:org.jboss.aerogear.webpush.netty.WebPushFrameListener.java

License:Apache License

@Override
public void onHeadersRead(final ChannelHandlerContext ctx, final int streamId, final Http2Headers headers,
        final int streamDependency, final short weight, final boolean exclusive, final int padding,
        final boolean endStream) throws Http2Exception {
    final String path = headers.path().toString();
    final String method = headers.method().toString();
    LOGGER.info("onHeadersRead. streamId={}, method={}, path={}, endstream={}", streamId, method, path,
            endStream);/*from ww  w.  j  ava 2s  .  c  om*/

    final Resource resource = getResource(path);
    final Http2Stream stream = encoder.connection().stream(streamId);
    stream.setProperty(pathPropertyKey, path);
    stream.setProperty(resourcePropertyKey, resource);
    switch (method) {
    case GET:
        switch (resource) {
        case SUBSCRIPTION:
            handleReceivingPushMessages(ctx, streamId, headers, path);
            return;
        case RECEIPT:
            handleReceivingPushMessageReceipts(ctx, streamId, path);
            return;
        }
        break;
    case POST:
        switch (resource) {
        case SUBSCRIBE:
            handleSubscribe(ctx, streamId);
            return;
        case RECEIPTS:
            handleReceipts(ctx, streamId, path);
            return;
        case PUSH:
            final Optional<String> pushReceiptToken = getPushReceiptToken(headers);
            stream.setProperty(pushReceiptPropertyKey, pushReceiptToken);
            final Optional<Integer> ttl = getTtl(headers);
            stream.setProperty(ttlPropertyKey, ttl);
            //see onDataRead(...) method
            return;
        }
        break;
    case DELETE:
        switch (resource) {
        case PUSH_MESSAGE:
            handleAcknowledgement(ctx, streamId, path);
            return;
        case SUBSCRIPTION:
            handlePushMessageSubscriptionRemoval(ctx, streamId, path);
            return;
        case RECEIPT:
            handleReceiptSubscriptionRemoval(ctx, streamId, path);
            return;
        }
        break;
    }
}