List of usage examples for io.netty.handler.codec.http2 Http2Headers add
T add(K name, V value);
From source file:com.linecorp.armeria.internal.ArmeriaHttpUtil.java
License:Apache License
/** * Converts the specified Armeria HTTP/2 headers into Netty HTTP/2 headers. *///from www . j a v a 2s . c o m public static Http2Headers toNettyHttp2(HttpHeaders in) { final Http2Headers out = new DefaultHttp2Headers(false, in.size()); out.set(in); out.remove(HttpHeaderNames.CONNECTION); out.remove(HttpHeaderNames.TRANSFER_ENCODING); out.remove(HttpHeaderNames.TRAILER); if (!out.contains(HttpHeaderNames.COOKIE)) { return out; } // Split up cookies to allow for better compression. // https://tools.ietf.org/html/rfc7540#section-8.1.2.5 final List<CharSequence> cookies = out.getAllAndRemove(HttpHeaderNames.COOKIE); for (CharSequence c : cookies) { out.add(HttpHeaderNames.COOKIE, COOKIE_SPLITTER.split(c)); } return out; }
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.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 va2s . c o 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 w ww .j av a 2s .c om 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()); }//w w w . j a v a 2 s. 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:com.turo.pushy.apns.TokenAuthenticationApnsClientHandler.java
License:Open Source License
@Override protected Http2Headers getHeadersForPushNotification(final ApnsPushNotification pushNotification, final int streamId) { final Http2Headers headers = super.getHeadersForPushNotification(pushNotification, streamId); if (this.authenticationToken == null) { try {/*from ww w . j a va 2s . com*/ this.authenticationToken = new AuthenticationToken(signingKey, new Date()); this.mostRecentStreamWithNewToken = streamId; } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) { // This should never happen because we check the key/algorithm at signing key construction time. log.error("Failed to generate authentication token.", e); throw new RuntimeException(e); } } headers.add(APNS_AUTHORIZATION_HEADER, this.authenticationToken.getAuthorizationHeader()); return headers; }
From source file:io.grpc.netty.GrpcHpackDecoder.java
License:Apache License
private long addHeader(int streamId, Http2Headers headers, CharSequence name, CharSequence value, long headersLength) throws Http2Exception { headersLength += name.length() + value.length(); if (headersLength > maxHeaderListSizeGoAway) { headerListSizeExceeded(maxHeaderListSizeGoAway); }/* w w w. jav a2 s . c o m*/ headers.add(name, value); return headersLength; }
From source file:io.grpc.netty.GrpcHttp2HeadersUtilsTest.java
License:Apache License
@Test public void decode_requestHeaders() throws Http2Exception { Http2HeadersDecoder decoder = new GrpcHttp2ServerHeadersDecoder(DEFAULT_MAX_HEADER_LIST_SIZE); Http2HeadersEncoder encoder = new DefaultHttp2HeadersEncoder(NEVER_SENSITIVE); Http2Headers headers = new DefaultHttp2Headers(false); headers.add(of(":scheme"), of("https")).add(of(":method"), of("GET")).add(of(":path"), of("index.html")) .add(of(":authority"), of("foo.grpc.io")).add(of("custom"), of("header")); encodedHeaders = Unpooled.buffer();/*from w w w.ja v a 2 s .c o m*/ encoder.encodeHeaders(1 /* randomly chosen */, headers, encodedHeaders); Http2Headers decodedHeaders = decoder.decodeHeaders(3 /* randomly chosen */, encodedHeaders); assertEquals(headers.get(of(":scheme")), decodedHeaders.scheme()); assertEquals(headers.get(of(":method")), decodedHeaders.method()); assertEquals(headers.get(of(":path")), decodedHeaders.path()); assertEquals(headers.get(of(":authority")), decodedHeaders.authority()); assertEquals(headers.get(of("custom")), decodedHeaders.get(of("custom"))); assertEquals(headers.size(), decodedHeaders.size()); String toString = decodedHeaders.toString(); assertContainsKeyAndValue(toString, ":scheme", decodedHeaders.scheme()); assertContainsKeyAndValue(toString, ":method", decodedHeaders.method()); assertContainsKeyAndValue(toString, ":path", decodedHeaders.path()); assertContainsKeyAndValue(toString, ":authority", decodedHeaders.authority()); assertContainsKeyAndValue(toString, "custom", decodedHeaders.get(of("custom"))); }
From source file:io.grpc.netty.GrpcHttp2HeadersUtilsTest.java
License:Apache License
@Test public void decode_responseHeaders() throws Http2Exception { Http2HeadersDecoder decoder = new GrpcHttp2ClientHeadersDecoder(DEFAULT_MAX_HEADER_LIST_SIZE); Http2HeadersEncoder encoder = new DefaultHttp2HeadersEncoder(NEVER_SENSITIVE); Http2Headers headers = new DefaultHttp2Headers(false); headers.add(of(":status"), of("200")).add(of("custom"), of("header")); encodedHeaders = Unpooled.buffer();/*from ww w . j av a2s. c o m*/ encoder.encodeHeaders(1 /* randomly chosen */, headers, encodedHeaders); Http2Headers decodedHeaders = decoder.decodeHeaders(3 /* randomly chosen */, encodedHeaders); assertEquals(headers.get(of(":status")), decodedHeaders.get(of(":status"))); assertEquals(headers.get(of("custom")), decodedHeaders.get(of("custom"))); assertEquals(headers.size(), decodedHeaders.size()); String toString = decodedHeaders.toString(); assertContainsKeyAndValue(toString, ":status", decodedHeaders.get(of(":status"))); assertContainsKeyAndValue(toString, "custom", decodedHeaders.get(of("custom"))); }
From source file:io.grpc.netty.GrpcHttp2HeadersUtilsTest.java
License:Apache License
@Test public void dupBinHeadersWithComma() { Key<byte[]> key = Key.of("bytes-bin", BINARY_BYTE_MARSHALLER); Http2Headers http2Headers = new GrpcHttp2RequestHeaders(2); http2Headers.add(AsciiString.of("bytes-bin"), AsciiString.of("BaS,e6,,4+,padding==")); http2Headers.add(AsciiString.of("bytes-bin"), AsciiString.of("more")); http2Headers.add(AsciiString.of("bytes-bin"), AsciiString.of("")); Metadata recoveredHeaders = Utils.convertHeaders(http2Headers); byte[][] values = Iterables.toArray(recoveredHeaders.getAll(key), byte[].class); assertTrue(Arrays.deepEquals(new byte[][] { BaseEncoding.base64().decode("BaS"), BaseEncoding.base64().decode("e6"), BaseEncoding.base64().decode(""), BaseEncoding.base64().decode("4+"), BaseEncoding.base64().decode("padding"), BaseEncoding.base64().decode("more"), BaseEncoding.base64().decode("") }, values)); }