Example usage for io.netty.handler.codec.http2 DefaultHttp2Headers DefaultHttp2Headers

List of usage examples for io.netty.handler.codec.http2 DefaultHttp2Headers DefaultHttp2Headers

Introduction

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

Prototype

public DefaultHttp2Headers() 

Source Link

Document

Create a new instance.

Usage

From source file:com.flysoloing.learning.network.netty.http2.helloworld.multiplex.server.HelloWorldHttp2Handler.java

License:Apache License

/**
 * Sends a "Hello World" DATA frame to the client.
 *///w  ww.  ja va  2s  .  c o  m
private static void sendResponse(ChannelHandlerContext ctx, ByteBuf payload) {
    // Send a frame for the response status
    Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
    ctx.write(new DefaultHttp2HeadersFrame(headers));
    ctx.writeAndFlush(new DefaultHttp2DataFrame(payload, true));
}

From source file:com.flysoloing.learning.network.netty.http2.helloworld.server.HelloWorldHttp2Handler.java

License:Apache License

/**
 * Handles the cleartext HTTP upgrade event. If an upgrade occurred, sends a simple response via HTTP/2
 * on stream 1 (the stream specifically reserved for cleartext HTTP upgrade).
 *///  w w w .  j a  v a2s  .co  m
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    if (evt instanceof HttpServerUpgradeHandler.UpgradeEvent) {
        // Write an HTTP/2 response to the upgrade request
        Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText())
                .set(new AsciiString(UPGRADE_RESPONSE_HEADER), new AsciiString("true"));
        encoder().writeHeaders(ctx, 1, headers, 0, true, ctx.newPromise());
    }
    super.userEventTriggered(ctx, evt);
}

From source file:com.flysoloing.learning.network.netty.http2.helloworld.server.HelloWorldHttp2Handler.java

License:Apache License

/**
 * Sends a "Hello World" DATA frame to the client.
 *//* w  w w.  jav  a  2 s .  co  m*/
private void sendResponse(ChannelHandlerContext ctx, int streamId, ByteBuf payload) {
    // Send a frame for the response status
    Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
    encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
    encoder().writeData(ctx, streamId, payload, 0, true, ctx.newPromise());
    try {
        flush(ctx);
    } catch (Throwable cause) {
        onError(ctx, cause);
    }
}

From source file:com.hop.hhxx.example.http2.helloworld.multiplex.server.HelloWorldHttp2Handler.java

License:Apache License

/**
 * Sends a "Hello World" DATA frame to the client.
 *//*ww w  .  ja  va  2  s  . c o m*/
private void sendResponse(ChannelHandlerContext ctx, ByteBuf payload) {
    // Send a frame for the response status
    Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
    ctx.write(new DefaultHttp2HeadersFrame(headers));
    ctx.writeAndFlush(new DefaultHttp2DataFrame(payload, true));
}

From source file:com.hop.hhxx.example.http2.helloworld.server.HelloWorldHttp2Handler.java

License:Apache License

/**
 * Sends a "Hello World" DATA frame to the client.
 *///w w  w  .jav a2 s . c  om
private void sendResponse(ChannelHandlerContext ctx, int streamId, ByteBuf payload) {
    // Send a frame for the response status
    Http2Headers headers = new DefaultHttp2Headers().status(OK.codeAsText());
    encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
    encoder().writeData(ctx, streamId, payload, 0, true, ctx.newPromise());
    ctx.flush();
}

From source file:com.linecorp.armeria.internal.ArmeriaHttpUtilTest.java

License:Apache License

@Test
public void inboundCookiesMustBeMergedForHttp2() {
    final Http2Headers in = new DefaultHttp2Headers();

    in.add(HttpHeaderNames.COOKIE, "a=b; c=d");
    in.add(HttpHeaderNames.COOKIE, "e=f;g=h");
    in.addObject(HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8);
    in.add(HttpHeaderNames.COOKIE, "i=j");
    in.add(HttpHeaderNames.COOKIE, "k=l;");

    final HttpHeaders out = toArmeria(in);

    assertThat(out.getAll(HttpHeaderNames.COOKIE)).containsExactly("a=b; c=d; e=f; g=h; i=j; k=l");
}

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

