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:net.nikore.gozer.router.RibbonUtils.java

License:Apache License

public HttpMethod getVerb(HttpServletRequest request) {
    String method = request.getMethod();

    if (method == null) {
        return HttpMethod.GET;
    } else {// w  w w .  j  a  v  a  2s . co m
        return HttpMethod.valueOf(method);
    }
}

From source file:org.apache.camel.component.netty4.http.NettyHttpHelper.java

License:Apache License

/**
 * Creates the {@link HttpMethod} to use to call the remote server, often either its GET or POST.
 *
 * @param message  the Camel message//from  w  w  w  .j  a va  2 s  . c  o  m
 * @return the created method
 */
public static HttpMethod createMethod(Message message, boolean hasPayload) {
    // use header first
    HttpMethod m = message.getHeader(Exchange.HTTP_METHOD, HttpMethod.class);
    if (m != null) {
        return m;
    }
    String name = message.getHeader(Exchange.HTTP_METHOD, String.class);
    if (name != null) {
        return HttpMethod.valueOf(name);
    }

    if (hasPayload) {
        // use POST if we have payload
        return HttpMethod.POST;
    } else {
        // fallback to GET
        return HttpMethod.GET;
    }
}

From source file:org.apache.cxf.transport.http.netty.client.NettyHttpClientRequest.java

License:Apache License

public void createRequest(ByteBuf content) {
    this.request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(method),
            uri.getPath().toString(), content);
    // setup the default headers
    request.headers().set("Connection", "keep-alive");
    request.headers().set("Host", uri.getHost() + ":"
            + (uri.getPort() != -1 ? uri.getPort() : "http".equals(uri.getScheme()) ? 80 : 443));
}

From source file:org.asynchttpclient.netty.request.NettyRequestFactory.java

License:Open Source License

public NettyRequest newNettyRequest(Request request, boolean forceConnect, ProxyServer proxyServer, Realm realm,
        Realm proxyRealm) {//from  w  w  w  .ja  v a  2s.c o  m

    Uri uri = request.getUri();
    HttpMethod method = forceConnect ? HttpMethod.CONNECT : HttpMethod.valueOf(request.getMethod());
    boolean connect = method == HttpMethod.CONNECT;

    HttpVersion httpVersion = HttpVersion.HTTP_1_1;
    String requestUri = requestUri(uri, proxyServer, connect);

    NettyBody body = body(request, connect);

    HttpRequest httpRequest;
    NettyRequest nettyRequest;
    if (body instanceof NettyDirectBody) {
        ByteBuf buf = NettyDirectBody.class.cast(body).byteBuf();
        httpRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri, buf);
        // body is passed as null as it's written directly with the request
        nettyRequest = new NettyRequest(httpRequest, null);

    } else if (body == null) {
        httpRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri);
        nettyRequest = new NettyRequest(httpRequest, null);

    } else {
        httpRequest = new DefaultHttpRequest(httpVersion, method, requestUri);
        nettyRequest = new NettyRequest(httpRequest, body);
    }

    HttpHeaders headers = httpRequest.headers();

    if (connect) {
        // assign proxy-auth as configured on request
        headers.set(PROXY_AUTHORIZATION, request.getHeaders().getAll(PROXY_AUTHORIZATION));

    } else {
        // assign headers as configured on request
        headers.set(request.getHeaders());

        if (isNonEmpty(request.getCookies()))
            headers.set(COOKIE, CookieEncoder.encode(request.getCookies()));

        String userDefinedAcceptEncoding = headers.get(ACCEPT_ENCODING);
        if (userDefinedAcceptEncoding != null) {
            // we don't support Brotly ATM
            if (userDefinedAcceptEncoding.endsWith(BROTLY_ACCEPT_ENCODING_SUFFIX)) {
                headers.set(ACCEPT_ENCODING, userDefinedAcceptEncoding.subSequence(0,
                        userDefinedAcceptEncoding.length() - BROTLY_ACCEPT_ENCODING_SUFFIX.length()));
            }

        } else if (config.isCompressionEnforced()) {
            headers.set(ACCEPT_ENCODING, GZIP_DEFLATE);
        }
    }

    if (body != null) {
        if (body.getContentLength() < 0)
            headers.set(TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
        else
            headers.set(CONTENT_LENGTH, body.getContentLength());

        if (body.getContentType() != null)
            headers.set(CONTENT_TYPE, body.getContentType());
    }

    // connection header and friends
    if (!connect && uri.isWebSocket()) {
        headers.set(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET)//
                .set(CONNECTION, HttpHeaders.Values.UPGRADE)//
                .set(ORIGIN, "http://" + uri.getHost() + ":" + uri.getExplicitPort())//
                .set(SEC_WEBSOCKET_KEY, getKey())//
                .set(SEC_WEBSOCKET_VERSION, "13");

    } else if (!headers.contains(CONNECTION)) {
        String connectionHeaderValue = connectionHeader(config.isKeepAlive(), httpVersion);
        if (connectionHeaderValue != null)
            headers.set(CONNECTION, connectionHeaderValue);
    }

    if (!headers.contains(HOST))
        headers.set(HOST, hostHeader(request, uri));

    // don't override authorization but append
    addAuthorizationHeader(headers, perRequestAuthorizationHeader(realm));
    // only set proxy auth on request over plain HTTP, or when performing CONNECT
    if (!uri.isSecured() || connect) {
        setProxyAuthorizationHeader(headers, perRequestProxyAuthorizationHeader(proxyRealm));
    }

    // Add default accept headers
    if (!headers.contains(ACCEPT))
        headers.set(ACCEPT, "*/*");

    // Add default user agent
    if (!headers.contains(USER_AGENT) && config.getUserAgent() != null)
        headers.set(USER_AGENT, config.getUserAgent());

    return nettyRequest;
}

