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

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

Introduction

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

Prototype

boolean contains(K name);

Source Link

Document

Returns true if a header with the name exists, false otherwise.

Usage

From source file:Http2ClientConnectionHandler.java

License:Apache License

@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,
        short weight, boolean exclusive, int padding, boolean endStream, boolean endSegment)
        throws Http2Exception {
    if (headers.contains(Http2ExampleUtil.UPGRADE_RESPONSE_HEADER)) {
        System.out.println("Received HTTP/2 response to the HTTP->HTTP/2 upgrade request");
    }//  w  w  w . j  a v  a  2s  .c o  m
    final OutstandingRequest outstandingRequest = outstanding.get(streamId);
    if (outstandingRequest != null) {
        for (Map.Entry<String, String> entry : headers.entries()) {
            if (outstandingRequest.status == null && entry.getKey().equals(":status")) {
                outstandingRequest.status = HttpResponseStatus.valueOf(Integer.valueOf(entry.getValue()));
            }
        }
    }
}

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  w  w  w  .  jav  a 2s . c  om*/
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.server.http.Http2RequestDecoder.java

License:Apache License

@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
        boolean endOfStream) throws Http2Exception {
    final HttpHeaders convertedHeaders = ArmeriaHttpUtil.toArmeria(headers);
    DecodedHttpRequest req = requests.get(streamId);
    if (req == null) {
        // Validate the 'content-length' header if exists.
        if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
            final long contentLength = headers.getLong(HttpHeaderNames.CONTENT_LENGTH, -1L);
            if (contentLength < 0) {
                writeErrorResponse(ctx, streamId, HttpResponseStatus.BAD_REQUEST);
                return;
            }//from  w w w . j  a va  2  s.c  o m
        }

        req = new DecodedHttpRequest(ctx.channel().eventLoop(), ++nextId, streamId, convertedHeaders, true,
                inboundTrafficController);

        requests.put(streamId, req);
        ctx.fireChannelRead(req);
    } else {
        try {
            req.write(convertedHeaders);
        } catch (Throwable t) {
            req.close(t);
            throw connectionError(INTERNAL_ERROR, t, "failed to consume a HEADERS frame");
        }
    }

    if (endOfStream) {
        req.close();
    }
}

From source file:com.linecorp.armeria.server.Http2RequestDecoder.java

License:Apache License

@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
        boolean endOfStream) throws Http2Exception {
    DecodedHttpRequest req = requests.get(streamId);
    if (req == null) {
        // Validate the method.
        final CharSequence method = headers.method();
        if (method == null) {
            writeErrorResponse(ctx, streamId, HttpResponseStatus.BAD_REQUEST);
            return;
        }//from  w ww  . j  a  v  a 2s  .  c  om
        if (!HttpMethod.isSupported(method.toString())) {
            writeErrorResponse(ctx, streamId, HttpResponseStatus.METHOD_NOT_ALLOWED);
            return;
        }

        // Validate the 'content-length' header if exists.
        final boolean contentEmpty;
        if (headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
            final long contentLength = headers.getLong(HttpHeaderNames.CONTENT_LENGTH, -1L);
            if (contentLength < 0) {
                writeErrorResponse(ctx, streamId, HttpResponseStatus.BAD_REQUEST);
                return;
            }
            contentEmpty = contentLength == 0;
        } else {
            contentEmpty = true;
        }

        req = new DecodedHttpRequest(ctx.channel().eventLoop(), ++nextId, streamId,
                ArmeriaHttpUtil.toArmeria(headers), true, inboundTrafficController,
                cfg.defaultMaxRequestLength());

        // Close the request early when it is sure that there will be
        // neither content nor trailing headers.
        if (contentEmpty && endOfStream) {
            req.close();
        }

        requests.put(streamId, req);
        ctx.fireChannelRead(req);
    } else {
        try {
            req.write(ArmeriaHttpUtil.toArmeria(headers));
        } catch (Throwable t) {
            req.close(t);
            throw connectionError(INTERNAL_ERROR, t, "failed to consume a HEADERS frame");
        }
    }

    if (endOfStream) {
        req.close();
    }
}

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

