Example usage for io.netty.handler.codec.http HttpMethod valueOf

List of usage examples for io.netty.handler.codec.http HttpMethod valueOf

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpMethod valueOf.

Prototype

public static HttpMethod valueOf(String name) 

Source Link

Document

Returns the HttpMethod represented by the specified name.

Usage

From source file:org.nosceon.titanite.Router.java

License:Apache License

private Method map(HttpMethod method) {
    try {//from   w  ww  .jav a 2s  .c om
        return Method.valueOf(method.name());
    } catch (IllegalArgumentException e) {
        return null;
    }
}

From source file:org.restexpress.Request.java

License:Apache License

/**
 * If the request HTTP method is post, allow a query string parameter to determine
 * the request HTTP method of the post (e.g. _method=DELETE or _method=PUT).  This
 * supports DELETE and PUT from the browser.
 */// w  w w .  j av  a 2 s . c o  m
private void determineEffectiveHttpMethod(HttpRequest request) {
    if (!HttpMethod.POST.equals(request.getMethod()))
        return;

    String methodString = request.headers().get(Parameters.Query.METHOD_TUNNEL);

    if ("PUT".equalsIgnoreCase(methodString) || "DELETE".equalsIgnoreCase(methodString)) {
        effectiveHttpMethod = HttpMethod.valueOf(methodString.toUpperCase());
    }
}

From source file:org.restnext.core.http.RequestImpl.java

License:Apache License

private boolean isGetOrHead() {
    HttpMethod httpMethod = HttpMethod.valueOf(getMethod().toString());
    return HttpMethod.GET.equals(httpMethod) || HttpMethod.HEAD.equals(httpMethod);
}

From source file:org.springframework.cloud.gateway.filter.NettyRoutingFilter.java

License:Apache License

@Override
@SuppressWarnings("Duplicates")
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

    String scheme = requestUrl.getScheme();
    if (isAlreadyRouted(exchange) || (!"http".equals(scheme) && !"https".equals(scheme))) {
        return chain.filter(exchange);
    }/* w w  w. ja va 2 s.c o  m*/
    setAlreadyRouted(exchange);

    ServerHttpRequest request = exchange.getRequest();

    final HttpMethod method = HttpMethod.valueOf(request.getMethodValue());
    final String url = requestUrl.toASCIIString();

    HttpHeaders filtered = filterRequest(getHeadersFilters(), exchange);

    final DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
    filtered.forEach(httpHeaders::set);

    boolean preserveHost = exchange.getAttributeOrDefault(PRESERVE_HOST_HEADER_ATTRIBUTE, false);

    Flux<HttpClientResponse> responseFlux = this.httpClient.request(method).uri(url)
            .send((req, nettyOutbound) -> {
                req.headers(httpHeaders);

                if (preserveHost) {
                    String host = request.getHeaders().getFirst(HttpHeaders.HOST);
                    req.header(HttpHeaders.HOST, host);
                }
                if (log.isTraceEnabled()) {
                    nettyOutbound.withConnection(
                            connection -> log.trace("outbound route: " + connection.channel().id().asShortText()
                                    + ", inbound: " + exchange.getLogPrefix()));
                }
                return nettyOutbound.options(NettyPipeline.SendOptions::flushOnEach).send(
                        request.getBody().map(dataBuffer -> ((NettyDataBuffer) dataBuffer).getNativeBuffer()));
            }).responseConnection((res, connection) -> {

                // Defer committing the response until all route filters have run
                // Put client response as ServerWebExchange attribute and write
                // response later NettyWriteResponseFilter
                exchange.getAttributes().put(CLIENT_RESPONSE_ATTR, res);
                exchange.getAttributes().put(CLIENT_RESPONSE_CONN_ATTR, connection);

                ServerHttpResponse response = exchange.getResponse();
                // put headers and status so filters can modify the response
                HttpHeaders headers = new HttpHeaders();

                res.responseHeaders().forEach(entry -> headers.add(entry.getKey(), entry.getValue()));

                String contentTypeValue = headers.getFirst(HttpHeaders.CONTENT_TYPE);
                if (StringUtils.hasLength(contentTypeValue)) {
                    exchange.getAttributes().put(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR, contentTypeValue);
                }

                HttpStatus status = HttpStatus.resolve(res.status().code());
                if (status != null) {
                    response.setStatusCode(status);
                } else if (response instanceof AbstractServerHttpResponse) {
                    // https://jira.spring.io/browse/SPR-16748
                    ((AbstractServerHttpResponse) response).setStatusCodeValue(res.status().code());
                } else {
                    // TODO: log warning here, not throw error?
                    throw new IllegalStateException("Unable to set status code on response: "
                            + res.status().code() + ", " + response.getClass());
                }

                // make sure headers filters run after setting status so it is
                // available in response
                HttpHeaders filteredResponseHeaders = HttpHeadersFilter.filter(getHeadersFilters(), headers,
                        exchange, Type.RESPONSE);

                if (!filteredResponseHeaders.containsKey(HttpHeaders.TRANSFER_ENCODING)
                        && filteredResponseHeaders.containsKey(HttpHeaders.CONTENT_LENGTH)) {
                    // It is not valid to have both the transfer-encoding header and
                    // the content-length header
                    // remove the transfer-encoding header in the response if the
                    // content-length header is presen
                    response.getHeaders().remove(HttpHeaders.TRANSFER_ENCODING);
                }

                exchange.getAttributes().put(CLIENT_RESPONSE_HEADER_NAMES, filteredResponseHeaders.keySet());

                response.getHeaders().putAll(filteredResponseHeaders);

                return Mono.just(res);
            });

    if (properties.getResponseTimeout() != null) {
        responseFlux = responseFlux
                .timeout(properties.getResponseTimeout(),
                        Mono.error(new TimeoutException(
                                "Response took longer than timeout: " + properties.getResponseTimeout())))
                .onErrorMap(TimeoutException.class,
                        th -> new ResponseStatusException(HttpStatus.GATEWAY_TIMEOUT, th.getMessage(), th));
    }

    return responseFlux.then(chain.filter(exchange));
}

