List of usage examples for org.apache.http.client CredentialsProvider setCredentials
void setCredentials(AuthScope authscope, Credentials credentials);
From source file:com.adobe.aem.demo.communities.Loader.java
private static String doPost(String hostname, String port, String url, String user, String password, HttpEntity entity, String lookup, String referer) { String jsonElement = null;//from w ww. j a v a2s .c o m try { HttpHost target = new HttpHost(hostname, Integer.parseInt(port), "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(user, password)); CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .build(); try { // Adding the Basic Authentication data to the context for this command AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // Composing the root URL for all subsequent requests String postUrl = "http://" + hostname + ":" + port + url; logger.debug("Posting request as " + user + " with password " + password + " to " + postUrl); // Preparing a standard POST HTTP command HttpPost request = new HttpPost(postUrl); request.setEntity(entity); if (!entity.getContentType().toString().contains("multipart")) { request.addHeader("content-type", "application/x-www-form-urlencoded"); } request.addHeader("Accept", "application/json, text/javascript, */*; q=0.01"); request.addHeader("Origin", postUrl); if (referer != null) { logger.debug("Referer header added to request: " + referer); request.addHeader("Referer", referer); } // Sending the HTTP POST command CloseableHttpResponse response = httpClient.execute(target, request, localContext); try { String responseString = EntityUtils.toString(response.getEntity(), "UTF-8"); logger.debug("Got POST response:" + responseString); if (lookup != null) { logger.debug("JSON lookup value: " + lookup); int separatorIndex = lookup.indexOf("/"); if (separatorIndex > 0) { // Grabbing element in a nested element Object object = new JSONObject(responseString).get(lookup.substring(0, separatorIndex)); if (object != null) { if (object instanceof JSONArray) { logger.debug("JSON object is a JSONArray"); JSONArray jsonArray = (JSONArray) object; if (jsonArray.length() == 1) { JSONObject jsonObject = jsonArray.getJSONObject(0); jsonElement = jsonObject.getString(lookup.substring(1 + separatorIndex)); logger.debug("JSON value (jsonArray) returned is " + jsonElement); } } else if (object instanceof JSONObject) { logger.debug("JSON object is a JSONObject"); JSONObject jsonobject = (JSONObject) object; jsonElement = jsonobject.getString(lookup.substring(1 + separatorIndex)); logger.debug("JSON value (jsonObject) returned is " + jsonElement); } } } else { // Grabbing element at the top of the JSON response jsonElement = new JSONObject(responseString).getString(lookup); logger.debug("JSON (top) value returned is " + jsonElement); } } } catch (Exception ex) { logger.error(ex.getMessage()); } finally { response.close(); } } catch (Exception ex) { logger.error(ex.getMessage()); } finally { httpClient.close(); } } catch (IOException e) { logger.error(e.getMessage()); } return jsonElement; }
From source file:fr.ippon.wip.http.hc.HttpClientExecutor.java
/** * This method updates the CredentialsProvider associated to the current * PortletSession and the windowID with the provided login and password. * Basic and NTLM authentication schemes are supported. This method uses the * current fr.ippon.wip.state.PortletWindow to retrieve the authentication * schemes requested by remote server.// www .j a va 2s .c o m * * @param login * @param password * @param portletRequest * Used to get current javax.portlet.PortletSession and windowID */ public void login(String login, String password, PortletRequest portletRequest) { HttpClientResourceManager resourceManager = HttpClientResourceManager.getInstance(); CredentialsProvider credentialsProvider = resourceManager.getCredentialsProvider(portletRequest); PortletWindow portletWindow = PortletWindow.getInstance(portletRequest); List<String> schemes = portletWindow.getRequestedAuthSchemes(); if (schemes.contains("Basic")) { // Creating basic credentials AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "Basic"); Credentials credentials = new UsernamePasswordCredentials(login, password); credentialsProvider.setCredentials(scope, credentials); } if (schemes.contains("NTLM")) { // Creating ntlm credentials AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "NTLM"); Credentials credentials = new NTCredentials(login, password, "", ""); credentialsProvider.setCredentials(scope, credentials); } }
From source file:jp.ambrosoli.quickrestclient.apache.service.ApacheHttpService.java
/** * Basic/Digest?????/* w w w. j a v a 2 s . com*/ * * @param uri * URI * @param authInfo * ? * @param provider */ protected void setCredentialsAuthenticate(final URI uri, final AuthInfo authInfo, final CredentialsProvider provider) { if (authInfo == null || provider == null) { return; } AuthType type = authInfo.type; if (type != AuthType.BASIC && type != AuthType.DIGEST) { return; } AuthScope authscope = new AuthScope(uri.getHost(), URIUtil.getPort(uri)); Credentials credentials = new UsernamePasswordCredentials(authInfo.username, authInfo.password); provider.setCredentials(authscope, credentials); }
From source file:fr.gael.dhus.sync.impl.ODataProductSynchronizer.java
/** Downloads a product. */ private void downloadProduct(Product p) throws IOException, InterruptedException { // Creates a client producer that produces HTTP Basic auth aware clients HttpAsyncClientProducer cliprod = new HttpAsyncClientProducer() { @Override//from w w w .j a v a2 s .c o m public CloseableHttpAsyncClient generateClient() { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(serviceUser, servicePass)); CloseableHttpAsyncClient res = HttpAsyncClients.custom() .setDefaultCredentialsProvider(credsProvider).build(); res.start(); return res; } }; // Asks the Incoming manager for a download path Path dir = Paths.get(INCOMING_MANAGER.getNewIncomingPath().toURI()); Path tmp_pd = dir.resolve(p.getIdentifier() + ".part"); // Temporary names Path tmp_ql = dir.resolve(p.getIdentifier() + "-ql.part"); Path tmp_tn = dir.resolve(p.getIdentifier() + "-tn.part"); // These files will be moved once download is complete InterruptibleHttpClient http_client = new InterruptibleHttpClient(cliprod); DownloadResult pd_res = null, ql_res = null, tn_res = null; try { long delta = System.currentTimeMillis(); pd_res = downloadValidateRename(http_client, tmp_pd, p.getOrigin()); logODataPerf(p.getOrigin(), System.currentTimeMillis() - delta); // Sets download info in the product (not written in the db here) p.setPath(pd_res.data.toUri().toURL()); p.setDownloadablePath(pd_res.data.toString()); p.setDownloadableType(pd_res.dataType); p.setDownloadableSize(pd_res.dataSize); // Downloads and sets the quicklook and thumbnail (if any) if (p.getQuicklookFlag()) { // Failing at downloading a quicklook must not abort the download! try { ql_res = downloadValidateRename(http_client, tmp_ql, p.getQuicklookPath()); p.setQuicklookPath(ql_res.data.toString()); p.setQuicklookSize(ql_res.dataSize); } catch (IOException ex) { LOGGER.error("Failed to download quicklook at " + p.getQuicklookPath(), ex); } } if (p.getThumbnailFlag()) { // Failing at downloading a thumbnail must not abort the download! try { tn_res = downloadValidateRename(http_client, tmp_tn, p.getThumbnailPath()); p.setThumbnailPath(tn_res.data.toString()); p.setThumbnailSize(tn_res.dataSize); } catch (IOException ex) { LOGGER.error("Failed to download thumbnail at " + p.getThumbnailPath(), ex); } } } catch (Exception ex) { // Removes downloaded files if an error occured if (pd_res != null) { Files.delete(pd_res.data); } if (ql_res != null) { Files.delete(ql_res.data); } if (tn_res != null) { Files.delete(tn_res.data); } throw ex; } }
From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java
/** * Create the new Apache HTTP Client connector. * * @param client JAX-RS client instance for which the connector is being created. * @param config client configuration.//ww w . jav a 2 s . c om */ ApacheConnector(final Client client, final Configuration config) { final Object connectionManager = config.getProperties().get(ApacheClientProperties.CONNECTION_MANAGER); if (connectionManager != null) { if (!(connectionManager instanceof HttpClientConnectionManager)) { LOGGER.log(Level.WARNING, LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.CONNECTION_MANAGER, connectionManager.getClass().getName(), HttpClientConnectionManager.class.getName())); } } Object reqConfig = config.getProperties().get(ApacheClientProperties.REQUEST_CONFIG); if (reqConfig != null) { if (!(reqConfig instanceof RequestConfig)) { LOGGER.log(Level.WARNING, LocalizationMessages.IGNORING_VALUE_OF_PROPERTY(ApacheClientProperties.REQUEST_CONFIG, reqConfig.getClass().getName(), RequestConfig.class.getName())); reqConfig = null; } } final SSLContext sslContext = client.getSslContext(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setConnectionManager(getConnectionManager(client, config, sslContext)); clientBuilder.setConnectionManagerShared(PropertiesHelper.getValue(config.getProperties(), ApacheClientProperties.CONNECTION_MANAGER_SHARED, false, null)); clientBuilder.setSslcontext(sslContext); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); final Object credentialsProvider = config.getProperty(ApacheClientProperties.CREDENTIALS_PROVIDER); if (credentialsProvider != null && (credentialsProvider instanceof CredentialsProvider)) { clientBuilder.setDefaultCredentialsProvider((CredentialsProvider) credentialsProvider); } final Object retryHandler = config.getProperties().get(ApacheClientProperties.RETRY_HANDLER); if (retryHandler != null && (retryHandler instanceof HttpRequestRetryHandler)) { clientBuilder.setRetryHandler((HttpRequestRetryHandler) retryHandler); } final Object proxyUri; proxyUri = config.getProperty(ClientProperties.PROXY_URI); if (proxyUri != null) { final URI u = getProxyUri(proxyUri); final HttpHost proxy = new HttpHost(u.getHost(), u.getPort(), u.getScheme()); final String userName; userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class); if (userName != null) { final String password; password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class); if (password != null) { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(u.getHost(), u.getPort()), new UsernamePasswordCredentials(userName, password)); clientBuilder.setDefaultCredentialsProvider(credsProvider); } } clientBuilder.setProxy(proxy); } final Boolean preemptiveBasicAuthProperty = (Boolean) config.getProperties() .get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION); this.preemptiveBasicAuth = (preemptiveBasicAuthProperty != null) ? preemptiveBasicAuthProperty : false; final boolean ignoreCookies = PropertiesHelper.isProperty(config.getProperties(), ApacheClientProperties.DISABLE_COOKIES); if (reqConfig != null) { final RequestConfig.Builder reqConfigBuilder = RequestConfig.copy((RequestConfig) reqConfig); if (ignoreCookies) { reqConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES); } requestConfig = reqConfigBuilder.build(); } else { if (ignoreCookies) { requestConfigBuilder.setCookieSpec(CookieSpecs.IGNORE_COOKIES); } requestConfig = requestConfigBuilder.build(); } if (requestConfig.getCookieSpec() == null || !requestConfig.getCookieSpec().equals(CookieSpecs.IGNORE_COOKIES)) { this.cookieStore = new BasicCookieStore(); clientBuilder.setDefaultCookieStore(cookieStore); } else { this.cookieStore = null; } clientBuilder.setDefaultRequestConfig(requestConfig); this.client = clientBuilder.build(); }
From source file:es.auth.plugin.AbstractUnitTest.java
protected final JestHttpClient getJestClient(final String serverUri, final String username, final String password) throws Exception { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final HttpClientConfig clientConfig1 = new HttpClientConfig.Builder(serverUri).multiThreaded(true).build(); // Construct a new Jest client according to configuration via factory final JestClientFactory factory1 = new JestClientFactory(); factory1.setHttpClientConfig(clientConfig1); final JestHttpClient c = factory1.getObject(); final HttpClientBuilder hcb = HttpClients.custom(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(username, password)); hcb.setDefaultCredentialsProvider(credsProvider); hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(60 * 1000).build()); final CloseableHttpClient httpClient = hcb.build(); c.setHttpClient(httpClient);// w w w.j av a 2 s.c o m return c; }