List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
From source file:net.geoprism.dashboard.DashboardMap.java
/** * Makes a getMap request to geoserver and returns the response as a ByteArrayOutputStream * //from w ww . j a v a 2 s . c om * @throws NoSuchAlgorithmException * * @requestURL = geoserver getMap() or getLegendGraphic() request url */ private byte[] requestGeoserverImage(String requestURL) { InputStream inStream = null; ByteArrayOutputStream outStream = null; CloseableHttpResponse response = null; CloseableHttpClient client = null; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // StorePath and StorePass must be set for the systems keystore trustStore.load(new FileInputStream(GeoserverProperties.getGeoserverKeystorePath()), GeoserverProperties.getGeoserverKeystorePass().toCharArray()); SSLContext sslcontext = SSLContexts.custom() .loadKeyMaterial(trustStore, GeoserverProperties.getGeoserverKeystorePass().toCharArray()) .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); // // TODO: socket factory load once ever // SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); client = HttpClients.custom() // Allow all hostnames regardless of what is specified in the certificate .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) // Use the provided SSL socket factory .setSSLSocketFactory(factory) // Set a default cookie store which will be used in all of the requests .setDefaultCookieStore(new BasicCookieStore()).build(); HttpGet method = new HttpGet(requestURL); response = client.execute(method); inStream = response.getEntity().getContent(); outStream = new ByteArrayOutputStream(); // Copy the input stream to the output stream IOUtils.copy(inStream, outStream); } catch (MalformedURLException e) { String error = "The URL is not formated correctly."; throw new ProgrammingErrorException(error, e); } catch (IOException e) { String error = "Could not make the request to the map server."; throw new ProgrammingErrorException(error, e); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } if (outStream != null) { try { outStream.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } if (response != null) { try { response.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } if (client != null) { try { client.close(); } catch (IOException e) { String error = "Could not close stream."; throw new ProgrammingErrorException(error, e); } } } return outStream.toByteArray(); }
From source file:net.www_eee.portal.channels.ProxyChannel.java
/** * Construct the {@link org.apache.http.client.CookieStore CookieStore} to be used for * {@linkplain #createProxyClient(Page.Request) creating} the {@link HttpClient}. * //from w ww. j a v a2s . c o m * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed. * @return The created {@link org.apache.http.client.CookieStore CookieStore}. * @throws WWWEEEPortal.Exception If a problem occurred while determining the result. * @see #createProxyClient(Page.Request) * @see #PROXY_CLIENT_COOKIE_STORE_HOOK */ protected org.apache.http.client.CookieStore createProxyClientCookieStore(final Page.Request pageRequest) throws WWWEEEPortal.Exception { org.apache.http.client.CookieStore proxyClientCookieStore = PROXY_CLIENT_COOKIE_STORE_HOOK.value(plugins, null, pageRequest); if (proxyClientCookieStore == null) { proxyClientCookieStore = new BasicCookieStore(); } proxyClientCookieStore = PROXY_CLIENT_COOKIE_STORE_HOOK.requireFilteredResult( PROXY_CLIENT_COOKIE_STORE_HOOK.filter(plugins, null, pageRequest, proxyClientCookieStore)); return proxyClientCookieStore; }
From source file:org.activiti.designer.eclipse.navigator.cloudrepo.ActivitiCloudEditorUtil.java
public static CloseableHttpClient getAuthenticatedClient() { // Get settings from preferences String url = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_URL); String userName = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_USERNAME); String password = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_PASSWORD); String cookieString = PreferencesUtil.getStringPreference(Preferences.ACTIVITI_CLOUD_EDITOR_COOKIE); Cookie cookie = null;//from w w w . ja va 2 s. com if (StringUtils.isNotEmpty(cookieString)) { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( hexStringToByteArray(cookieString)); try { ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); cookie = (BasicClientCookie) objectInputStream.readObject(); } catch (Exception e) { e.printStackTrace(); } } // Build session BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); if (cookie == null) { try { HttpUriRequest login = RequestBuilder.post().setUri(new URI(url + "/rest/app/authentication")) .addParameter("j_username", userName).addParameter("j_password", password) .addParameter("_spring_security_remember_me", "true").build(); CloseableHttpResponse response = httpClient.execute(login); try { EntityUtils.consume(response.getEntity()); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { // nothing to do } else { Cookie reponseCookie = cookies.get(0); ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream outputStream = new ObjectOutputStream(os); outputStream.writeObject(reponseCookie); PreferencesUtil.getActivitiDesignerPreferenceStore().setValue( Preferences.ACTIVITI_CLOUD_EDITOR_COOKIE.getPreferenceId(), byteArrayToHexString(os.toByteArray())); InstanceScope.INSTANCE.getNode(ActivitiPlugin.PLUGIN_ID).flush(); } } finally { response.close(); } } catch (Exception e) { Logger.logError("Error authenticating " + userName, e); } } else { // setting cookie from cache cookieStore.addCookie(cookie); } return httpClient; }
From source file:org.apache.hive.jdbc.HiveConnection.java
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());/* w ww. j a v a 2 s .c o m*/ } } // 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; // Set the context attribute to true which will be interpreted by the request // 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(); } // In case the server's idletimeout is set to a lower value, it might close it's side of // connection. However we retry one more time on NoHttpResponseException httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount > 1) { LOG.info("Retry attempts to connect to server exceeded."); return false; } if (exception instanceof org.apache.http.NoHttpResponseException) { LOG.info("Could not connect to the server. Retrying one more time."); return true; } return false; } }); // 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(); }
From source file:org.apache.http.impl.client.AbstractHttpClient.java
protected CookieStore createCookieStore() { return new BasicCookieStore(); }
From source file:org.brunocvcunha.instagram4j.Instagram4j.java
/** * Setup some variables/* w w w .j av a 2 s. c om*/ */ public void setup() { log.info("Setup..."); if (StringUtils.isEmpty(this.username)) { throw new IllegalArgumentException("Username is mandatory."); } if (StringUtils.isEmpty(this.password)) { throw new IllegalArgumentException("Password is mandatory."); } this.deviceId = InstagramHashUtil.generateDeviceId(this.username, this.password); this.uuid = InstagramGenericUtil.generateUuid(true); log.info("Device ID is: " + this.deviceId + ", random id: " + this.uuid); this.client = new DefaultHttpClient(); this.client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); this.client.setCookieStore(new BasicCookieStore()); }
From source file:org.codice.solr.factory.impl.HttpClientBuilder.java
public org.apache.http.impl.client.HttpClientBuilder get() { final org.apache.http.impl.client.HttpClientBuilder httpClientBuilder = HttpClients.custom() .setDefaultCookieStore(new BasicCookieStore()).setMaxConnTotal(128).setMaxConnPerRoute(32); if (useTls()) { String[] defaultProtocols = AccessController.doPrivileged( (PrivilegedAction<String[]>) () -> commaSeparatedToArray(System.getProperty(HTTPS_PROTOCOLS))); String[] defaultCipherSuites = AccessController .doPrivileged((PrivilegedAction<String[]>) () -> commaSeparatedToArray( System.getProperty(HTTPS_CIPHER_SUITES))); httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(getSslContext(), defaultProtocols, defaultCipherSuites, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER)); }//from w ww .j a va 2 s . com if (isConfiguredForBasicAuth()) { httpClientBuilder.setDefaultCredentialsProvider(getCredentialsProvider()); httpClientBuilder.addInterceptorFirst(new PreemptiveAuth(new BasicScheme())); } return httpClientBuilder; }
From source file:org.codice.solr.factory.SolrClientFactory.java
private static CloseableHttpClient getHttpClient(boolean retryRequestsOnError) { SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslContext(), getProtocols(), getCipherSuites(), SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); HttpRequestRetryHandler solrRetryHandler = new SolrHttpRequestRetryHandler(); HttpClientBuilder builder = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory) .setDefaultCookieStore(new BasicCookieStore()).setMaxConnTotal(128).setMaxConnPerRoute(32); if (retryRequestsOnError) { builder.setRetryHandler(solrRetryHandler); }/*from www.j ava2 s . c o m*/ return builder.build(); }
From source file:org.codice.solr.factory.SolrServerFactory.java
private static CloseableHttpClient getHttpClient() { SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslContext(), getProtocols(), getCipherSuites(), SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory) .setDefaultCookieStore(new BasicCookieStore()).setMaxConnTotal(128).setMaxConnPerRoute(32).build(); }