License:Apache License

/**
 * Extracts fields from a {@link Request} and construct a {@link Http2Headers} instance.
 *
 * @param request StreamRequest to extract fields from
 * @return a new instance of Http2Headers
 * @throws Exception/*from   ww w  .j  a v  a2s  .  c  o m*/
 */
static <R extends Request> Http2Headers toHttp2Headers(R request) throws Exception {
    URI uri = request.getURI();
    URL url = new URL(uri.toString());

    String method = request.getMethod();
    String authority = url.getAuthority();
    String path = url.getFile();
    String scheme = uri.getScheme();

    // RFC 2616, section 5.1.2:
    //   Note that the absolute path cannot be empty; if none is present in the original URI,
    //   it MUST be given as "/" (the server root).
    path = path.isEmpty() ? "/" : path;

    final Http2Headers headers = new DefaultHttp2Headers().method(method).authority(authority).path(path)
            .scheme(scheme);
    for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
        // Ignores HTTP/2 blacklisted headers
        if (HEADER_BLACKLIST.contains(entry.getKey().toLowerCase())) {
            continue;
        }

        // RFC 7540, section 8.1.2:
        //   ... header field names MUST be converted to lowercase prior to their
        //   encoding in HTTP/2.  A request or response containing uppercase
        //   header field names MUST be treated as malformed (Section 8.1.2.6).
        String name = entry.getKey().toLowerCase();
        String value = entry.getValue();
        headers.set(name, value);
    }

    // Split up cookies to allow for better header compression
    headers.set(HttpHeaderNames.COOKIE, request.getCookies());

    return headers;
}

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 {/*ww w .  j  a va  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.AbstractMockApnsServerHandler.java

License:Open Source License

@Override
public void write(final ChannelHandlerContext context, final Object message, final ChannelPromise writePromise)
        throws Exception {
    if (message instanceof AcceptNotificationResponse) {
        final AcceptNotificationResponse acceptNotificationResponse = (AcceptNotificationResponse) message;
        this.encoder().writeHeaders(context, acceptNotificationResponse.getStreamId(), SUCCESS_HEADERS, 0, true,
                writePromise);/*from  ww w . j av a  2s  .  c  o  m*/

        log.trace("Accepted push notification on stream {}", acceptNotificationResponse.getStreamId());
    } else if (message instanceof RejectNotificationResponse) {
        final RejectNotificationResponse rejectNotificationResponse = (RejectNotificationResponse) message;

        final Http2Headers headers = new DefaultHttp2Headers();
        headers.status(rejectNotificationResponse.getErrorReason().getHttpResponseStatus().codeAsText());
        headers.add(HttpHeaderNames.CONTENT_TYPE, "application/json");

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

        final byte[] payloadBytes;
        {
            final ErrorResponse errorResponse = new ErrorResponse(
                    rejectNotificationResponse.getErrorReason().getReasonText(),
                    rejectNotificationResponse.getTimestamp());

            payloadBytes = GSON.toJson(errorResponse).getBytes();
        }

        final ChannelPromise headersPromise = context.newPromise();
        this.encoder().writeHeaders(context, rejectNotificationResponse.getStreamId(), headers, 0, false,
                headersPromise);

        final ChannelPromise dataPromise = context.newPromise();
        this.encoder().writeData(context, rejectNotificationResponse.getStreamId(),
                Unpooled.wrappedBuffer(payloadBytes), 0, true, dataPromise);

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

        log.trace("Rejected push notification on stream {}: {}", rejectNotificationResponse.getStreamId(),
                rejectNotificationResponse.getErrorReason());
    } else if (message instanceof InternalServerErrorResponse) {
        final InternalServerErrorResponse internalServerErrorResponse = (InternalServerErrorResponse) message;

        final Http2Headers headers = new DefaultHttp2Headers();
        headers.status(HttpResponseStatus.INTERNAL_SERVER_ERROR.codeAsText());

        this.encoder().writeHeaders(context, internalServerErrorResponse.getStreamId(), headers, 0, true,
                writePromise);

        log.trace("Encountered an internal error on stream {}", internalServerErrorResponse.getStreamId());
    } else {
        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());
    }/*from w w w . j av  a  2s .com*/

    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;
}