License:Apache License

@Test
public void testStreamToHttp2HeadersBlacklist() throws Exception {
    StreamRequestBuilder streamRequestBuilder = new StreamRequestBuilder(new URI(ANY_URI));
    HEADER_BLACKLIST.forEach(header -> streamRequestBuilder.addHeaderValue(header, ANY_HEADER));
    StreamRequest request = streamRequestBuilder
            .build(EntityStreams.newEntityStream(new ByteStringWriter(ByteString.copy(ANY_ENTITY.getBytes()))));

    Http2Headers headers = NettyRequestAdapter.toHttp2Headers(request);
    Assert.assertNotNull(headers);/*from   w ww  .  ja  v  a2  s .co  m*/

    HEADER_BLACKLIST.forEach(header -> Assert.assertFalse(headers.contains(header), header));
}

From source file:org.wso2.carbon.http2.transport.util.Http2RequestWriter.java

License:Open Source License

/**
 * Writes a normal request in wire under given stream-id
 *
 * @param streamId//  w  w  w.j  a v a 2 s .c o m
 * @param msgContext
 * @throws AxisFault
 */
public void writeSimpleReqeust(int streamId, MessageContext msgContext) throws AxisFault {
    Http2TargetRequestUtil util = (Http2TargetRequestUtil) msgContext
            .getProperty(Http2Constants.PASSTHROUGH_TARGET);
    Http2Headers headers = util.getHeaders(msgContext);
    ChannelPromise promise = chContext.newPromise();

    if (util.isHasEntityBody() && headers.contains(HttpHeaderNames.CONTENT_TYPE)) {
        http2Encoder pipeEncoder = new http2Encoder(chContext, streamId, encoder, promise);
        Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
        encoder.writeHeaders(chContext, streamId, headers, 0, false, promise);
        if (pipe != null) {
            pipe.attachConsumer(new Http2CosumerIoControl());
            try {
                if (Boolean.TRUE.equals(msgContext.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(msgContext);
                    OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(msgContext);
                    formatter.writeTo(msgContext, format, out, false);
                    OutputStream _out = pipe.getOutputStream();
                    IOUtils.write(out.toByteArray(), _out);
                }
                int t = pipe.consume(pipeEncoder);
            } catch (IOException e) {
                throw new AxisFault("Error while consuming pipe", e);
            }
        }
    } else {
        encoder.writeHeaders(chContext, streamId, headers, 0, true, promise);
    }
    try {
        encoder.flowController().writePendingBytes();
    } catch (Exception e) {
        throw new AxisFault("Error while writing pending bytes of encoder to channel", e);
    }
    chContext.flush();
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.http2.Http2ResponseWriter.java

License:Open Source License

/**
 * writing a response on wire/* w w w .j  ava2s.c  o m*/
 *
 * @param synCtx
 * @throws AxisFault
 */
public void writeNormalResponse(MessageContext synCtx) throws AxisFault {
    org.apache.axis2.context.MessageContext msgContext = ((Axis2MessageContext) synCtx)
            .getAxis2MessageContext();
    Http2Headers transportHeaders = new DefaultHttp2Headers();
    InboundResponseSender responseSender = synCtx
            .getProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER) == null ? null
                    : (InboundHttp2ResponseSender) synCtx
                            .getProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER);
    try {
        sourceConfiguration = PassThroughInboundEndpointHandler.getPassThroughSourceConfiguration();
    } catch (Exception e) {
        throw new AxisFault("Error while building sourceConfiguration " + e);
    }

    //status
    try {
        int statusCode = PassThroughTransportUtils.determineHttpStatusCode(msgContext);
        if (statusCode > 0) {
            HttpResponseStatus status1 = HttpResponseStatus.valueOf(statusCode);
            transportHeaders.status(status1.codeAsText());
        }
    } catch (Exception e) {
        throw new AxisFault("Error occured while parsing response status", e);
    }
    //content_type
    Boolean noEntityBody = msgContext.getProperty(NhttpConstants.NO_ENTITY_BODY) != null
            ? (boolean) msgContext.getProperty(NhttpConstants.NO_ENTITY_BODY)
            : null;
    if (noEntityBody == null || Boolean.FALSE == noEntityBody) {
        Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
        if (pipe == null) {
            pipe = new Pipe(sourceConfiguration.getBufferFactory().getBuffer(), "Test", sourceConfiguration);
            msgContext.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
            msgContext.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
        }

        OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext);
        MessageFormatter messageFormatter = MessageFormatterDecoratorFactory
                .createMessageFormatterDecorator(msgContext);
        if (msgContext.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE) == null) {
            transportHeaders.add(HttpHeaderNames.CONTENT_TYPE,
                    messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
        }
    }

    if (transportHeaders != null
            && msgContext.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE) != null) {
        if (msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE) != null
                && msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE).toString()
                        .contains(PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED)) {
            transportHeaders.add(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
                    PassThroughConstants.CONTENT_TYPE_MULTIPART_RELATED);
        } else {
            Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE);
            if (pipe != null
                    && !Boolean.TRUE
                            .equals(msgContext.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))
                    && msgContext.getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE) != null) {
                transportHeaders.add(HttpHeaderNames.CONTENT_TYPE, msgContext
                        .getProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE).toString());
            }
        }
    }

    //Excess headers
    String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
    Map excessHeaders = msgContext.getProperty(excessProp) == null ? null
            : (Map) msgContext.getProperty(excessProp);
    if (excessHeaders != null) {
        for (Iterator iterator = excessHeaders.keySet().iterator(); iterator.hasNext();) {
            String key = (String) iterator.next();
            for (String excessVal : (Collection<String>) excessHeaders.get(key)) {
                transportHeaders.add(key.toLowerCase(), (String) excessVal);
            }
        }
    }

    boolean hasBody = false;
    if (!transportHeaders.contains(HttpHeaderNames.CONTENT_TYPE)) {
        String contentType = null;
        try {
            contentType = new InboundMessageHandler(responseSender, config).getContentType(msgContext);
        } catch (Exception e) {
            throw new AxisFault("Error while parsing content type", e);
        }
        if (contentType != null) {
            transportHeaders.add(HttpHeaderNames.CONTENT_TYPE, contentType);
            hasBody = true;
        }
    } else
        hasBody = true;

    int streamId = (int) synCtx.getProperty("stream-id");
    ChannelHandlerContext c = (ChannelHandlerContext) synCtx.getProperty("stream-channel");
    if (c == null) {
        c = chContext;
    }
    ChannelPromise promise = c.newPromise();
    if (hasBody) {
        Pipe pipe = msgContext.getProperty("pass-through.pipe") == null ? null
                : (Pipe) msgContext.getProperty("pass-through.pipe");
        encoder.writeHeaders(c, streamId, transportHeaders, 0, false, promise);
        http2Encoder pipeEncoder = new http2Encoder(c, streamId, encoder, c.newPromise());
        if (pipe != null) {
            pipe.attachConsumer(new Http2CosumerIoControl());
            try {
                if (Boolean.TRUE.equals(msgContext.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED))) {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(msgContext);
                    OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(msgContext);
                    formatter.writeTo(msgContext, format, out, false);
                    OutputStream _out = pipe.getOutputStream();
                    IOUtils.write(out.toByteArray(), _out);
                }
                int t = pipe.consume(pipeEncoder);
                if (t < 1)
                    throw new AxisFault("Pipe consuming failed");
            } catch (Exception e) {
                throw new AxisFault("Error while writing built message back to pipe", e);
            }
        }
        c.flush();
    } else {
        encoder.writeHeaders(c, streamId, transportHeaders, 0, true, promise);
        c.flush();
    }
}