From source file:org.asynchttpclient.providers.netty.request.NettyRequestFactory.java

License:Apache License

public NettyRequest newNettyRequest(Request request, URI uri, boolean forceConnect, ProxyServer proxyServer)
        throws IOException {

    HttpMethod method = forceConnect ? HttpMethod.CONNECT : HttpMethod.valueOf(request.getMethod());
    HttpVersion httpVersion = method == HttpMethod.CONNECT ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;
    String requestUri = requestUri(uri, proxyServer, method);

    NettyBody body = body(request, method);

    HttpRequest httpRequest;/* www. j  a  va2 s .c om*/
    NettyRequest nettyRequest;
    if (body instanceof NettyByteArrayBody) {
        byte[] bytes = NettyByteArrayBody.class.cast(body).getBytes();
        httpRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri,
                Unpooled.wrappedBuffer(bytes));
        // body is passed as null as it's written directly with the request
        nettyRequest = new NettyRequest(httpRequest, null);

    } else if (body == null) {
        httpRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri);
        nettyRequest = new NettyRequest(httpRequest, null);

    } else {
        httpRequest = new DefaultHttpRequest(httpVersion, method, requestUri);
        nettyRequest = new NettyRequest(httpRequest, body);
    }

    if (method != HttpMethod.CONNECT) {
        // assign headers as configured on request
        for (Entry<String, List<String>> header : request.getHeaders()) {
            httpRequest.headers().set(header.getKey(), header.getValue());
        }

        if (isNonEmpty(request.getCookies()))
            httpRequest.headers().set(HttpHeaders.Names.COOKIE, CookieEncoder.encode(request.getCookies()));

        if (config.isCompressionEnabled())
            httpRequest.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, GZIP_DEFLATE);
    }

    if (body != null) {
        if (body.getContentLength() >= 0)
            httpRequest.headers().set(HttpHeaders.Names.CONTENT_LENGTH, body.getContentLength());
        else
            httpRequest.headers().set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);

        if (body.getContentType() != null)
            httpRequest.headers().set(HttpHeaders.Names.CONTENT_TYPE, body.getContentType());
    }

    // connection header and friends
    boolean webSocket = isWebSocket(uri.getScheme());
    if (method != HttpMethod.CONNECT && webSocket) {
        httpRequest.headers().set(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
        httpRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
        httpRequest.headers().set(HttpHeaders.Names.ORIGIN, "http://" + uri.getHost() + ":"
                + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
        httpRequest.headers().set(HttpHeaders.Names.SEC_WEBSOCKET_KEY, WebSocketUtil.getKey());
        httpRequest.headers().set(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, "13");

    } else if (!httpRequest.headers().contains(HttpHeaders.Names.CONNECTION)) {
        httpRequest.headers().set(HttpHeaders.Names.CONNECTION,
                AsyncHttpProviderUtils.keepAliveHeaderValue(config));
    }

    Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();

    String hostHeader = hostHeader(request, uri, realm);
    if (hostHeader != null)
        httpRequest.headers().set(HttpHeaders.Names.HOST, hostHeader);

    String authorizationHeader = authorizationHeader(request, uri, proxyServer, realm);
    if (authorizationHeader != null)
        // don't override authorization but append
        httpRequest.headers().add(HttpHeaders.Names.AUTHORIZATION, authorizationHeader);

    String proxyAuthorizationHeader = proxyAuthorizationHeader(request, proxyServer, method);
    if (proxyAuthorizationHeader != null)
        httpRequest.headers().set(HttpHeaders.Names.PROXY_AUTHORIZATION, proxyAuthorizationHeader);

    // Add default accept headers
    if (!httpRequest.headers().contains(HttpHeaders.Names.ACCEPT))
        httpRequest.headers().set(HttpHeaders.Names.ACCEPT, "*/*");

    // Add default user agent
    if (!httpRequest.headers().contains(HttpHeaders.Names.USER_AGENT)) {
        String userAgent = config.getUserAgent() != null ? config.getUserAgent()
                : AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config);
        httpRequest.headers().set(HttpHeaders.Names.USER_AGENT, userAgent);
    }

    return nettyRequest;
}

