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

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

Introduction

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

Prototype

<V> V getProperty(Http2Connection.PropertyKey key);

Source Link

Document

Returns application-defined data if any was associated with this stream.

Usage

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

License:Open Source License

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

    if (endOfStream) {
        final Http2Stream stream = this.connection().stream(streamId);

        // Presumably, we spotted an error earlier and sent a response immediately if the stream is closed on our
        // side.// ww w  . j  av a  2  s . co  m
        if (stream.state() == Http2Stream.State.OPEN) {
            final UUID apnsId = stream.getProperty(this.apnsIdPropertyKey);

            if (data.readableBytes() <= MAX_CONTENT_LENGTH) {
                context.channel().writeAndFlush(new AcceptNotificationResponse(streamId));
            } else {
                context.channel().writeAndFlush(
                        new RejectNotificationResponse(streamId, apnsId, ErrorReason.PAYLOAD_TOO_LARGE, null));
            }
        }
    }

    return bytesProcessed;
}

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

License:Open Source License

@Override
public int onDataRead(final ChannelHandlerContext context, final int streamId, final ByteBuf data,
        final int padding, final boolean endOfStream) {
    log.trace("Received data from APNs gateway on stream {}: {}", streamId,
            data.toString(StandardCharsets.UTF_8));

    final int bytesProcessed = data.readableBytes() + padding;

    if (endOfStream) {
        final Http2Stream stream = this.connection().stream(streamId);
        this.handleEndOfStream(context, this.connection().stream(streamId),
                (Http2Headers) stream.getProperty(this.responseHeadersPropertyKey), data);
    } else {//from   ww w. ja va2  s  .  c  o m
        log.error("Gateway sent a DATA frame that was not the end of a stream.");
    }

    return bytesProcessed;
}

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

License:Open Source License

private void handleEndOfStream(final ChannelHandlerContext context, final Http2Stream stream,
        final Http2Headers headers, final ByteBuf data) {

    final PushNotificationPromise<ApnsPushNotification, PushNotificationResponse<ApnsPushNotification>> responsePromise = stream
            .getProperty(this.responsePromisePropertyKey);

    final ApnsPushNotification pushNotification = responsePromise.getPushNotification();

    final HttpResponseStatus status = HttpResponseStatus.parseLine(headers.status());

    if (HttpResponseStatus.OK.equals(status)) {
        responsePromise.trySuccess(new SimplePushNotificationResponse<>(responsePromise.getPushNotification(),
                true, getApnsIdFromHeaders(headers), null, null));
    } else {/* ww  w  .j a va  2 s  .c o  m*/
        if (data != null) {
            final ErrorResponse errorResponse = GSON.fromJson(data.toString(StandardCharsets.UTF_8),
                    ErrorResponse.class);
            this.handleErrorResponse(context, stream.id(), headers, pushNotification, errorResponse);
        } else {
            log.warn("Gateway sent an end-of-stream HEADERS frame for an unsuccessful notification.");
        }
    }
}

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

License:Open Source License

@Override
public void onStreamClosed(final Http2Stream stream) {
    // Always try to fail promises associated with closed streams; most of the time, this should fail silently, but
    // in cases of unexpected closure, it will make sure that nothing gets left hanging.
    final Promise<PushNotificationResponse<ApnsPushNotification>> responsePromise = stream
            .getProperty(this.responsePromisePropertyKey);

    if (responsePromise != null) {
        final Throwable cause;

        if (stream.getProperty(this.streamErrorCausePropertyKey) != null) {
            cause = stream.getProperty(this.streamErrorCausePropertyKey);
        } else if (this.connectionErrorCause != null) {
            cause = this.connectionErrorCause;
        } else {//from   w w  w . j  av a2  s .c  om
            cause = STREAM_CLOSED_BEFORE_REPLY_EXCEPTION;
        }

        responsePromise.tryFailure(cause);
    }
}

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  w w.  j  a 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

