List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider
public final HttpClientBuilder setDefaultCredentialsProvider(final CredentialsProvider credentialsProvider)
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.AppConfig.java
/** * @return The instance of {@link HttpClient} to be used by {@link ClientHttpRequestFactory} to create client * requests. Pre-configured to support basic authentication using externally configured API user credentials, and to * utilise the API service's support for HTTP response compression (using gzip). *//*from ww w.j av a 2s . c o m*/ @Bean public HttpClient httpClient() { HttpClientBuilder builder = HttpClients.custom(); // Configure the basic authentication credentials to use for all requests CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); AuthScope authScope = new AuthScope(this.apiServiceHostName, this.apiServicePort); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.apiUserKey, this.apiUserSecret); credentialsProvider.setCredentials(authScope, credentials); builder.setDefaultCredentialsProvider(credentialsProvider); builder.addInterceptorFirst(new PreemptiveBasicAuthHttpRequestInterceptor()); // Configure default request headers List<Header> headers = new ArrayList<>(5); headers.add(new BasicHeader("Api-Client", SpringApiClientImpl.class.getCanonicalName())); if (this.defaultRequestHeaders != null) { for (String header : this.defaultRequestHeaders) { String[] headerNameAndValue = header.split("==", 2); if (headerNameAndValue.length == 2) { headers.add(new BasicHeader(headerNameAndValue[0], headerNameAndValue[1])); } } } builder.setDefaultHeaders(headers); // HttpClient should by default set the Accept-Encoding request header to indicate the client supports HTTP // response compression using gzip return builder.build(); }
From source file:org.nuxeo.connect.downloads.LocalDownloadingPackage.java
@Override public void run() { setPackageState(PackageState.REMOTE); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT_MS) .setConnectTimeout(CONNECTION_TIMEOUT_MS); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); ProxyHelper.configureProxyIfNeeded(requestConfigBuilder, credentialsProvider, sourceUrl); httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); try (CloseableHttpClient httpClient = httpClientBuilder.build()) { setPackageState(PackageState.DOWNLOADING); HttpGet method = new HttpGet(sourceUrl); if (!sourceUrl.contains(ConnectUrlConfig.CONNECT_TEST_MODE_BASEURL + "test")) { // for testing Map<String, String> headers = SecurityHeaderGenerator.getHeaders(); for (String headerName : headers.keySet()) { method.addHeader(headerName, headers.get(headerName)); }/*from w ww . java2 s . c o m*/ } try (CloseableHttpResponse httpResponse = httpClient.execute(method)) { int rc = httpResponse.getStatusLine().getStatusCode(); switch (rc) { case HttpStatus.SC_OK: if (sourceSize == 0) { Header clheader = httpResponse.getFirstHeader("content-length"); if (clheader != null) { sourceSize = Long.parseLong(clheader.getValue()); } } InputStream in = httpResponse.getEntity().getContent(); saveStreamAsFile(in); registerDownloadedPackage(); setPackageState(PackageState.DOWNLOADED); break; case HttpStatus.SC_NOT_FOUND: throw new ConnectServerError(String.format("Package not found (%s).", rc)); case HttpStatus.SC_FORBIDDEN: throw new ConnectServerError(String.format("Access refused (%s).", rc)); case HttpStatus.SC_UNAUTHORIZED: throw new ConnectServerError(String.format("Registration required (%s).", rc)); default: serverError = true; throw new ConnectServerError(String.format("Connect server HTTP response code %s.", rc)); } } } catch (IOException e) { // Expected SocketTimeoutException or ConnectTimeoutException serverError = true; setPackageState(PackageState.REMOTE); log.debug(e, e); errorMessage = e.getMessage(); } catch (ConnectServerError e) { setPackageState(PackageState.REMOTE); log.debug(e, e); errorMessage = e.getMessage(); } finally { ConnectDownloadManager cdm = NuxeoConnectClient.getDownloadManager(); cdm.removeDownloadingPackage(getId()); completed = true; } }
From source file:com.activiti.service.activiti.ActivitiClientService.java
public CloseableHttpClient getHttpClient(String userName, String password) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); SSLConnectionSocketFactory sslsf = null; try {/*from ww w. j av a2 s . c o m*/ SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { log.warn("Could not configure HTTP client to use SSL", e); } HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); if (sslsf != null) { httpClientBuilder.setSSLSocketFactory(sslsf); } return httpClientBuilder.build(); }
From source file:sachin.spider.SpiderConfig.java
private String handleRedirect(String url) { try {/*from w w w.j a va2s . co m*/ HttpGet httpget = new HttpGet(url); RequestConfig requestConfig = RequestConfig.custom().setRedirectsEnabled(true) .setCircularRedirectsAllowed(true).setRelativeRedirectsAllowed(true) .setConnectionRequestTimeout(getConnectionRequestTimeout()).setSocketTimeout(getSocketTimeout()) .setConnectTimeout(getConnectionTimeout()).build(); httpget.setConfig(requestConfig); HttpClientBuilder builder = HttpClientBuilder.create(); builder.setUserAgent(getUserAgentString()); if (isAuthenticate()) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(getUsername(), getPassword())); builder.setDefaultCredentialsProvider(credentialsProvider); } CloseableHttpClient httpclient = builder.build(); HttpClientContext context = HttpClientContext.create(); CloseableHttpResponse response = httpclient.execute(httpget, context); HttpHost target = context.getTargetHost(); List<URI> redirectLocations = context.getRedirectLocations(); URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations); url = location.toString(); EntityUtils.consumeQuietly(response.getEntity()); HttpClientUtils.closeQuietly(response); } catch (IOException | URISyntaxException ex) { Logger.getLogger(SpiderConfig.class.getName()).log(Level.SEVERE, null, ex); System.err.println(url); } return url; }
From source file:org.flowable.mule.MuleSendActivityBehavior.java
public void execute(DelegateExecution execution) { String endpointUrlValue = this.getStringFromField(this.endpointUrl, execution); String languageValue = this.getStringFromField(this.language, execution); String payloadExpressionValue = this.getStringFromField(this.payloadExpression, execution); String resultVariableValue = this.getStringFromField(this.resultVariable, execution); String usernameValue = this.getStringFromField(this.username, execution); String passwordValue = this.getStringFromField(this.password, execution); boolean isFlowable5Execution = false; Object payload = null;//w ww. ja va 2s . c om if ((Context.getCommandContext() != null && Flowable5Util .isFlowable5ProcessDefinitionId(Context.getCommandContext(), execution.getProcessDefinitionId())) || (Context.getCommandContext() == null && Flowable5Util.getFlowable5CompatibilityHandler() != null)) { payload = Flowable5Util.getFlowable5CompatibilityHandler() .getScriptingEngineValue(payloadExpressionValue, languageValue, execution); isFlowable5Execution = true; } else { ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines(); payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution); } if (endpointUrlValue.startsWith("vm:")) { LocalMuleClient client = this.getMuleContext().getClient(); MuleMessage message = new DefaultMuleMessage(payload, this.getMuleContext()); MuleMessage resultMessage; try { resultMessage = client.send(endpointUrlValue, message); } catch (MuleException e) { throw new RuntimeException(e); } Object result = resultMessage.getPayload(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); } } else { HttpClientBuilder clientBuilder = HttpClientBuilder.create(); if (usernameValue != null && passwordValue != null) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(usernameValue, passwordValue); provider.setCredentials(new AuthScope("localhost", -1, "mule-realm"), credentials); clientBuilder.setDefaultCredentialsProvider(provider); } HttpClient client = clientBuilder.build(); HttpPost request = new HttpPost(endpointUrlValue); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(payload); oos.flush(); oos.close(); request.setEntity(new ByteArrayEntity(baos.toByteArray())); } catch (Exception e) { throw new FlowableException("Error setting message payload", e); } byte[] responseBytes = null; try { // execute the POST request HttpResponse response = client.execute(request); responseBytes = IOUtils.toByteArray(response.getEntity().getContent()); } catch (Exception e) { throw new RuntimeException(e); } finally { // release any connection resources used by the method request.releaseConnection(); } if (responseBytes != null) { try { ByteArrayInputStream in = new ByteArrayInputStream(responseBytes); ObjectInputStream is = new ObjectInputStream(in); Object result = is.readObject(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); } } catch (Exception e) { throw new FlowableException("Failed to read response value", e); } } } if (isFlowable5Execution) { Flowable5Util.getFlowable5CompatibilityHandler().leaveExecution(execution); } else { this.leave(execution); } }
From source file:com.microsoft.alm.plugin.context.ServerContext.java
public synchronized HttpClient getHttpClient() { checkDisposed();//from ww w .j a v a 2 s. c o m if (httpClient == null && authenticationInfo != null) { final Credentials credentials = AuthHelper.getCredentials(type, authenticationInfo); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (isSSLEnabledOnPrem(Type.TFS, authenticationInfo.getServerUri())) { final SslConfigurator sslConfigurator = getSslConfigurator(); final SSLContext sslContext = sslConfigurator.createSSLContext(); httpClientBuilder.setSslcontext(sslContext); } httpClient = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).build(); } return httpClient; }
From source file:com.bosch.iot.things.tutorial.ui.ProxyServlet.java
/** * Create http client//from w w w . j av a 2 s . c om */ private synchronized CloseableHttpClient getHttpClient() { if (httpClient == null) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (props.getProperty("proxyHost") != null) { httpClientBuilder.setProxy(new HttpHost(props.getProperty("proxyHost"), Integer.parseInt(props.getProperty("proxyPort")))); } if (props.getProperty("proxyUser") != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials( props.getProperty("proxyUser"), props.getProperty("proxyPwd"))); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } httpClient = httpClientBuilder.build(); } return httpClient; }
From source file:it.larusba.neo4j.jdbc.http.driver.CypherExecutor.java
/** * Default constructor./*from w w w. j a v a 2s . co m*/ * * @param host Hostname of the Neo4j instance. * @param port HTTP port of the Neo4j instance. * @param properties Properties of the url connection. * @throws SQLException */ public CypherExecutor(String host, Integer port, Properties properties) throws SQLException { // Create the http client builder HttpClientBuilder builder = HttpClients.custom(); // Adding authentication to the http client if needed if (properties.containsKey("user") && properties.containsKey("password")) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials( properties.get("user").toString(), properties.get("password").toString())); builder.setDefaultCredentialsProvider(credsProvider); } // Setting user-agent StringBuilder sb = new StringBuilder(); sb.append("Neo4j JDBC Driver"); if (properties.containsKey("userAgent")) { sb.append(" via "); sb.append(properties.getProperty("userAgent")); } builder.setUserAgent(sb.toString()); // Create the http client this.http = builder.build(); // Create the url endpoint StringBuffer sbEndpoint = new StringBuffer(); sbEndpoint.append("http://").append(host).append(":").append(port).append("/db/data/transaction"); this.transactionUrl = sbEndpoint.toString(); // Setting autocommit this.setAutoCommit(Boolean.valueOf(properties.getProperty("autoCommit", "true"))); }