List of usage examples for org.apache.http.client CredentialsProvider setCredentials
void setCredentials(AuthScope authscope, Credentials credentials);
From source file:com.imense.imenseANPRsdkProAUNZ.ImenseLicenseServer.java
@Override protected Boolean doInBackground(Void... arg0) { try {/*from www. ja va 2 s. co m*/ int[] uid_success = { 0 }; //generate unique device ID String device_uid = ImenseOCRTask.getUniqueDeviceID(androidAppContext, uid_success); if (device_uid == null || device_uid.length() < VALID_UID_LENGTH) { throw new Exception("Invalid UID"); } // Instantiate the custom HttpClient DefaultHttpClient client = new MyHttpClient(androidAppContext.getApplicationContext()); //see http://hc.apache.org/httpcomponents-client/httpclient/xref/index.html CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(ImenseLicenseServerLogin, ImenseLicenseServerPassword)); client.setCredentialsProvider(credsProvider); HttpGet httpget = new HttpGet(ImenseLicenseServerURL + device_uid); // Execute the GET call and obtain the response HttpResponse httpresponse = client.execute(httpget); HttpEntity resEntity = httpresponse.getEntity(); //System.out.println("Response Status: <"+httpresponse.getStatusLine()+">"); if (resEntity != null) { String resS = EntityUtils.toString(resEntity); resS = resS.trim(); if (resS.length() == VALID_KEY_LENGTH && !resS.startsWith("Error:")) { //this should be a valid key! licensekey = resS; } else { if (resS.startsWith("Error:")) { serverResponseMessage = resS; //human readable error message } } } if (resEntity != null) { resEntity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); } catch (Exception ex) { ex.printStackTrace(); } if (licensekey != null && licensekey.length() == VALID_KEY_LENGTH) { //verify license key int verificationResponse = ImenseOCRTask.verifyLicenseKey(androidAppContext, licensekey); //"verificationResponse" may take on the following values: //0: license key invalid or expired //1: license key valid for more than 14 days //>1: license key valid for "verificationResponse-1" number of days if (verificationResponse < 1) { licensekey = null; return false; } return true; } //if (licensekey != null && licensekey.length()==VALID_KEY_LENGTH) { return false; }
From source file:ranktracker.crawler.youtube.YoutubeStatistics.java
public String fetchVideoPage(String newurl) throws IOException { int portNo = generateRandomPort(); CredentialsProvider credsprovider = new BasicCredentialsProvider(); credsprovider.setCredentials(new AuthScope("95.85.29.99", portNo), new UsernamePasswordCredentials("mongoose", "Fjh30fi")); HttpHost proxy = new HttpHost("95.85.29.99", portNo); String userAgent = UserAgents.getRandomUserAgent(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsprovider) .setUserAgent(userAgent).setProxy(proxy).build(); String responsebody = ""; String responsestatus = null; int returnresponse; int count = 0; try {/* www .j av a 2 s . c o m*/ HttpGet httpget = new HttpGet(newurl); httpget.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); httpget.addHeader("Accept-Encoding", "gzip, deflate"); httpget.addHeader("Accept-Language", "en-US,en;q=0.5"); httpget.addHeader("Connection", "keep-alive"); System.out.println("Response status" + httpget.getRequestLine()); CloseableHttpResponse resp = httpclient.execute(httpget); responsestatus = resp.getStatusLine().toString(); if (responsestatus.contains("503") || responsestatus.contains("502") || responsestatus.contains("400") || responsestatus.contains("402") || responsestatus.contains("403") || responsestatus.contains("404") || responsestatus.contains("407") || responsestatus.contains("406") || responsestatus.contains("SSLHandshakeException") || responsestatus.contains("999") || responsestatus.contains("504") || responsestatus.contains("505") || responsestatus.contains("ClientProtocolException") || responsestatus.contains("SocketTimeoutException") || responsestatus.contains("HttpHostConnectException")) { return "Proxy faliure"; // do { // count++; // returnresponse = fetchPageSourcefromClientforYoutube2(newurl, pagename); // if (returnresponse == 503) { // System.out.println("PROX FAILURE"); // try { // Thread.sleep(1000); // } catch (InterruptedException ex) { // java.util.logging.Logger.getLogger(FetchPagewithClientAthentication.class.getName()).log(Level.SEVERE, null, ex); // } // } // if (count > 15) { // break; // } // } while (returnresponse == 503 || returnresponse == 502); } else { HttpEntity entity = resp.getEntity(); System.out.println(resp.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent())); String inputLine; while ((inputLine = in.readLine()) != null) { responsebody = new StringBuilder().append(responsebody).append(inputLine).toString(); } // writeResponseFile(responsebody, pagename); } EntityUtils.consume(entity); } } catch (IOException | IllegalStateException e) { System.out.println("Exception = " + e); // do { // count++; // returnresponse = fetchPageSourcefromClientforYoutube2(newurl); // if (returnresponse == 503) { // System.out.println("PROX FAILURE"); // try { // Thread.sleep(5000); // } catch (InterruptedException ex) { // java.util.logging.Logger.getLogger(FetchPagewithClientAthentication.class.getName()).log(Level.SEVERE, null, ex); // } // } // if (count > 15) { // fetchPageSourcefromClientforYoutube2(newurl); // } // } while (returnresponse == 503 || returnresponse == 502); } finally { httpclient.close(); } return responsebody; }
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;/*from w w w.j av a 2s . com*/ 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.cprassoc.solr.auth.SolrHttpHandler.java
protected SolrHttpHandler() { PoolingClientConnectionManager cm = new PoolingClientConnectionManager(); if (props == null) { props = SolrAuthManager.getProperties(); }//from www . jav a 2 s . co m if (props.getProperty("solr.ssl.enabled").equals("true")) { solrBaseUrl = "https://"; } else { solrBaseUrl = "http://"; } solrBaseUrl += props.getProperty("solr.host.port"); // solr.crawler.cloud.server=localhost:9983 //admin:password123@ CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( props.getProperty("solr.admin.user"), props.getProperty("solr.admin.pwd")); provider.setCredentials(AuthScope.ANY, credentials); // client = new DefaultHttpClient(cm); client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); zkCloudClient = new CloudSolrClient(props.getProperty("solr.zookeeper.port"), client); zkCloudClient.setDefaultCollection(props.getProperty("solr.default.collection")); // solrCloudClient = new CloudSolrClient(props.getProperty("solr.host.port"), client); // solrCloudClient.setDefaultCollection(props.getProperty("solr.default.collection")); System.out.println("Solr Base URL: " + solrBaseUrl); }
From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java
public void afterPropertiesSet() { HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager()); if ((_login != null) && (_password != null)) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(_hostName, _hostPort), new UsernamePasswordCredentials(_login, _password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl()); } else {/*from w w w. j a v a 2s. co m*/ if (_logger.isWarnEnabled()) { _logger.warn("Login and password are required"); } } try { setProxyHost(httpClientBuilder); _closeableHttpClient = httpClientBuilder.build(); if (_logger.isDebugEnabled()) { _logger.debug("Configured client for " + _protocol + "://" + _hostName); } } catch (Exception e) { _logger.error("Unable to configure client", e); } }
From source file:aajavafx.EmployeeController.java
public void deleteRow(int id) { try {/*from ww w . j av a 2 s. c om*/ String idToDelete = id + ""; CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password"); provider.setCredentials(AuthScope.ANY, credentials); HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); HttpDelete delete = new HttpDelete(postEmployeesURL + idToDelete); HttpResponse response = httpClient.execute(delete); System.out.println("you want to delete: " + id); } catch (Exception ex) { System.out.println(ex); } }
From source file:org.apache.hadoop.gateway.GatewayMultiFuncTest.java
@Test(timeout = TestUtils.MEDIUM_TIMEOUT) public void testPostWithContentTypeKnox681() throws Exception { LOG_ENTER();/*from w w w .j ava 2 s . com*/ MockServer mock = new MockServer("REPEAT", true); params = new Properties(); params.put("MOCK_SERVER_PORT", mock.getPort()); params.put("LDAP_URL", "ldap://localhost:" + ldapTransport.getAcceptor().getLocalAddress().getPort()); String topoStr = TestUtils.merge(DAT, "topologies/test-knox678-utf8-chars-topology.xml", params); File topoFile = new File(config.getGatewayTopologyDir(), "knox681.xml"); FileUtils.writeStringToFile(topoFile, topoStr); topos.reloadTopologies(); mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED) .content("{\"name\":\"value\"}".getBytes()).contentLength(-1) .contentType("application/json; charset=UTF-8").header("Location", gatewayUrl + "/knox681/repeat"); String uname = "guest"; String pword = uname + "-password"; HttpHost targetHost = new HttpHost("localhost", gatewayPort, "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(uname, pword)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); CloseableHttpClient client = HttpClients.createDefault(); HttpPut request = new HttpPut(gatewayUrl + "/knox681/repeat"); request.addHeader("X-XSRF-Header", "jksdhfkhdsf"); request.addHeader("Content-Type", "application/json"); CloseableHttpResponse response = client.execute(request, context); assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED)); assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat")); assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/json; charset=UTF-8")); String body = new String(IOUtils.toByteArray(response.getEntity().getContent()), Charset.forName("UTF-8")); assertThat(body, is("{\"name\":\"value\"}")); response.close(); client.close(); mock.expect().method("PUT").pathInfo("/repeat-context/").respond().status(HttpStatus.SC_CREATED) .content("<test-xml/>".getBytes()).contentType("application/xml; charset=UTF-8") .header("Location", gatewayUrl + "/knox681/repeat"); client = HttpClients.createDefault(); request = new HttpPut(gatewayUrl + "/knox681/repeat"); request.addHeader("X-XSRF-Header", "jksdhfkhdsf"); request.addHeader("Content-Type", "application/xml"); response = client.execute(request, context); assertThat(response.getStatusLine().getStatusCode(), is(HttpStatus.SC_CREATED)); assertThat(response.getFirstHeader("Location").getValue(), endsWith("/gateway/knox681/repeat")); assertThat(response.getFirstHeader("Content-Type").getValue(), is("application/xml; charset=UTF-8")); body = new String(IOUtils.toByteArray(response.getEntity().getContent()), Charset.forName("UTF-8")); assertThat(the(body), hasXPath("/test-xml")); response.close(); client.close(); mock.stop(); LOG_EXIT(); }
From source file:org.datacleaner.monitor.cluster.HttpClusterManagerFactory.java
@Override public ClusterManager getClusterManager(TenantIdentifier tenant) { final DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager()); if (username != null && password != null) { final CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider(); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); final List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC);//from w w w. j av a 2 s . c o m authpref.add(AuthPolicy.DIGEST); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); credentialsProvider.setCredentials(new AuthScope(null, -1), credentials); } // use the server list final List<String> finalEndpoints = new ArrayList<String>(); for (String endpoint : slaveServerUrls) { if (!endpoint.endsWith("/")) { endpoint = endpoint + "/"; } endpoint = endpoint + "repository/" + tenant.getId() + "/cluster_slave_endpoint"; finalEndpoints.add(endpoint); } return new HttpClusterManager(httpClient, finalEndpoints); }
From source file:com.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). */// ww w . j a va 2 s. co 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(); }