List of usage examples for org.apache.http.client CredentialsProvider setCredentials
void setCredentials(AuthScope authscope, Credentials credentials);
From source file:org.geosdi.geoplatform.gui.server.service.impl.PublisherService.java
@PostConstruct public void init() { logger.info("Reload publisher parameters: URL CLUSTER RELOAD " + urlClusterReload + " - HOST URL CLUSTER RELOAD " + hostUrlClusterReload + " - USERNAME CLUSTER RELOAD " + userNameClusterReload + " - PASSWORD CLUSTER RELOAD " + passwordClusterReload); localContext = new BasicHttpContext(); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 60000); HttpConnectionParams.setSoTimeout(params, 60000); this.httpclient = new DefaultHttpClient(params); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(userNameClusterReload, passwordClusterReload)); httpclient.setCredentialsProvider(credsProvider); }
From source file:fr.logfiletoes.config.Unit.java
/** * Initialise ElasticSearch Index ans taile file * @throws IOException /* w w w. j av a 2s. c o m*/ */ public void start() throws IOException { httpclient = HttpClients.createDefault(); context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(getElasticSearch().getUrl()); if (getElasticSearch().getLogin() != null && getElasticSearch().getPassword() != null) { UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getElasticSearch().getLogin(), getElasticSearch().getPassword()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); context.setCredentialsProvider(credentialsProvider); } CloseableHttpResponse elasticSearchCheck = httpclient.execute(httpGet, context); LOG.log(Level.INFO, "Check index : \"{0}\"", elasticSearchCheck.getStatusLine().getStatusCode()); LOG.log(Level.INFO, inputSteamToString(elasticSearchCheck.getEntity().getContent())); int statusCodeCheck = elasticSearchCheck.getStatusLine().getStatusCode(); EntityUtils.consume(elasticSearchCheck.getEntity()); elasticSearchCheck.close(); if (statusCodeCheck == 404) { // Cration de l'index HttpPut httpPut = new HttpPut(getElasticSearch().getUrl()); CloseableHttpResponse executeCreateIndex = httpclient.execute(httpPut, context); LOG.log(Level.INFO, "Create index : \"{0}\"", executeCreateIndex.getStatusLine().getStatusCode()); LOG.log(Level.INFO, inputSteamToString(executeCreateIndex.getEntity().getContent())); EntityUtils.consume(executeCreateIndex.getEntity()); executeCreateIndex.close(); CloseableHttpResponse elasticSearchCheckCreate = httpclient.execute(httpGet, context); LOG.log(Level.INFO, "Check create index : \"{0}\"", elasticSearchCheckCreate.getStatusLine().getStatusCode()); LOG.log(Level.INFO, inputSteamToString(elasticSearchCheckCreate.getEntity().getContent())); int statusCodeCheckCreate = elasticSearchCheckCreate.getStatusLine().getStatusCode(); EntityUtils.consume(elasticSearchCheckCreate.getEntity()); elasticSearchCheckCreate.close(); if (statusCodeCheckCreate != 200) { LOG.log(Level.SEVERE, "unable to create index \"{0}\"", getElasticSearch().getUrl()); throw new IOException("unable to create index \"" + getElasticSearch().getUrl() + "\""); } } else if (elasticSearchCheck.getStatusLine().getStatusCode() != 200) { LOG.severe("unkown error elasticsearch"); throw new IOException("unkown error elasticsearch"); } LOG.log(Level.INFO, "Initialisation ElasticSearch r\u00e9ussi pour {0}", getElasticSearch().getUrl()); tailer = Tailer.create(getLogFile(), new TailerListenerUnit(this, httpclient, context)); }
From source file:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java
/** * Create http client//w w w .j a v a2 s. co m */ private synchronized CloseableHttpClient getHttpClient() { if (httpClient == null) { try { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...) SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true) .build(); httpClientBuilder.setSSLContext(sslContext); // #### ONLY FOR TEST: Do NOT verify hostname SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory).build(); PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry); httpClientBuilder.setConnectionManager(httpClientConnectionManager); if (props.getProperty("http.proxyHost") != null) { httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"), Integer.parseInt(props.getProperty("http.proxyPort")))); } if (props.getProperty("http.proxyUser") != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials( props.getProperty("http.proxyUser"), props.getProperty("http.proxyPwd"))); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } httpClient = httpClientBuilder.build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) { throw new RuntimeException(ex); } } return httpClient; }
From source file:jp.co.ctc_g.jse.core.rest.springmvc.client.ProxyClientHttpRequestFactory.java
/** * ???????HttpClient????????//from w ww. j a va 2 s. com * {@inheritDoc} */ @Override public void afterPropertiesSet() throws Exception { Assert.notNull(proxyHost, "(proxyHost)???"); Assert.notNull(proxyPort, "??(proxyPort)???"); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(maxTotal); connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); HttpClientBuilder builder = HttpClients.custom(); builder.setConnectionManager(connectionManager); if (authentication) { Assert.notNull(username, "??true???????(username)???"); Assert.notNull(password, "??true?????(password)???"); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner( new HttpHost(proxyHost, Integer.parseInt(proxyPort))); builder.setRoutePlanner(routePlanner); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, Integer.parseInt(proxyPort)), new UsernamePasswordCredentials(username, password)); builder.setDefaultCredentialsProvider(credsProvider); } builder.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(readTimeout).build()); CloseableHttpClient client = builder.build(); setHttpClient(client); }
From source file:org.opennms.core.test.JUnitHttpServerTest.java
@Test @JUnitHttpServer(port = 9162, basicAuth = true, webapps = { @Webapp(context = "/testContext", path = "src/test/resources/test-webapp") }) public void testBasicAuthFailure() throws Exception { final DefaultHttpClient client = new DefaultHttpClient(); final HttpUriRequest method = new HttpGet("http://localhost:9162/testContext/monkey"); final CredentialsProvider cp = client.getCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "sucks"); cp.setCredentials(new AuthScope("localhost", 9162), credentials); final HttpResponse response = client.execute(method); assertEquals(401, response.getStatusLine().getStatusCode()); }
From source file:bad.robot.http.apache.ApacheHttpClientBuilder.java
private void setupAuthentication(DefaultHttpClient client) { CredentialsProvider credentialsProvider = client.getCredentialsProvider(); for (AuthenticatedHost authentication : authentications) credentialsProvider.setCredentials(authentication.scope, authentication.credentials); }
From source file:com.whizzosoftware.hobson.rest.v1.resource.device.MediaProxyResource.java
protected HttpProps createHttpGet(String varValue) throws ParseException, URISyntaxException { URIInfo uriInfo = URLVariableParser.parse(varValue); HttpGet get = new HttpGet(uriInfo.getURI()); // populate the GET request with headers if specified if (uriInfo.hasHeaders()) { Map<String, String> headers = uriInfo.getHeaders(); for (String name : headers.keySet()) { uriInfo.addHeader(name, headers.get(name)); }//from w ww . j av a2 s . co m } CloseableHttpClient httpClient; // populate the GET request with auth information if specified if (uriInfo.hasAuthInfo()) { URI uri = uriInfo.getURI(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(uri.getHost(), (uri.getPort() > 0) ? uri.getPort() : DEFAULT_REALM_PORT), new UsernamePasswordCredentials(uriInfo.getAuthInfo().getUsername(), uriInfo.getAuthInfo().getPassword())); httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); } else { httpClient = HttpClients.createDefault(); } return new HttpProps(httpClient, get); }
From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java
@Override protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) { this.configuration = configuration; this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize()); target = new HttpHost(configuration.getHost(), configuration.getPort(), configuration.getSsl() ? "https" : "http"); HttpClientBuilder builder = HttpClients.custom(); if (configuration.getUsername() != null && configuration.getPassword() != null) { LOG.info("Adding basic auth credentials provider"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword())); builder.setDefaultCredentialsProvider(credsProvider); }// ww w.j a va 2 s . c o m if (!configuration.getVerifySslCert()) { LOG.info("Adding trustful ssl context"); SSLContextBuilder sslBuilder = new SSLContextBuilder(); try { sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build()); builder.setSSLSocketFactory(sslsf); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) { LOG.error("Failed to init socket factory {}", ex.getMessage(), ex); } } PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize()); cm.setMaxTotal(configuration.getConnectionPoolSize()); builder.setConnectionManager(cm); this.client = builder.build(); }
From source file:org.zenoss.app.consumer.metric.impl.MetricServicePoster.java
/** * Login to the ZAuth service using the zenoss credentials. Grab the tenant id from the http response and cache * the results for future requests.//from ww w. j a va 2 s. com * @return tenant id * @throws IOException */ String getTenantId() throws IOException { if (tenantId == null) { log.debug("Requesting tenant id"); // get the hostname and port from ProxyConfiguration ProxyConfiguration proxyConfig = configuration.getProxyConfiguration(); String hostname = proxyConfig.getHostname(); int port = proxyConfig.getPort(); //configure request HttpContext context = new BasicHttpContext(); HttpHost host = new HttpHost(hostname, port, "http"); HttpPost post = new HttpPost(AUTHENTICATE_URL); post.addHeader(ACCEPT, APPLICATION_JSON.toString()); //configure authentication String username = configuration.getZenossCredentials().getUsername(); String password = configuration.getZenossCredentials().getPassword(); if (!Strings.nullToEmpty(username).isEmpty()) { //configure credentials CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(username, password)); context.setAttribute(ClientContext.CREDS_PROVIDER, provider); //setup auth cache AuthCache cache = new BasicAuthCache(); BasicScheme scheme = new BasicScheme(); cache.put(host, scheme); context.setAttribute(ClientContext.AUTH_CACHE, cache); } //handle response and collect tenantId HttpResponse response = null; try { response = httpClient.execute(host, post, context); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); log.debug("Tenant id request complete with status: {}", statusCode); if (statusCode >= 200 && statusCode <= 299) { Header id = response.getFirstHeader(ZenossTenant.ID_HTTP_HEADER); if (id == null) { log.warn("Failed to get zauth tenant id after login"); throw new RuntimeException("Failed to get zauth tenant id after successful login"); } tenantId = id.getValue(); log.info("Got tenant id: {}", tenantId); } else { log.warn("Unsuccessful response from server: {}", response.getStatusLine()); throw new IOException("Login for tenantId failed"); } } catch (NullPointerException ex) { log.warn("npe retrieving tenantId: {}", ex); } finally { try { if (response != null) { response.getEntity().getContent().close(); } } catch (NullPointerException | IOException ex) { log.warn("Failed to close request: {}", ex); } } } return tenantId; }