From source file:org.springframework.cloud.gateway.handler.NettyRoutingWebHandler.java

License:Apache License

@Override
public Mono<Void> handle(ServerWebExchange exchange) {
    Optional<URI> requestUrl = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
    ServerHttpRequest request = exchange.getRequest();

    final HttpMethod method = HttpMethod.valueOf(request.getMethod().toString());
    final String url = requestUrl.get().toString();

    final DefaultHttpHeaders httpHeaders = new DefaultHttpHeaders();
    request.getHeaders().forEach(httpHeaders::set);

    return this.httpClient.request(method, url,
            req -> req.options(NettyPipeline.SendOptions::flushOnEach).headers(httpHeaders).sendHeaders()
                    .send(request.getBody().map(DataBuffer::asByteBuffer).map(Unpooled::wrappedBuffer)))
            .then(res -> {//from   w  w w  .jav  a 2  s.  co  m
                // Defer committing the response until all route filters have run
                // Put client response as ServerWebExchange attribute and write response later WriteResponseFilter
                exchange.getAttributes().put(CLIENT_RESPONSE_ATTR, res);

                ServerHttpResponse response = exchange.getResponse();
                // put headers and status so filters can modify the response
                final HttpHeaders headers = new HttpHeaders();
                res.responseHeaders().forEach(entry -> headers.add(entry.getKey(), entry.getValue()));

                response.getHeaders().putAll(headers);
                response.setStatusCode(HttpStatus.valueOf(res.status().code()));

                return Mono.empty();
            });
}

From source file:org.thingsplode.synapse.proxy.handlers.Request2HttpRequestEncoder.java

License:Apache License

