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

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

Introduction

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

Prototype

T addInt(K name, int value);

Source Link

Document

Adds a new header.

Usage

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

License:Open Source License

@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise writePromise)
        throws Http2Exception {
    if (message instanceof PushNotificationAndResponsePromise) {
        final PushNotificationAndResponsePromise pushNotificationAndResponsePromise = (PushNotificationAndResponsePromise) message;

        final ApnsPushNotification pushNotification = pushNotificationAndResponsePromise.getPushNotification();

        if (this.responsePromises.containsKey(pushNotification)) {
            writePromise.tryFailure(new PushNotificationStillPendingException());
        } else {/*from  w w w.  j a  v  a 2  s  .co m*/
            this.responsePromises.put(pushNotification,
                    pushNotificationAndResponsePromise.getResponsePromise());

            pushNotificationAndResponsePromise.getResponsePromise().addListener(
                    new GenericFutureListener<Future<PushNotificationResponse<ApnsPushNotification>>>() {

                        @Override
                        public void operationComplete(
                                final Future<PushNotificationResponse<ApnsPushNotification>> future) {
                            // Regardless of the outcome, when the response promise is finished, we want to remove it from
                            // the map of pending promises.
                            ApnsClientHandler.this.responsePromises.remove(pushNotification);
                        }
                    });

            this.write(context, pushNotification, writePromise);
        }
    } else if (message instanceof ApnsPushNotification) {
        final ApnsPushNotification pushNotification = (ApnsPushNotification) message;

        try {
            final int streamId = (int) this.nextStreamId;

            final Http2Headers headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName())
                    .authority(this.authority).path(APNS_PATH_PREFIX + pushNotification.getToken())
                    .addInt(APNS_EXPIRATION_HEADER, pushNotification.getExpiration() == null ? 0
                            : (int) (pushNotification.getExpiration().getTime() / 1000));

            final String authenticationToken = this.apnsClient
                    .getAuthenticationTokenSupplierForTopic(pushNotification.getTopic()).getToken();
            headers.add(APNS_AUTHORIZATION_HEADER, "bearer " + authenticationToken);

            if (pushNotification.getCollapseId() != null) {
                headers.add(APNS_COLLAPSE_ID_HEADER, pushNotification.getCollapseId());
            }

            if (pushNotification.getPriority() != null) {
                headers.addInt(APNS_PRIORITY_HEADER, pushNotification.getPriority().getCode());
            }

            if (pushNotification.getTopic() != null) {
                headers.add(APNS_TOPIC_HEADER, pushNotification.getTopic());
            }

            final ChannelPromise headersPromise = context.newPromise();
            this.encoder().writeHeaders(context, streamId, headers, 0, false, headersPromise);
            log.trace("Wrote headers on stream {}: {}", streamId, headers);

            final ByteBuf payloadBuffer = context.alloc().ioBuffer(INITIAL_PAYLOAD_BUFFER_CAPACITY);
            payloadBuffer.writeBytes(pushNotification.getPayload().getBytes(StandardCharsets.UTF_8));

            final ChannelPromise dataPromise = context.newPromise();
            this.encoder().writeData(context, streamId, payloadBuffer, 0, true, dataPromise);
            log.trace("Wrote payload on stream {}: {}", streamId, pushNotification.getPayload());

            final PromiseCombiner promiseCombiner = new PromiseCombiner();
            promiseCombiner.addAll(headersPromise, dataPromise);
            promiseCombiner.finish(writePromise);

            writePromise.addListener(new GenericFutureListener<ChannelPromise>() {

                @Override
                public void operationComplete(final ChannelPromise future) throws Exception {
                    if (future.isSuccess()) {
                        ApnsClientHandler.this.pushNotificationsByStreamId.put(streamId, pushNotification);
                        ApnsClientHandler.this.authenticationTokensByStreamId.put(streamId,
                                authenticationToken);
                    } else {
                        log.trace("Failed to write push notification on stream {}.", streamId, future.cause());

                        final Promise<PushNotificationResponse<ApnsPushNotification>> responsePromise = ApnsClientHandler.this.responsePromises
                                .get(pushNotification);

                        if (responsePromise != null) {
                            responsePromise.tryFailure(future.cause());
                        } else {
                            log.error("Notification write failed, but no response promise found.");
                        }
                    }
                }
            });

            this.nextStreamId += 2;

            if (this.nextStreamId >= STREAM_ID_RESET_THRESHOLD) {
                // This is very unlikely, but in the event that we run out of stream IDs (the maximum allowed is
                // 2^31, per https://httpwg.github.io/specs/rfc7540.html#StreamIdentifiers), we need to open a new
                // connection. Just closing the context should be enough; automatic reconnection should take things
                // from there.
                context.close();
            }
        } catch (NoKeyForTopicException | SignatureException e) {
            writePromise.tryFailure(e);
        }

    } else {
        // This should never happen, but in case some foreign debris winds up in the pipeline, just pass it through.
        log.error("Unexpected object in pipeline: {}", message);
        context.write(message, writePromise);
    }
}

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

License:Open Source License

protected Http2Headers getHeadersForPushNotification(final ApnsPushNotification pushNotification,
        final int streamId) {
    final Http2Headers headers = new DefaultHttp2Headers().method(HttpMethod.POST.asciiName())
            .authority(this.authority).path(APNS_PATH_PREFIX + pushNotification.getToken())
            .scheme(HttpScheme.HTTPS.name())
            .addInt(APNS_EXPIRATION_HEADER, pushNotification.getExpiration() == null ? 0
                    : (int) (pushNotification.getExpiration().getTime() / 1000));

    if (pushNotification.getCollapseId() != null) {
        headers.add(APNS_COLLAPSE_ID_HEADER, pushNotification.getCollapseId());
    }//  w ww .  ja v  a 2s .c o  m

    if (pushNotification.getPriority() != null) {
        headers.addInt(APNS_PRIORITY_HEADER, pushNotification.getPriority().getCode());
    }

    if (pushNotification.getTopic() != null) {
        headers.add(APNS_TOPIC_HEADER, pushNotification.getTopic());
    }

    if (pushNotification.getApnsId() != null) {
        headers.add(APNS_ID_HEADER, FastUUID.toString(pushNotification.getApnsId()));
    }

    return headers;
}

From source file:org.jboss.aerogear.webpush.WebPushClient.java

License:Apache License

public void notify(final String endpointUrl, final String payload, final String receiptUrl, int ttl)
        throws Exception {
    final Http2Headers headers = http2Headers(POST, endpointUrl);
    if (receiptUrl != null && !receiptUrl.isEmpty()) {
        headers.add(PUSH_RECEIPT_HEADER, AsciiString.of(receiptUrl));
    }/*  w ww. ja  va  2  s  .c  o  m*/
    if (ttl > 0) {
        headers.addInt(TTL_HEADER, ttl);
    }
    writeRequest(headers, copiedBuffer(payload, UTF_8));
}