Example usage for io.netty.handler.codec.http2 Http2Headers get

List of usage examples for io.netty.handler.codec.http2 Http2Headers get

Introduction

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

Prototype

V get(K name);

Source Link

Document

Returns the value of a header with the specified name.

Usage

From source file:com.linkedin.r2.transport.http.client.TestNettyRequestAdapter.java

License:Apache License

@Test
public void testStreamToHttp2HeadersRegularHeaders() throws Exception {
    StreamRequestBuilder streamRequestBuilder = new StreamRequestBuilder(new URI(ANY_URI));
    streamRequestBuilder.setHeader("header1", "value1");
    streamRequestBuilder.setHeader("header2", "value2");
    StreamRequest request = streamRequestBuilder
            .build(EntityStreams.newEntityStream(new ByteStringWriter(ByteString.copy(ANY_ENTITY.getBytes()))));

    Http2Headers headers = NettyRequestAdapter.toHttp2Headers(request);
    Assert.assertNotNull(headers);/*from w  w  w.jav a  2s  .  c om*/

    Assert.assertEquals(headers.get("header1"), "value1");
    Assert.assertEquals(headers.get("header2"), "value2");
}

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 {// w ww.ja  v a  2 s .c om
        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.AbstractMockApnsServerHandler.java

License:Open Source License

protected void verifyHeaders(final Http2Headers headers) throws RejectedNotificationException {
    final String topic;
    {//from   ww w  . jav  a  2 s . c o m
        final CharSequence topicSequence = headers.get(APNS_TOPIC_HEADER);
        topic = (topicSequence != null) ? topicSequence.toString() : null;
    }

    if (topic == null) {
        throw new RejectedNotificationException(ErrorReason.MISSING_TOPIC);
    }

    {
        final Integer priorityCode = headers.getInt(APNS_PRIORITY_HEADER);

        if (priorityCode != null) {
            try {
                DeliveryPriority.getFromCode(priorityCode);
            } catch (final IllegalArgumentException e) {
                throw new RejectedNotificationException(ErrorReason.BAD_PRIORITY);
            }
        }
    }

    {
        final CharSequence pathSequence = headers.get(Http2Headers.PseudoHeaderName.PATH.value());

        if (pathSequence != null) {
            final String pathString = pathSequence.toString();

            if (pathString.startsWith(APNS_PATH_PREFIX)) {
                final String tokenString = pathString.substring(APNS_PATH_PREFIX.length());

                final Matcher tokenMatcher = DEVICE_TOKEN_PATTERN.matcher(tokenString);

                if (!tokenMatcher.matches()) {
                    throw new RejectedNotificationException(ErrorReason.BAD_DEVICE_TOKEN);
                }

                final boolean deviceTokenRegisteredForTopic;
                final Date expirationTimestamp;
                {
                    final Map<String, Date> expirationTimestampsByDeviceToken = this.deviceTokenExpirationsByTopic
                            .get(topic);

                    expirationTimestamp = expirationTimestampsByDeviceToken != null
                            ? expirationTimestampsByDeviceToken.get(tokenString)
                            : null;
                    deviceTokenRegisteredForTopic = expirationTimestampsByDeviceToken != null
                            && expirationTimestampsByDeviceToken.containsKey(tokenString);
                }

                if (expirationTimestamp != null) {
                    throw new RejectedNotificationException(ErrorReason.UNREGISTERED, expirationTimestamp);
                }

                if (!deviceTokenRegisteredForTopic) {
                    throw new RejectedNotificationException(ErrorReason.DEVICE_TOKEN_NOT_FOR_TOPIC);
                }
            }
        } else {
            throw new RejectedNotificationException(ErrorReason.BAD_PATH);
        }
    }
}

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

License:Open Source License

private static UUID getApnsIdFromHeaders(final Http2Headers headers) {
    final CharSequence apnsIdSequence = headers.get(APNS_ID_HEADER);

    try {/*from  w  ww . j  a v a  2 s  .  c  om*/
        return apnsIdSequence != null ? FastUUID.parseUUID(apnsIdSequence) : null;
    } catch (final IllegalArgumentException e) {
        log.error("Failed to parse `apns-id` header: {}", apnsIdSequence, e);
        return null;
    }
}

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

License:Open Source License

@Override
public void handlePushNotification(final Http2Headers headers, final ByteBuf payload)
        throws RejectedNotificationException {
    final CharSequence authorizationSequence = headers.get(APNS_AUTHORIZATION_HEADER);

    if (authorizationSequence != null) {
        final String authorizationHeader = authorizationSequence.toString();

        if (this.rejectedAuthorizationHeader == null) {
            this.rejectedAuthorizationHeader = authorizationHeader;
        }//from  w  w w . ja  v a  2  s  .c  o m

        if (this.rejectedAuthorizationHeader.equals(authorizationHeader)) {
            throw new RejectedNotificationException(RejectionReason.EXPIRED_PROVIDER_TOKEN);
        }
    }
}

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;
    {//w  ww . ja va 2 s  .c  om
        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:com.turo.pushy.apns.server.ParsingMockApnsServerListenerAdapter.java

License:Open Source License

private static ApnsPushNotification parsePushNotification(final Http2Headers headers, final ByteBuf payload) {
    final UUID apnsId;
    {//  ww w .  j  a v a2 s . c om
        final CharSequence apnsIdSequence = headers.get(APNS_ID_HEADER);

        UUID apnsIdFromHeaders;

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

        apnsId = apnsIdFromHeaders;
    }

    final String deviceToken;
    {
        final CharSequence pathSequence = headers.get(Http2Headers.PseudoHeaderName.PATH.value());

        if (pathSequence != null) {
            final String pathString = pathSequence.toString();

            deviceToken = pathString.startsWith(APNS_PATH_PREFIX)
                    ? pathString.substring(APNS_PATH_PREFIX.length())
                    : null;
        } else {
            deviceToken = null;
        }
    }

    final String topic;
    {
        final CharSequence topicSequence = headers.get(APNS_TOPIC_HEADER);
        topic = topicSequence != null ? topicSequence.toString() : null;
    }

    final DeliveryPriority deliveryPriority;
    {
        final Integer priorityCode = headers.getInt(APNS_PRIORITY_HEADER);

        DeliveryPriority priorityFromCode;

        try {
            priorityFromCode = priorityCode != null ? DeliveryPriority.getFromCode(priorityCode) : null;
        } catch (final IllegalArgumentException e) {
            priorityFromCode = null;
        }

        deliveryPriority = priorityFromCode;
    }

    final Date expiration;
    {
        final Integer expirationTimestamp = headers.getInt(APNS_EXPIRATION_HEADER);
        expiration = expirationTimestamp != null ? new Date(expirationTimestamp * 1000) : null;
    }

    final String collapseId;
    {
        final CharSequence collapseIdSequence = headers.get(APNS_COLLAPSE_ID_HEADER);
        collapseId = collapseIdSequence != null ? collapseIdSequence.toString() : null;
    }

    // One challenge here is that we don't actually know that a push notification is valid, even if it's
    // accepted by the push notification handler (since we might be using a handler that blindly accepts
    // everything), so we want to use a lenient push notification implementation.
    return new LenientApnsPushNotification(deviceToken, topic,
            payload != null ? payload.toString(StandardCharsets.UTF_8) : null, expiration, deliveryPriority,
            collapseId, apnsId);
}

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

License:Open Source License

@Override
protected void verifyAuthentication(final Http2Headers headers) throws RejectedNotificationException {
    final String topic;
    {/*w  w  w .  j a  v a 2  s  . co  m*/
        final CharSequence topicSequence = headers.get(APNS_TOPIC_HEADER);
        topic = (topicSequence != null) ? topicSequence.toString() : null;
    }

    if (!this.allowedTopics.contains(topic)) {
        throw new RejectedNotificationException(RejectionReason.BAD_TOPIC);
    }
}

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

License:Open Source License

@Override
protected void verifyAuthentication(final Http2Headers headers) throws RejectedNotificationException {
    final String base64EncodedAuthenticationToken;
    {/*from   w w  w .ja  v a  2  s.c  o  m*/
        final CharSequence authorizationSequence = headers.get(APNS_AUTHORIZATION_HEADER);

        if (authorizationSequence != null) {
            final String authorizationString = authorizationSequence.toString();

            if (authorizationString.startsWith("bearer")) {
                base64EncodedAuthenticationToken = authorizationString.substring("bearer".length()).trim();
            } else {
                throw new RejectedNotificationException(RejectionReason.MISSING_PROVIDER_TOKEN);
            }
        } else {
            throw new RejectedNotificationException(RejectionReason.MISSING_PROVIDER_TOKEN);
        }
    }

    if (base64EncodedAuthenticationToken.trim().length() == 0) {
        throw new RejectedNotificationException(RejectionReason.MISSING_PROVIDER_TOKEN);
    }

    final AuthenticationToken authenticationToken;

    try {
        authenticationToken = new AuthenticationToken(base64EncodedAuthenticationToken);
    } catch (final IllegalArgumentException e) {
        throw new RejectedNotificationException(RejectionReason.INVALID_PROVIDER_TOKEN);
    }

    final ApnsVerificationKey verificationKey = this.verificationKeysByKeyId
            .get(authenticationToken.getKeyId());

    // Have we ever heard of the key in question?
    if (verificationKey == null) {
        throw new RejectedNotificationException(RejectionReason.INVALID_PROVIDER_TOKEN);
    }

    try {
        if (!authenticationToken.verifySignature(verificationKey)) {
            throw new RejectedNotificationException(RejectionReason.INVALID_PROVIDER_TOKEN);
        }
    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
        // This should never happen (here, at least) because we check keys at construction time. If something's
        // going to go wrong, it will go wrong before we ever get here.
        log.error("Failed to verify authentication token signature.", e);
        throw new RuntimeException(e);
    }

    // At this point, we've verified that the token is signed by somebody with the named team's private key. The
    // real APNs server only allows one team per connection, so if this is our first notification, we want to keep
    // track of the team that sent it so we can reject notifications from other teams, even if they're signed
    // correctly.
    if (this.expectedTeamId == null) {
        this.expectedTeamId = authenticationToken.getTeamId();
    }

    if (!this.expectedTeamId.equals(authenticationToken.getTeamId())) {
        throw new RejectedNotificationException(RejectionReason.INVALID_PROVIDER_TOKEN);
    }

    if (authenticationToken.getIssuedAt().getTime() + AUTHENTICATION_TOKEN_EXPIRATION_MILLIS < System
            .currentTimeMillis()) {
        throw new RejectedNotificationException(RejectionReason.EXPIRED_PROVIDER_TOKEN);
    }

    final String topic;
    {
        final CharSequence topicSequence = headers.get(APNS_TOPIC_HEADER);

        if (topicSequence == null) {
            // A topic is always required when using token authentication
            throw new RejectedNotificationException(RejectionReason.MISSING_TOPIC);
        }

        topic = topicSequence.toString();
    }

    final Set<String> topicsAllowedForVerificationKey = this.topicsByVerificationKey.get(verificationKey);

    if (topicsAllowedForVerificationKey == null || !topicsAllowedForVerificationKey.contains(topic)) {
        throw new RejectedNotificationException(RejectionReason.INVALID_PROVIDER_TOKEN);
    }
}

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

License:Open Source License

@Override
public void handlePushNotification(final Http2Headers headers, final ByteBuf payload)
        throws RejectedNotificationException {

    try {/*from   ww w . j a  va  2  s  .  c  o m*/
        final CharSequence apnsIdSequence = headers.get(APNS_ID_HEADER);

        if (apnsIdSequence != null) {
            FastUUID.parseUUID(apnsIdSequence);
        }
    } catch (final IllegalArgumentException e) {
        throw new RejectedNotificationException(RejectionReason.BAD_MESSAGE_ID);
    }

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

    final String topic;
    {
        final CharSequence topicSequence = headers.get(APNS_TOPIC_HEADER);

        if (topicSequence == null) {
            throw new RejectedNotificationException(RejectionReason.MISSING_TOPIC);
        }

        topic = topicSequence.toString();
    }

    {
        final CharSequence collapseIdSequence = headers.get(APNS_COLLAPSE_ID_HEADER);

        if (collapseIdSequence != null && collapseIdSequence.toString()
                .getBytes(StandardCharsets.UTF_8).length > MAX_COLLAPSE_ID_SIZE) {
            throw new RejectedNotificationException(RejectionReason.BAD_COLLAPSE_ID);
        }
    }

    {
        final Integer priorityCode = headers.getInt(APNS_PRIORITY_HEADER);

        if (priorityCode != null) {
            try {
                DeliveryPriority.getFromCode(priorityCode);
            } catch (final IllegalArgumentException e) {
                throw new RejectedNotificationException(RejectionReason.BAD_PRIORITY);
            }
        }
    }

    {
        final CharSequence pathSequence = headers.get(Http2Headers.PseudoHeaderName.PATH.value());

        if (pathSequence != null) {
            final String pathString = pathSequence.toString();

            if (pathSequence.toString().equals(APNS_PATH_PREFIX)) {
                throw new RejectedNotificationException(RejectionReason.MISSING_DEVICE_TOKEN);
            } else if (pathString.startsWith(APNS_PATH_PREFIX)) {
                final String deviceToken = pathString.substring(APNS_PATH_PREFIX.length());

                final Matcher tokenMatcher = DEVICE_TOKEN_PATTERN.matcher(deviceToken);

                if (!tokenMatcher.matches()) {
                    throw new RejectedNotificationException(RejectionReason.BAD_DEVICE_TOKEN);
                }

                final Date expirationTimestamp = this.expirationTimestampsByDeviceToken.get(deviceToken);

                if (expirationTimestamp != null) {
                    throw new UnregisteredDeviceTokenException(expirationTimestamp);
                }

                final Set<String> allowedDeviceTokensForTopic = this.deviceTokensByTopic.get(topic);

                if (allowedDeviceTokensForTopic == null || !allowedDeviceTokensForTopic.contains(deviceToken)) {
                    throw new RejectedNotificationException(RejectionReason.DEVICE_TOKEN_NOT_FOR_TOPIC);
                }
            } else {
                throw new RejectedNotificationException(RejectionReason.BAD_PATH);
            }
        } else {
            throw new RejectedNotificationException(RejectionReason.BAD_PATH);
        }
    }

    this.verifyAuthentication(headers);

    if (payload == null || payload.readableBytes() == 0) {
        throw new RejectedNotificationException(RejectionReason.PAYLOAD_EMPTY);
    }

    if (payload.readableBytes() > MAX_PAYLOAD_SIZE) {
        throw new RejectedNotificationException(RejectionReason.PAYLOAD_TOO_LARGE);
    }
}