private HttpRequest convert(Request request) throws SerializationException {
    if (request == null || request.getHeader() == null) {
        return null;
    }//from  ww  w.  j  a  v  a 2s. co  m
    HttpMethod m = null;
    if (request.getHeader().getMethod() != null) {
        m = HttpMethod.valueOf(request.getHeader().getMethod().toString());
    } else if (request.getHeader().getUri() != null && !Util.isEmpty(request.getHeader().getUri().getQuery())) {
        m = HttpMethod.GET;
    } else if (request.getBody() != null) {
        m = HttpMethod.PUT;
    } else {
        m = HttpMethod.GET;
    }
    final HttpRequest out;
    if (request.getBody() != null) {
        Optional<String> contentTypeOpt = request.getRequestHeaderProperty(HttpHeaderNames.ACCEPT.toString());
        MediaType mt = contentTypeOpt.isPresent() ? new MediaType(contentTypeOpt.get())
                : new MediaType(MediaType.APPLICATION_JSON_CT);
        request.getHeader().addProperty(AbstractMessage.PROP_BODY_TYPE,
                request.getBody().getClass().getCanonicalName());
        byte[] payload = EndpointProxy.SERIALIZATION_SERVICE.getSerializer(mt).marshall(request.getBody());
        out = new DefaultFullHttpRequest(HttpVersion.HTTP_1_0, m, request.getHeader().getUri().getPath(),
                Unpooled.wrappedBuffer(payload));
        out.headers().add(HttpHeaderNames.CONTENT_LENGTH, payload.length);
    } else {
        out = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, m, request.getHeader().getUri().getPath());
    }
    if (request.getHeader().isKeepalive()) {
        out.headers().add(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    if (request.getHeader() != null && request.getHeader().getProperties() != null) {
        request.getHeader().getProperties().forEach((k, v) -> {
            out.headers().set(new AsciiString(k), new AsciiString(v != null ? v : ""));
        });
    }
    return out;
}

From source file:org.waarp.gateway.kernel.rest.client.HttpRestClientHelper.java

License:Open Source License

/**
 * //ww  w  .j a  va 2 s  . c  o  m
 * @param args
 *            as uri (http://host:port/uri method user pwd sign=path|nosign [json])
 */
public static void main(String[] args) {
    WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null));
    final WaarpLogger logger = WaarpLoggerFactory.getLogger(HttpRestClientHelper.class);
    if (args.length < 5) {
        logger.error("Need more arguments: http://host:port/uri method user pwd sign=path|nosign [json]");
        return;
    }
    String uri = args[0];
    String meth = args[1];
    String user = args[2];
    String pwd = args[3];
    boolean sign = args[4].toLowerCase().contains("sign=");
    HmacSha256 hmacSha256 = null;
    if (sign) {
        String file = args[4].replace("sign=", "");
        hmacSha256 = new HmacSha256();
        try {
            hmacSha256.setSecretKey(new File(file));
        } catch (CryptoException e) {
            logger.error("Need more arguments: http://host:port/uri method user pwd sign=path|nosign [json]");
            return;
        } catch (IOException e) {
            logger.error("Need more arguments: http://host:port/uri method user pwd sign=path|nosign [json]");
            return;
        }
    }
    String json = null;
    if (args.length > 5) {
        json = args[5].replace("'", "\"");
    }
    HttpMethod method = HttpMethod.valueOf(meth);
    int port = -1;
    String host = null;
    String path = null;
    try {
        URI realUri = new URI(uri);
        port = realUri.getPort();
        host = realUri.getHost();
        path = realUri.getPath();
    } catch (URISyntaxException e) {
        logger.error("Error", e);
        return;
    }
    HttpRestClientHelper client = new HttpRestClientHelper(path, 1, 30000,
            new HttpRestClientSimpleInitializer());
    Channel channel = client.getChannel(host, port);
    if (channel == null) {
        client.closeAll();
        logger.error("Cannot connect to " + host + " on port " + port);
        return;
    }
    RestFuture future = null;
    if (sign) {
        future = client.sendQuery(hmacSha256, channel, method, host, null, user, pwd, null, json);
    } else {
        future = client.sendQuery(channel, method, host, null, user, null, json);
    }
    try {
        future.await();
    } catch (InterruptedException e) {
        client.closeAll();
        logger.error("Interruption", e);
        return;
    }
    WaarpSslUtility.closingSslChannel(channel);
    if (future.isSuccess()) {
        logger.warn(future.getRestArgument().prettyPrint());
    } else {
        RestArgument ra = future.getRestArgument();
        if (ra != null) {
            logger.error(ra.prettyPrint());
        } else {
            logger.error("Query in error", future.getCause());
        }
    }
    client.closeAll();
}

From source file:ratpack.handling.internal.MethodHandler.java

License:Apache License

private MethodHandler(String method) {
    this.method = DefaultHttpMethod.valueOf(HttpMethod.valueOf(method));
}

From source file:ratpack.http.client.internal.RequestActionSupport.java

License:Apache License

