List of usage examples for org.apache.http.impl.client BasicCredentialsProvider BasicCredentialsProvider
public BasicCredentialsProvider()
From source file:org.ttrssreader.net.deprecated.ApacheJSONConnector.java
@Override public void init() { super.init(); if (!httpAuth) { credProvider = null;//from w ww . j av a 2s . c o m return; } // Refresh Credentials-Provider if (httpUsername.equals(Constants.EMPTY) || httpPassword.equals(Constants.EMPTY)) { credProvider = null; } else { credProvider = new BasicCredentialsProvider(); credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(httpUsername, httpPassword)); } }
From source file:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java
/** * Define the Credentials/*from w w w. j a v a2s . c om*/ * * @param httpClientBuilder * @param url * @return * @throws java.net.MalformedURLException */ private HttpClientBuilder configCredentials(HttpClientBuilder httpClientBuilder, final String url) throws DSSException { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); for (final Map.Entry<HttpHost, UsernamePasswordCredentials> entry : authenticationMap.entrySet()) { final HttpHost httpHost = entry.getKey(); final UsernamePasswordCredentials usernamePasswordCredentials = entry.getValue(); credsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()), usernamePasswordCredentials); } httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder = configureProxy(httpClientBuilder, credsProvider, url); return httpClientBuilder; }
From source file:com.liferay.sync.engine.session.Session.java
public Session(URL url, String login, String password, boolean trustSelfSigned, int maxConnections) { if (maxConnections == Integer.MAX_VALUE) { _executorService = Executors.newCachedThreadPool(); } else {/*from ww w .j av a2 s. c o m*/ _executorService = Executors.newFixedThreadPool(maxConnections); } HttpClientBuilder httpClientBuilder = createHttpClientBuilder(trustSelfSigned, maxConnections); httpClientBuilder.setConnectionManager(_getHttpClientConnectionManager(trustSelfSigned)); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); _httpHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); credentialsProvider.setCredentials(new AuthScope(_httpHost), new UsernamePasswordCredentials(login, password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); _httpClient = httpClientBuilder.build(); _oAuthEnabled = false; }
From source file:org.opensaml.security.httpclient.HttpClientSecuritySupportTest.java
@Test public void testMarshalSecurityParametersWithoutReplacement() { HttpClientContext context = HttpClientContext.create(); CredentialsProvider credProvider = new BasicCredentialsProvider(); TrustEngine<X509Credential> trustEngine = new MockTrustEngine(); CriteriaSet criteriaSet = new CriteriaSet(); List<String> protocols = Lists.newArrayList("foo"); List<String> cipherSuites = Lists.newArrayList("foo"); X509Credential clientTLSCred = new BasicX509Credential(cert); HostnameVerifier verifier = new StrictHostnameVerifier(); context.setCredentialsProvider(credProvider); context.setAttribute(CONTEXT_KEY_TRUST_ENGINE, trustEngine); context.setAttribute(CONTEXT_KEY_CRITERIA_SET, criteriaSet); context.setAttribute(CONTEXT_KEY_TLS_PROTOCOLS, protocols); context.setAttribute(CONTEXT_KEY_TLS_CIPHER_SUITES, cipherSuites); context.setAttribute(CONTEXT_KEY_CLIENT_TLS_CREDENTIAL, clientTLSCred); context.setAttribute(CONTEXT_KEY_HOSTNAME_VERIFIER, verifier); HttpClientSecurityParameters params = new HttpClientSecurityParameters(); params.setCredentialsProvider(new BasicCredentialsProvider()); params.setTLSTrustEngine(new MockTrustEngine()); params.setTLSCriteriaSet(new CriteriaSet()); params.setTLSProtocols(Lists.newArrayList("foo")); params.setTLSCipherSuites(Lists.newArrayList("foo")); params.setClientTLSCredential(new BasicX509Credential(cert)); params.setHostnameVerifier(new StrictHostnameVerifier()); HttpClientSecuritySupport.marshalSecurityParameters(context, params, false); Assert.assertSame(context.getCredentialsProvider(), credProvider); Assert.assertSame(context.getAttribute(CONTEXT_KEY_TRUST_ENGINE), trustEngine); Assert.assertSame(context.getAttribute(CONTEXT_KEY_CRITERIA_SET), criteriaSet); Assert.assertSame(context.getAttribute(CONTEXT_KEY_TLS_PROTOCOLS), protocols); Assert.assertSame(context.getAttribute(CONTEXT_KEY_TLS_CIPHER_SUITES), cipherSuites); Assert.assertSame(context.getAttribute(CONTEXT_KEY_CLIENT_TLS_CREDENTIAL), clientTLSCred); Assert.assertSame(context.getAttribute(CONTEXT_KEY_HOSTNAME_VERIFIER), verifier); }
From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java
@Override public void setUsernamePassword(AuthenticationType authType, String username, String password) { this.credentials = new UsernamePasswordCredentials(Objects.requireNonNull(username), Objects.requireNonNull(password)); this.credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create(); switch (authType) { case BASIC://w ww . j a v a2s .co m authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); break; case DIGEST: authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; default: throw new IllegalArgumentException("Unsupported authentiation type: " + authType); } this.authRegistry = authRegistryBuilder.build(); }
From source file:org.apache.nifi.elasticsearch.ElasticSearchClientServiceImpl.java
private void setupClient(ConfigurationContext context) throws MalformedURLException, InitializationException { final String hosts = context.getProperty(HTTP_HOSTS).evaluateAttributeExpressions().getValue(); String[] hostsSplit = hosts.split(",[\\s]*"); this.url = hostsSplit[0]; final SSLContextService sslService = context.getProperty(PROP_SSL_CONTEXT_SERVICE) .asControllerService(SSLContextService.class); final String username = context.getProperty(USERNAME).evaluateAttributeExpressions().getValue(); final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue(); final Integer connectTimeout = context.getProperty(CONNECT_TIMEOUT).asInteger(); final Integer readTimeout = context.getProperty(SOCKET_TIMEOUT).asInteger(); final Integer retryTimeout = context.getProperty(RETRY_TIMEOUT).asInteger(); HttpHost[] hh = new HttpHost[hostsSplit.length]; for (int x = 0; x < hh.length; x++) { URL u = new URL(hostsSplit[x]); hh[x] = new HttpHost(u.getHost(), u.getPort(), u.getProtocol()); }/* w w w . j av a 2 s.c o m*/ final SSLContext sslContext; try { sslContext = (sslService != null && sslService.isKeyStoreConfigured() && sslService.isTrustStoreConfigured()) ? buildSslContext(sslService) : null; } catch (IOException | CertificateException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | KeyManagementException e) { getLogger().error("Error building up SSL Context from the supplied configuration.", e); throw new InitializationException(e); } RestClientBuilder builder = RestClient.builder(hh).setHttpClientConfigCallback(httpClientBuilder -> { if (sslContext != null) { httpClientBuilder = httpClientBuilder.setSSLContext(sslContext); } if (username != null && password != null) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } return httpClientBuilder; }).setRequestConfigCallback(requestConfigBuilder -> { requestConfigBuilder.setConnectTimeout(connectTimeout); requestConfigBuilder.setSocketTimeout(readTimeout); return requestConfigBuilder; }).setMaxRetryTimeoutMillis(retryTimeout); this.client = builder.build(); this.highLevelClient = new RestHighLevelClient(client); }
From source file:org.alfresco.test.util.AlfrescoHttpClient.java
/** * Get basic http client with basic credential. * @param username String username /*from ww w .j a va 2 s . c o m*/ * @param password String password * @return {@link HttpClient} client */ public HttpClient getHttpClientWithBasicAuth(String username, String password) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); provider.setCredentials(AuthScope.ANY, credentials); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); return client; }
From source file:nl.architolk.ldt.processors.HttpClientProcessor.java
public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException { try {/*from w w w. j a va 2s .c o m*/ CloseableHttpClient httpclient = HttpClientProperties.createHttpClient(); try { // Read content of config pipe Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG); Node configNode = configDocument.selectSingleNode("//config"); URL theURL = new URL(configNode.valueOf("url")); if (configNode.valueOf("auth-method").equals("basic")) { HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol()); //Authentication support CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( configNode.valueOf("username"), configNode.valueOf("password"))); // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); authCache.put(targetHost, new BasicScheme()); // Add AuthCache to the execution context httpContext = HttpClientContext.create(); httpContext.setCredentialsProvider(credsProvider); httpContext.setAuthCache(authCache); } else if (configNode.valueOf("auth-method").equals("form")) { //Sign in. Cookie will be remembered bij httpclient HttpPost authpost = new HttpPost(configNode.valueOf("auth-url")); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username"))); nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password"))); authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse httpResponse = httpclient.execute(authpost); // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode())); } CloseableHttpResponse response; if (configNode.valueOf("method").equals("post")) { // POST HttpPost httpRequest = new HttpPost(configNode.valueOf("url")); setBody(httpRequest, context, configNode); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("put")) { // PUT HttpPut httpRequest = new HttpPut(configNode.valueOf("url")); setBody(httpRequest, context, configNode); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("delete")) { //DELETE HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("head")) { //HEAD HttpHead httpRequest = new HttpHead(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else if (configNode.valueOf("method").equals("options")) { //OPTIONS HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url")); response = executeRequest(httpRequest, httpclient); } else { //Default = GET HttpGet httpRequest = new HttpGet(configNode.valueOf("url")); String acceptHeader = configNode.valueOf("accept"); if (!acceptHeader.isEmpty()) { httpRequest.addHeader("accept", configNode.valueOf("accept")); } //Add proxy route if needed HttpClientProperties.setProxy(httpRequest, theURL.getHost()); response = executeRequest(httpRequest, httpclient); } try { contentHandler.startDocument(); int status = response.getStatusLine().getStatusCode(); AttributesImpl statusAttr = new AttributesImpl(); statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status)); contentHandler.startElement("", "response", "response", statusAttr); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); Header contentType = response.getFirstHeader("Content-Type"); if (entity != null && contentType != null) { //logger.info("Contenttype: " + contentType.getValue()); //Read content into inputstream InputStream inStream = entity.getContent(); // output-type = json means: response is json, convert to xml if (configNode.valueOf("output-type").equals("json")) { //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!! //javax.json contains readers to read from an inputstream StringWriter writer = new StringWriter(); IOUtils.copy(inStream, writer, "UTF-8"); JSONObject json = JSONObject.fromObject(writer.toString()); parseJSONObject(contentHandler, json); // output-type = xml means: response is xml, keep it } else if (configNode.valueOf("output-type").equals("xml")) { try { XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inStream)); } catch (Exception e) { throw new OXFException(e); } // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml } else if (configNode.valueOf("output-type").equals("jsonld")) { try { Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response! Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback()); Any23 runner = new Any23(); DocumentSource source = new StringDocumentSource((String) nquads, configNode.valueOf("url")); ByteArrayOutputStream out = new ByteArrayOutputStream(); TripleHandler handler = new RDFXMLWriter(out); try { runner.extract(source, handler); } finally { handler.close(); } ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray()); XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inJsonStream)); } catch (Exception e) { throw new OXFException(e); } // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml } else if (configNode.valueOf("output-type").equals("rdf")) { try { Any23 runner = new Any23(); DocumentSource source; //If contentType = text/html than convert from html to xhtml to handle non-xml style html! logger.info("Contenttype: " + contentType.getValue()); if (configNode.valueOf("tidy").equals("yes") && contentType.getValue().startsWith("text/html")) { org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8", configNode.valueOf("url")); //TODO UTF-8 should be read from response! RDFCleaner cleaner = new RDFCleaner(); org.jsoup.nodes.Document cleandoc = cleaner.clean(doc); cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); cleandoc.outputSettings() .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml); cleandoc.outputSettings().charset("UTF-8"); source = new StringDocumentSource(cleandoc.html(), configNode.valueOf("url"), contentType.getValue()); } else { source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"), contentType.getValue()); } ByteArrayOutputStream out = new ByteArrayOutputStream(); TripleHandler handler = new RDFXMLWriter(out); try { runner.extract(source, handler); } finally { handler.close(); } ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray()); XMLReader saxParser = XMLParsing .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false)); saxParser.setContentHandler(new ParseHandler(contentHandler)); saxParser.parse(new InputSource(inAnyStream)); } catch (Exception e) { throw new OXFException(e); } } else { CharArrayWriter writer = new CharArrayWriter(); IOUtils.copy(inStream, writer, "UTF-8"); contentHandler.characters(writer.toCharArray(), 0, writer.size()); } } } contentHandler.endElement("", "response", "response"); contentHandler.endDocument(); } finally { response.close(); } } finally { httpclient.close(); } } catch (Exception e) { throw new OXFException(e); } }
From source file:org.guvnor.ala.wildfly.access.WildflyClient.java
public int start(String deploymentName) throws WildflyClientException { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, managementPort), new UsernamePasswordCredentials(user, password)); CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build(); final HttpPost post = new HttpPost("http://" + host + ":" + managementPort + "/management"); post.addHeader("X-Management-Client-Name", "GUVNOR-ALA"); // the DMR operation ModelNode operation = new ModelNode(); operation.get("operation").set("deploy"); operation.get("address").add("deployment", deploymentName); post.setEntity(new StringEntity(operation.toJSONString(true), APPLICATION_JSON)); try {/* www. ja va2s . c om*/ HttpResponse response = httpclient.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { throw new WildflyClientException("Error Starting App Status Code: " + statusCode); } return statusCode; } catch (IOException ex) { getLogger(WildflyClient.class.getName()).log(SEVERE, null, ex); throw new WildflyClientException("Error Starting App : " + ex.getMessage(), ex); } }
From source file:org.fao.geonet.utils.AbstractHttpRequest.java
protected ClientHttpResponse doExecute(final HttpRequestBase httpMethod) throws IOException { return requestFactory.execute(httpMethod, new Function<HttpClientBuilder, Void>() { @Nullable/*from ww w . j av a2 s . c o m*/ @Override public Void apply(@Nonnull HttpClientBuilder input) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); if (credentials != null) { final URI uri = httpMethod.getURI(); HttpHost hh = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()); credentialsProvider.setCredentials(new AuthScope(hh), credentials); // Preemptive authentication if (isPreemptiveBasicAuth()) { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(hh, basicAuth); // Add AuthCache to the execution context httpClientContext = HttpClientContext.create(); httpClientContext.setCredentialsProvider(credentialsProvider); httpClientContext.setAuthCache(authCache); } else { input.setDefaultCredentialsProvider(credentialsProvider); } } else { input.setDefaultCredentialsProvider(credentialsProvider); } if (useProxy) { final HttpHost proxy = new HttpHost(proxyHost, proxyPort); input.setProxy(proxy); if (proxyCredentials != null) { credentialsProvider.setCredentials(new AuthScope(proxy), proxyCredentials); } } input.setRedirectStrategy(new LaxRedirectStrategy()); return null; } }, this); }