Search in sources :

Example 1 with CookieStore

use of org.apache.http.client.CookieStore in project hive by apache.

the class HiveConnection method getHttpClient.

private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException {
    boolean isCookieEnabled = sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH) == null || (!JdbcConnectionParams.COOKIE_AUTH_FALSE.equalsIgnoreCase(sessConfMap.get(JdbcConnectionParams.COOKIE_AUTH)));
    String cookieName = sessConfMap.get(JdbcConnectionParams.COOKIE_NAME) == null ? JdbcConnectionParams.DEFAULT_COOKIE_NAMES_HS2 : sessConfMap.get(JdbcConnectionParams.COOKIE_NAME);
    CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null;
    HttpClientBuilder httpClientBuilder;
    // Request interceptor for any request pre-processing logic
    HttpRequestInterceptor requestInterceptor;
    Map<String, String> additionalHttpHeaders = new HashMap<String, String>();
    // Retrieve the additional HttpHeaders
    for (Map.Entry<String, String> entry : sessConfMap.entrySet()) {
        String key = entry.getKey();
        if (key.startsWith(JdbcConnectionParams.HTTP_HEADER_PREFIX)) {
            additionalHttpHeaders.put(key.substring(JdbcConnectionParams.HTTP_HEADER_PREFIX.length()), entry.getValue());
        }
    }
    // Configure http client for kerberos/password based authentication
    if (isKerberosAuthMode()) {
        /**
       * Add an interceptor which sets the appropriate header in the request.
       * It does the kerberos authentication and get the final service ticket,
       * for sending to the server before every request.
       * In https mode, the entire information is encrypted
       */
        requestInterceptor = new HttpKerberosRequestInterceptor(sessConfMap.get(JdbcConnectionParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders);
    } else {
        // Check for delegation token, if present add it in the header
        String tokenStr = getClientDelegationToken(sessConfMap);
        if (tokenStr != null) {
            requestInterceptor = new HttpTokenAuthInterceptor(tokenStr, cookieStore, cookieName, useSsl, additionalHttpHeaders);
        } else {
            /**
       * Add an interceptor to pass username/password in the header.
       * In https mode, the entire information is encrypted
       */
            requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders);
        }
    }
    // Configure http client for cookie based authentication
    if (isCookieEnabled) {
        // Create a http client with a retry mechanism when the server returns a status code of 401.
        httpClientBuilder = HttpClients.custom().setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {

            @Override
            public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) {
                int statusCode = response.getStatusLine().getStatusCode();
                boolean ret = statusCode == 401 && executionCount <= 1;
                // interceptor
                if (ret) {
                    context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE);
                }
                return ret;
            }

            @Override
            public long getRetryInterval() {
                // Immediate retry
                return 0;
            }
        });
    } else {
        httpClientBuilder = HttpClientBuilder.create();
    }
    // Add the request interceptor to the client builder
    httpClientBuilder.addInterceptorFirst(requestInterceptor);
    // Add an interceptor to add in an XSRF header
    httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor());
    // Configure http client for SSL
    if (useSsl) {
        String useTwoWaySSL = sessConfMap.get(JdbcConnectionParams.USE_TWO_WAY_SSL);
        String sslTrustStorePath = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE);
        String sslTrustStorePassword = sessConfMap.get(JdbcConnectionParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore;
        SSLConnectionSocketFactory socketFactory;
        SSLContext sslContext;
        /**
       * The code within the try block throws: SSLInitializationException, KeyStoreException,
       * IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException &
       * UnrecoverableKeyException. We don't want the client to retry on any of these,
       * hence we catch all and throw a SQLException.
       */
        try {
            if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(JdbcConnectionParams.TRUE)) {
                socketFactory = getTwoWaySSLSocketFactory();
            } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) {
                // Create a default socket factory based on standard JSSE trust material
                socketFactory = SSLConnectionSocketFactory.getSocketFactory();
            } else {
                // Pick trust store config from the given path
                sslTrustStore = KeyStore.getInstance(JdbcConnectionParams.SSL_TRUST_STORE_TYPE);
                try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) {
                    sslTrustStore.load(fis, sslTrustStorePassword.toCharArray());
                }
                sslContext = SSLContexts.custom().loadTrustMaterial(sslTrustStore, null).build();
                socketFactory = new SSLConnectionSocketFactory(sslContext, new DefaultHostnameVerifier(null));
            }
            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", socketFactory).build();
            httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        } catch (Exception e) {
            String msg = "Could not create an https connection to " + jdbcUriString + ". " + e.getMessage();
            throw new SQLException(msg, " 08S01", e);
        }
    }
    return httpClientBuilder.build();
}
Also used : HashMap(java.util.HashMap) SQLException(java.sql.SQLException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ServiceUnavailableRetryStrategy(org.apache.http.client.ServiceUnavailableRetryStrategy) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) DefaultHostnameVerifier(org.apache.http.conn.ssl.DefaultHostnameVerifier) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) Savepoint(java.sql.Savepoint) FileInputStream(java.io.FileInputStream) TTransportException(org.apache.thrift.transport.TTransportException) SQLFeatureNotSupportedException(java.sql.SQLFeatureNotSupportedException) SaslException(javax.security.sasl.SaslException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLClientInfoException(java.sql.SQLClientInfoException) SQLException(java.sql.SQLException) TException(org.apache.thrift.TException) IOException(java.io.IOException) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with CookieStore

use of org.apache.http.client.CookieStore in project nanohttpd by NanoHttpd.

the class CookieIntegrationTest method testNoCookies.

@Test
public void testNoCookies() throws Exception {
    HttpGet httpget = new HttpGet("http://localhost:8192/");
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    this.httpclient.execute(httpget, responseHandler);
    CookieStore cookies = this.httpclient.getCookieStore();
    assertEquals(0, cookies.getCookies().size());
}
Also used : CookieStore(org.apache.http.client.CookieStore) HttpGet(org.apache.http.client.methods.HttpGet) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) Test(org.junit.Test)