From source file:org.asynchttpclient.providers.netty.request.NettyRequests.java

License:Apache License

public static HttpRequest newNettyRequest(AsyncHttpClientConfig config, Request request, URI uri,
        boolean allowConnect, ProxyServer proxyServer) throws IOException {

    HttpMethod method = null;//  w  w  w .  j  av a  2 s. c om
    if (allowConnect && proxyServer != null && isSecure(uri))
        method = HttpMethod.CONNECT;
    else
        method = HttpMethod.valueOf(request.getMethod());

    String host = null;
    HttpVersion httpVersion;
    String requestUri;
    Map<String, Object> headers = new HashMap<String, Object>();
    String authorizationHeader = null;
    ByteBuf content = null;
    boolean webSocket = isWebSocket(uri);

    if (request.getVirtualHost() != null) {
        host = request.getVirtualHost();
    } else {
        host = AsyncHttpProviderUtils.getHost(uri);
    }

    if (method == HttpMethod.CONNECT) {
        httpVersion = HttpVersion.HTTP_1_0;
        requestUri = AsyncHttpProviderUtils.getAuthority(uri);
    } else {
        httpVersion = HttpVersion.HTTP_1_1;
        if (proxyServer != null && !(isSecure(uri) && config.isUseRelativeURIsWithSSLProxies()))
            requestUri = uri.toString();
        else if (uri.getRawQuery() != null)
            requestUri = uri.getRawPath() + "?" + uri.getRawQuery();
        else
            requestUri = uri.getRawPath();
    }

    if (webSocket) {
        headers.put(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET);
        headers.put(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE);
        headers.put(HttpHeaders.Names.ORIGIN, "http://" + uri.getHost() + ":"
                + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()));
        headers.put(HttpHeaders.Names.SEC_WEBSOCKET_KEY, WebSocketUtil.getKey());
        headers.put(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, "13");
    }

    if (host != null) {
        if (request.getVirtualHost() != null || uri.getPort() == -1) {
            headers.put(HttpHeaders.Names.HOST, host);
        } else {
            headers.put(HttpHeaders.Names.HOST, host + ":" + uri.getPort());
        }
    } else {
        host = "127.0.0.1";
    }

    if (method != HttpMethod.CONNECT) {
        if (config.isCompressionEnabled()) {
            headers.put(HttpHeaders.Names.ACCEPT_ENCODING, GZIP_DEFLATE);
        }
    } else {
        List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
        if (isNTLM(auth)) {
            headers.put(HttpHeaders.Names.PROXY_AUTHORIZATION, auth.get(0));
        }
    }
    Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();

    if (realm != null && realm.getUsePreemptiveAuth()) {

        String domain = realm.getNtlmDomain();
        if (proxyServer != null && proxyServer.getNtlmDomain() != null) {
            domain = proxyServer.getNtlmDomain();
        }

        String authHost = realm.getNtlmHost();
        if (proxyServer != null && proxyServer.getHost() != null) {
            host = proxyServer.getHost();
        }

        switch (realm.getAuthScheme()) {
        case BASIC:
            authorizationHeader = AuthenticatorUtils.computeBasicAuthentication(realm);
            break;
        case DIGEST:
            if (isNonEmpty(realm.getNonce())) {
                try {
                    authorizationHeader = AuthenticatorUtils.computeDigestAuthentication(realm);
                } catch (NoSuchAlgorithmException e) {
                    throw new SecurityException(e);
                }
            }
            break;
        case NTLM:
            try {
                String msg = NTLMEngine.INSTANCE.generateType1Msg("NTLM " + domain, authHost);
                authorizationHeader = "NTLM " + msg;
            } catch (NTLMEngineException e) {
                throw new IOException(e);
            }
            break;
        case KERBEROS:
        case SPNEGO:
            String challengeHeader = null;
            String server = proxyServer == null ? host : proxyServer.getHost();
            try {
                challengeHeader = SpnegoEngine.instance().generateToken(server);
            } catch (Throwable e) {
                throw new IOException(e);
            }
            authorizationHeader = "Negotiate " + challengeHeader;
            break;
        case NONE:
            break;
        default:
            throw new IllegalStateException("Invalid Authentication " + realm);
        }
    }

    if (!webSocket && !request.getHeaders().containsKey(HttpHeaders.Names.CONNECTION)) {
        headers.put(HttpHeaders.Names.CONNECTION, AsyncHttpProviderUtils.keepAliveHeaderValue(config));
    }

    if (proxyServer != null) {
        // FIXME Wikipedia says that Proxy-Connection was a misunderstanding of Connection http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
        if (!request.getHeaders().containsKey("Proxy-Connection")) {
            headers.put("Proxy-Connection", AsyncHttpProviderUtils.keepAliveHeaderValue(config));
        }

        if (proxyServer.getPrincipal() != null) {
            if (isNonEmpty(proxyServer.getNtlmDomain())) {

                List<String> auth = request.getHeaders().get(HttpHeaders.Names.PROXY_AUTHORIZATION);
                if (!isNTLM(auth)) {
                    try {
                        String msg = NTLMEngine.INSTANCE.generateType1Msg(proxyServer.getNtlmDomain(),
                                proxyServer.getHost());
                        headers.put(HttpHeaders.Names.PROXY_AUTHORIZATION, "NTLM " + msg);
                    } catch (NTLMEngineException e) {
                        IOException ie = new IOException();
                        ie.initCause(e);
                        throw ie;
                    }
                }
            } else {
                headers.put(HttpHeaders.Names.PROXY_AUTHORIZATION,
                        AuthenticatorUtils.computeBasicAuthentication(proxyServer));
            }
        }
    }

    // Add default accept headers
    if (!request.getHeaders().containsKey(HttpHeaders.Names.ACCEPT)) {
        headers.put(HttpHeaders.Names.ACCEPT, "*/*");
    }

    String userAgentHeader = request.getHeaders().getFirstValue(HttpHeaders.Names.USER_AGENT);
    if (userAgentHeader != null) {
        headers.put(HttpHeaders.Names.USER_AGENT, userAgentHeader);
    } else if (config.getUserAgent() != null) {
        headers.put(HttpHeaders.Names.USER_AGENT, config.getUserAgent());
    } else {
        headers.put(HttpHeaders.Names.USER_AGENT,
                AsyncHttpProviderUtils.constructUserAgent(NettyAsyncHttpProvider.class, config));
    }

    boolean hasDeferredContent = false;
    if (method != HttpMethod.CONNECT) {
        if (isNonEmpty(request.getCookies())) {
            headers.put(HttpHeaders.Names.COOKIE,
                    CookieEncoder.encodeClientSide(request.getCookies(), config.isRfc6265CookieEncoding()));
        }

        String bodyCharset = request.getBodyEncoding() == null ? DEFAULT_CHARSET : request.getBodyEncoding();

        if (request.getByteData() != null) {
            headers.put(HttpHeaders.Names.CONTENT_LENGTH, request.getByteData().length);
            content = Unpooled.wrappedBuffer(request.getByteData());

        } else if (request.getStringData() != null) {
            byte[] bytes = request.getStringData().getBytes(bodyCharset);
            headers.put(HttpHeaders.Names.CONTENT_LENGTH, bytes.length);
            content = Unpooled.wrappedBuffer(bytes);

        } else if (request.getStreamData() != null) {
            hasDeferredContent = true;
            headers.put(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);

        } else if (isNonEmpty(request.getParams())) {
            StringBuilder sb = new StringBuilder();
            for (final Entry<String, List<String>> paramEntry : request.getParams()) {
                final String key = paramEntry.getKey();
                for (final String value : paramEntry.getValue()) {
                    UTF8UrlEncoder.appendEncoded(sb, key);
                    sb.append("=");
                    UTF8UrlEncoder.appendEncoded(sb, value);
                    sb.append("&");
                }
            }
            sb.setLength(sb.length() - 1);
            byte[] bytes = sb.toString().getBytes(bodyCharset);
            headers.put(HttpHeaders.Names.CONTENT_LENGTH, bytes.length);
            content = Unpooled.wrappedBuffer(bytes);

            if (!request.getHeaders().containsKey(HttpHeaders.Names.CONTENT_TYPE)) {
                headers.put(HttpHeaders.Names.CONTENT_TYPE,
                        HttpHeaders.Values.APPLICATION_X_WWW_FORM_URLENCODED);
            }

        } else if (request.getParts() != null) {
            // FIXME use Netty multipart
            MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(),
                    request.getHeaders());

            headers.put(HttpHeaders.Names.CONTENT_TYPE, mre.getContentType());
            if (mre.getContentLength() >= 0) {
                headers.put(HttpHeaders.Names.CONTENT_LENGTH, mre.getContentLength());
            }
            hasDeferredContent = true;

        } else if (request.getFile() != null) {
            File file = request.getFile();
            if (!file.isFile()) {
                throw new IOException(
                        String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
            }
            headers.put(HttpHeaders.Names.CONTENT_LENGTH, file.length());
            hasDeferredContent = true;

        } else if (request.getBodyGenerator() != null) {
            hasDeferredContent = true;
        }
    }

    HttpRequest nettyRequest;
    if (hasDeferredContent) {
        nettyRequest = new DefaultHttpRequest(httpVersion, method, requestUri);
    } else if (content != null) {
        nettyRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri, content);
    } else {
        nettyRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri);
    }

    // assign headers as configured on request
    if (method != HttpMethod.CONNECT) {
        for (Entry<String, List<String>> header : request.getHeaders()) {
            nettyRequest.headers().set(header.getKey(), header.getValue());
        }
    }

    // override with computed ones
    for (Entry<String, Object> header : headers.entrySet()) {
        nettyRequest.headers().set(header.getKey(), header.getValue());
    }

    if (authorizationHeader != null) {
        // don't override authorization but append
        nettyRequest.headers().add(HttpHeaders.Names.AUTHORIZATION, authorizationHeader);
    }

    return nettyRequest;
}