private void handleEndOfStream(final ChannelHandlerContext context, final Http2Stream stream) {
    final Http2Headers headers = stream.getProperty(this.headersPropertyKey);
    final ByteBuf payload = stream.getProperty(this.payloadPropertyKey);
    final ChannelPromise writePromise = context.newPromise();

    final UUID apnsId;
    {//  ww  w  . j a v a2 s  .  c  o m
        final CharSequence apnsIdSequence = headers.get(APNS_ID_HEADER);

        UUID apnsIdFromHeaders;

        try {
            apnsIdFromHeaders = apnsIdSequence != null ? FastUUID.parseUUID(apnsIdSequence) : UUID.randomUUID();
        } catch (final IllegalArgumentException e) {
            log.error("Failed to parse `apns-id` header: {}", apnsIdSequence, e);
            apnsIdFromHeaders = UUID.randomUUID();
        }

        apnsId = apnsIdFromHeaders;
    }

    try {
        this.pushNotificationHandler.handlePushNotification(headers, payload);

        this.write(context, new AcceptNotificationResponse(stream.id(), apnsId), writePromise);
        this.listener.handlePushNotificationAccepted(headers, payload);
    } catch (final RejectedNotificationException e) {
        final Date deviceTokenExpirationTimestamp = e instanceof UnregisteredDeviceTokenException
                ? ((UnregisteredDeviceTokenException) e).getDeviceTokenExpirationTimestamp()
                : null;

        this.write(context, new RejectNotificationResponse(stream.id(), apnsId, e.getRejectionReason(),
                deviceTokenExpirationTimestamp), writePromise);
        this.listener.handlePushNotificationRejected(headers, payload, e.getRejectionReason(),
                deviceTokenExpirationTimestamp);
    } catch (final Exception e) {
        this.write(context, new RejectNotificationResponse(stream.id(), apnsId,
                RejectionReason.INTERNAL_SERVER_ERROR, null), writePromise);
        this.listener.handlePushNotificationRejected(headers, payload, RejectionReason.INTERNAL_SERVER_ERROR,
                null);
    } finally {
        if (stream.getProperty(this.payloadPropertyKey) != null) {
            ((ByteBuf) stream.getProperty(this.payloadPropertyKey)).release();
        }

        this.flush(context);
    }
}

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

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;
        Integer streamId = response.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
        Http2Stream stream = connection.stream(streamId);
        HttpTx tx = stream.getProperty(propertyKey);

        if (tx.requestTimeout.isDone()) {
            http2ConnectionHandler.resetStream(ctx, streamId, 8, ctx.newPromise());
            channelPool.offer(ctx.channel());
            return;
        }/*from  w  w  w.  java 2s  . c  o m*/

        tx.listener.onHttpResponse(response.status(), response.headers());

    } else if (msg instanceof Http2Content) {
        Http2Content content = (Http2Content) msg;
        int streamId = content.getStreamId();
        Http2Stream stream = connection.stream(streamId);
        HttpTx tx = stream.getProperty(propertyKey);

        if (tx.requestTimeout.isDone()) {
            http2ConnectionHandler.resetStream(ctx, streamId, 8, ctx.newPromise());
            channelPool.offer(ctx.channel());
            return;
        }

        HttpContent httpContent = content.getHttpContent();
        boolean last = httpContent instanceof LastHttpContent;
        tx.listener.onHttpResponseBodyChunk(httpContent.content(), last);
        if (last) {
            tx.requestTimeout.cancel();
            channelPool.offer(ctx.channel());
        }
    }
}

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

License:Apache License

/**
 * Gets the client stream associated to the given HTTP/2 stream object.
 *///  w ww  . j  ava 2  s  .  c o m
private NettyClientStream.TransportState clientStream(Http2Stream stream) {
    return stream == null ? null : (NettyClientStream.TransportState) stream.getProperty(streamKey);
}

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

License:Apache License

/**
 * Returns the server stream associated to the given HTTP/2 stream object.
 *//*from   w w  w .  j a v  a 2  s.c om*/
private NettyServerStream.TransportState serverStream(Http2Stream stream) {
    return stream == null ? null : (NettyServerStream.TransportState) stream.getProperty(streamKey);
}

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

License:Apache License

@Override
public int onDataRead(final ChannelHandlerContext ctx, final int streamId, final ByteBuf data,
        final int padding, final boolean endOfStream) throws Http2Exception {
    final Http2Stream stream = encoder.connection().stream(streamId);
    final String path = stream.getProperty(pathPropertyKey);
    final Resource resource = stream.getProperty(resourcePropertyKey);
    LOGGER.info("onDataRead. streamId={}, path={}, resource={}, endstream={}", streamId, path, resource,
            endOfStream);//  ww w .ja  v a2  s .  c o m
    switch (resource) {
    case PUSH:
        handlePush(ctx, streamId, path, data);
        break;
    }
    return super.onDataRead(ctx, streamId, data, padding, endOfStream);
}