public void execute(final Fulfiller<? super T> fulfiller) throws Exception {
    final AtomicBoolean redirecting = new AtomicBoolean();

    final Bootstrap b = new Bootstrap();
    b.group(this.execution.getEventLoop()).channel(ChannelImplDetector.getSocketChannelImpl())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from  w w  w  .ja  v a2s.c  o  m
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();

                    if (finalUseSsl) {
                        SSLEngine engine = SSLContext.getDefault().createSSLEngine();
                        engine.setUseClientMode(true);
                        p.addLast("ssl", new SslHandler(engine));
                    }

                    p.addLast("codec", new HttpClientCodec());
                    p.addLast("readTimeout",
                            new ReadTimeoutHandler(requestParams.readTimeoutNanos, TimeUnit.NANOSECONDS));

                    p.addLast("redirectHandler", new SimpleChannelInboundHandler<HttpObject>(false) {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
                                throws Exception {
                            if (msg instanceof HttpResponse) {
                                final HttpResponse response = (HttpResponse) msg;
                                final Headers headers = new NettyHeadersBackedHeaders(response.headers());
                                final Status status = new DefaultStatus(response.status());
                                int maxRedirects = requestSpecBacking.getMaxRedirects();
                                String locationValue = headers.get("Location");

                                //Check for redirect and location header if it is follow redirect if we have request forwarding left
                                if (shouldRedirect(status) && maxRedirects > 0 && locationValue != null) {
                                    redirecting.compareAndSet(false, true);

                                    Action<? super RequestSpec> redirectRequestConfig = Action
                                            .join(requestConfigurer, s -> {
                                                if (status.getCode() == 301 || status.getCode() == 302) {
                                                    s.method("GET");
                                                }

                                                s.redirects(maxRedirects - 1);
                                            });

                                    URI locationUrl;
                                    if (ABSOLUTE_PATTERN.matcher(locationValue).matches()) {
                                        locationUrl = new URI(locationValue);
                                    } else {
                                        locationUrl = new URI(uri.getScheme(), null, uri.getHost(),
                                                uri.getPort(), locationValue, null, null);
                                    }

                                    buildRedirectRequestAction(redirectRequestConfig, locationUrl)
                                            .execute(fulfiller);
                                } else {
                                    p.remove(this);
                                }
                            }

                            if (!redirecting.get()) {
                                ctx.fireChannelRead(msg);
                            }
                        }
                    });

                    addResponseHandlers(p, fulfiller);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    ctx.close();
                    error(fulfiller, cause);
                }
            });

    ChannelFuture connectFuture = b.connect(host, port);
    connectFuture.addListener(f1 -> {
        if (connectFuture.isSuccess()) {
            String fullPath = getFullPath(uri);
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(requestSpecBacking.getMethod()), fullPath, requestSpecBacking.getBody());
            if (headers.get(HttpHeaderConstants.HOST) == null) {
                headers.set(HttpHeaderConstants.HOST, host);
            }
            headers.set(HttpHeaderConstants.CONNECTION, HttpHeaderValues.CLOSE);
            int contentLength = request.content().readableBytes();
            if (contentLength > 0) {
                headers.set(HttpHeaderConstants.CONTENT_LENGTH, Integer.toString(contentLength, 10));
            }

            HttpHeaders requestHeaders = request.headers();

            for (String name : headers.getNames()) {
                requestHeaders.set(name, headers.getAll(name));
            }

            ChannelFuture writeFuture = connectFuture.channel().writeAndFlush(request);
            writeFuture.addListener(f2 -> {
                if (!writeFuture.isSuccess()) {
                    writeFuture.channel().close();
                    error(fulfiller, writeFuture.cause());
                }
            });
        } else {
            connectFuture.channel().close();
            error(fulfiller, connectFuture.cause());
        }
    });
}

From source file:ratpack.test.handling.internal.DefaultRequestFixture.java

License:Apache License

private HandlingResult invoke(Handler handler, Registry registry, DefaultHandlingResult.ResultsHolder results)
        throws HandlerTimeoutException {
    Request request = new DefaultRequest(requestHeaders, HttpMethod.valueOf(method.toUpperCase()), uri,
            new InetSocketAddress(remoteHostAndPort.getHostText(), remoteHostAndPort.getPort()),
            new InetSocketAddress(localHostAndPort.getHostText(), localHostAndPort.getPort()), requestBody);

    try {/*from w w  w. j  av  a  2s. c o  m*/
        ServerConfig serverConfig = registry.get(ServerConfig.class);
        return new DefaultHandlingResult(request, results, responseHeaders, registry, timeout, handler);
    } catch (Exception e) {
        throw Exceptions.uncheck(e);
    } finally {
        registry.get(ExecController.class).close();
    }
}