From source file:org.asynchttpclient.providers.netty4.request.NettyRequestFactory.java

License:Open Source License

public NettyRequest newNettyRequest(Request request, Uri uri, boolean forceConnect, ProxyServer proxyServer)
        throws IOException {

    HttpMethod method = forceConnect ? HttpMethod.CONNECT : HttpMethod.valueOf(request.getMethod());
    HttpVersion httpVersion = method == HttpMethod.CONNECT ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;
    String requestUri = requestUri(uri, proxyServer, method);

    NettyBody body = body(request, method);

    HttpRequest httpRequest;//  ww w . j  a va2 s .  co m
    NettyRequest nettyRequest;
    if (body instanceof NettyDirectBody) {
        ByteBuf buf = NettyDirectBody.class.cast(body).byteBuf();
        httpRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri, buf);
        // body is passed as null as it's written directly with the request
        nettyRequest = new NettyRequest(httpRequest, null);

    } else if (body == null) {
        httpRequest = new DefaultFullHttpRequest(httpVersion, method, requestUri);
        nettyRequest = new NettyRequest(httpRequest, null);

    } else {
        httpRequest = new DefaultHttpRequest(httpVersion, method, requestUri);
        nettyRequest = new NettyRequest(httpRequest, body);
    }

    HttpHeaders headers = httpRequest.headers();

    if (method != HttpMethod.CONNECT) {
        // assign headers as configured on request
        for (Entry<String, List<String>> header : request.getHeaders()) {
            headers.set(header.getKey(), header.getValue());
        }

        if (isNonEmpty(request.getCookies()))
            headers.set(HttpHeaders.Names.COOKIE, CookieEncoder.encode(request.getCookies()));

        if (config.isCompressionEnforced() && !headers.contains(HttpHeaders.Names.ACCEPT_ENCODING))
            headers.set(HttpHeaders.Names.ACCEPT_ENCODING, GZIP_DEFLATE);
    }

    if (body != null) {
        if (body.getContentLength() < 0)
            headers.set(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
        else
            headers.set(HttpHeaders.Names.CONTENT_LENGTH, body.getContentLength());

        if (body.getContentType() != null)
            headers.set(HttpHeaders.Names.CONTENT_TYPE, body.getContentType());
    }

    // connection header and friends
    boolean webSocket = isWebSocket(uri.getScheme());
    if (method != HttpMethod.CONNECT && webSocket) {
        headers.set(HttpHeaders.Names.UPGRADE, HttpHeaders.Values.WEBSOCKET)//
                .set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.UPGRADE)//
                .set(HttpHeaders.Names.ORIGIN,
                        "http://" + uri.getHost() + ":"
                                + (uri.getPort() == -1 ? isSecure(uri.getScheme()) ? 443 : 80 : uri.getPort()))//
                .set(HttpHeaders.Names.SEC_WEBSOCKET_KEY, getKey())//
                .set(HttpHeaders.Names.SEC_WEBSOCKET_VERSION, "13");

    } else if (!headers.contains(HttpHeaders.Names.CONNECTION)) {
        headers.set(HttpHeaders.Names.CONNECTION, keepAliveHeaderValue(config));
    }

    if (!headers.contains(HttpHeaders.Names.HOST))
        headers.set(HttpHeaders.Names.HOST, hostHeader(request, uri));

    Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();

    // don't override authorization but append
    addAuthorizationHeader(headers, systematicAuthorizationHeader(request, uri, proxyServer, realm));

    setProxyAuthorizationHeader(headers, systematicProxyAuthorizationHeader(request, proxyServer, method));

    // Add default accept headers
    if (!headers.contains(HttpHeaders.Names.ACCEPT))
        headers.set(HttpHeaders.Names.ACCEPT, "*/*");

    // Add default user agent
    if (!headers.contains(HttpHeaders.Names.USER_AGENT) && config.getUserAgent() != null)
        headers.set(HttpHeaders.Names.USER_AGENT, config.getUserAgent());

    return nettyRequest;
}