Example 3 with CookieStore

use of org.apache.http.client.CookieStore in project SmartAndroidSource by jaychou2012.

the class AbstractAjaxCallback method httpDo.

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException {
    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }
    }
    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }
    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, hr);
    }
    DefaultHttpClient client = getClient();
    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT);
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }
    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    request = hr;
    if (abort) {
        throw new IOException("Aborted");
    }
    HttpResponse response = client.execute(hr, context);
    byte[] data = null;
    String redirect = url;
    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;
    HttpEntity entity = response.getEntity();
    Header[] hs = response.getAllHeaders();
    HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length);
    for (Header h : hs) {
        responseHeaders.put(h.getName(), h.getValue());
    }
    setResponseHeaders(responseHeaders);
    File file = null;
    if (code < 200 || code >= 300) {
        try {
            if (entity != null) {
                InputStream is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);
                error = new String(s, "UTF-8");
                AQUtility.debug("error", error);
            }
        } catch (Exception e) {
            AQUtility.debug(e);
        }
    } else {
        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();
        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));
        OutputStream os = null;
        InputStream is = null;
        try {
            file = getPreFile();
            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }
            //AQUtility.time("copy");
            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());
            //AQUtility.timeEnd("copy", 0);
            os.flush();
            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }
        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file).client(client).context(context).headers(response.getAllHeaders());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DataOutputStream(java.io.DataOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHost(org.apache.http.HttpHost) BufferedOutputStream(java.io.BufferedOutputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Date(java.util.Date) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 4 with CookieStore

use of org.apache.http.client.CookieStore in project jersey by jersey.

the class UnderlyingCookieStoreAccessTest method testCookieStoreInstanceAccess.

@Test
public void testCookieStoreInstanceAccess() {
    final Client client = ClientBuilder.newClient(new ClientConfig().connectorProvider(new ApacheConnectorProvider()));
    final CookieStore csOnClient = ApacheConnectorProvider.getCookieStore(client);
    // important: the web target instance in this test must be only created AFTER the client has been pre-initialized
    // (see org.glassfish.jersey.client.Initializable.preInitialize method). This is here achieved by calling the
    // connector provider's static getCookieStore method above.
    final WebTarget target = client.target("http://localhost/");
    final CookieStore csOnTarget = ApacheConnectorProvider.getCookieStore(target);
    assertNotNull("CookieStore instance set on JerseyClient should not be null.", csOnClient);
    assertNotNull("CookieStore instance set on JerseyWebTarget should not be null.", csOnTarget);
    assertSame("CookieStore instance set on JerseyClient should be the same instance as the one set on JerseyWebTarget" + "(provided the target instance has not been further configured).", csOnClient, csOnTarget);
}
Also used : CookieStore(org.apache.http.client.CookieStore) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) ClientConfig(org.glassfish.jersey.client.ClientConfig) Test(org.junit.Test)

Example 5 with CookieStore

use of org.apache.http.client.CookieStore in project robovm by robovm.

the class RequestAddCookies method process.

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }
    // Obtain cookie store
    CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
    if (cookieStore == null) {
        this.log.info("Cookie store not available in HTTP context");
        return;
    }
    // Obtain the registry of cookie specs
    CookieSpecRegistry registry = (CookieSpecRegistry) context.getAttribute(ClientContext.COOKIESPEC_REGISTRY);
    if (registry == null) {
        this.log.info("CookieSpec registry not available in HTTP context");
        return;
    }
    // Obtain the target host (required)
    HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    if (targetHost == null) {
        throw new IllegalStateException("Target host not specified in HTTP context");
    }
    // Obtain the client connection (required)
    ManagedClientConnection conn = (ManagedClientConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION);
    if (conn == null) {
        throw new IllegalStateException("Client connection not specified in HTTP context");
    }
    String policy = HttpClientParams.getCookiePolicy(request.getParams());
    if (this.log.isDebugEnabled()) {
        this.log.debug("CookieSpec selected: " + policy);
    }
    URI requestURI;
    if (request instanceof HttpUriRequest) {
        requestURI = ((HttpUriRequest) request).getURI();
    } else {
        try {
            requestURI = new URI(request.getRequestLine().getUri());
        } catch (URISyntaxException ex) {
            throw new ProtocolException("Invalid request URI: " + request.getRequestLine().getUri(), ex);
        }
    }
    String hostName = targetHost.getHostName();
    int port = targetHost.getPort();
    if (port < 0) {
        port = conn.getRemotePort();
    }
    CookieOrigin cookieOrigin = new CookieOrigin(hostName, port, requestURI.getPath(), conn.isSecure());
    // Get an instance of the selected cookie policy
    CookieSpec cookieSpec = registry.getCookieSpec(policy, request.getParams());
    // Get all cookies available in the HTTP state
    List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies());
    // Find cookies matching the given origin
    List<Cookie> matchedCookies = new ArrayList<Cookie>();
    for (Cookie cookie : cookies) {
        if (cookieSpec.match(cookie, cookieOrigin)) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Cookie " + cookie + " match " + cookieOrigin);
            }
            matchedCookies.add(cookie);
        }
    }
    // Generate Cookie request headers
    if (!matchedCookies.isEmpty()) {
        List<Header> headers = cookieSpec.formatCookies(matchedCookies);
        for (Header header : headers) {
            request.addHeader(header);
        }
    }
    int ver = cookieSpec.getVersion();
    if (ver > 0) {
        boolean needVersionHeader = false;
        for (Cookie cookie : matchedCookies) {
            if (ver != cookie.getVersion()) {
                needVersionHeader = true;
            }
        }
        if (needVersionHeader) {
            Header header = cookieSpec.getVersionHeader();
            if (header != null) {
                // Advertise cookie version support
                request.addHeader(header);
            }
        }
    }
    // Stick the CookieSpec and CookieOrigin instances to the HTTP context
    // so they could be obtained by the response interceptor
    context.setAttribute(ClientContext.COOKIE_SPEC, cookieSpec);
    context.setAttribute(ClientContext.COOKIE_ORIGIN, cookieOrigin);
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) Cookie(org.apache.http.cookie.Cookie) ProtocolException(org.apache.http.ProtocolException) ManagedClientConnection(org.apache.http.conn.ManagedClientConnection) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) CookieStore(org.apache.http.client.CookieStore) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) CookieSpec(org.apache.http.cookie.CookieSpec) CookieOrigin(org.apache.http.cookie.CookieOrigin) CookieSpecRegistry(org.apache.http.cookie.CookieSpecRegistry)

Aggregations

CookieStore (org.apache.http.client.CookieStore)25 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)12 IOException (java.io.IOException)7 HttpResponse (org.apache.http.HttpResponse)7 HttpGet (org.apache.http.client.methods.HttpGet)7 HttpHost (org.apache.http.HttpHost)6 CookieOrigin (org.apache.http.cookie.CookieOrigin)6 CookieSpec (org.apache.http.cookie.CookieSpec)6 ArrayList (java.util.ArrayList)5 ClientProtocolException (org.apache.http.client.ClientProtocolException)5 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)5 Cookie (org.apache.http.cookie.Cookie)5 BasicHttpContext (org.apache.http.protocol.BasicHttpContext)5 Test (org.junit.Test)5 URI (java.net.URI)4 Date (java.util.Date)4 Header (org.apache.http.Header)4 HttpEntity (org.apache.http.HttpEntity)4 HttpClient (org.apache.http.client.HttpClient)4 HttpContext (org.apache.http.protocol.HttpContext)4