From source file:org.fiware.kiara.transport.http.HttpRequestMessage.java

License:Open Source License

@Override
public TransportMessage set(String name, Object value) {
    if (TransportMessage.Names.CONTENT_TYPE.equals(name)) {
        request.headers().set(HttpHeaders.Names.CONTENT_TYPE, value);
    } else if (TransportMessage.Names.SESSION_ID.equals(name)) {
        request.headers().set("x-kiara-session", value);
    } else if (HttpMessage.Names.REQUEST_URI.equals(name)) {
        request.setUri((String) value);
    } else if (HttpMessage.Names.HTTP_METHOD.equals(name)) {
        request.setMethod(HttpMethod.valueOf(name));
    }//from  w ww  .j av a  2s  .  co  m
    return this;
}

From source file:org.glassfish.jersey.netty.connector.NettyConnector.java

License:Open Source License

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {

    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();

    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort()
            : "https".equals(requestUri.getScheme()) ? 443 : 80;

    try {//ww w . ja v a  2  s.c  o m
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();

                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true,
                            ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }

                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);

                    final String userName = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_PASSWORD, String.class);

                    p.addLast(new HttpProxyHandler(
                            new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()),
                            userName, password));
                }

                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback,
                        settableFuture));
            }
        });

        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(),
                ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }

        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();

        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future)
                    throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };

        ch.closeFuture().addListener(closeListener);

        HttpRequest nettyRequest;

        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }

        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }

        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());

        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }

        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);

            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });

            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);

                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });

            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);

            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }

    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }

    return settableFuture;
}

From source file:org.jooby.internal.netty.NettyPush.java

License:Apache License

@Override
public void push(final String method, final String path, final Map<String, Object> headers) {
    ctx.channel().eventLoop().execute(() -> {
        AsciiString streamIdHeader = HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text();
        Http2Connection connection = encoder.connection();
        int nextStreamId = connection.local().incrementAndGetNextStreamId();
        Http2Headers h2headers = new DefaultHttp2Headers().path(path).method(method).authority(authority)
                .scheme(scheme);/*www  .  j av  a 2s .c o m*/
        headers.forEach((n, v) -> h2headers.add(n, v.toString()));
        encoder.writePushPromise(ctx, streamId, nextStreamId, h2headers, 0, ctx.newPromise());

        // TODO: Is there another way of handling a push promise?
        DefaultFullHttpRequest pushRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                HttpMethod.valueOf(method.toUpperCase()), path, Unpooled.EMPTY_BUFFER,
                new DefaultHttpHeaders(false).set(streamIdHeader, nextStreamId), EmptyHttpHeaders.INSTANCE);
        ctx.pipeline().fireChannelRead(pushRequest);
        ctx.pipeline().fireChannelReadComplete();
    });
}