List of usage examples for org.apache.http.client CredentialsProvider setCredentials
void setCredentials(AuthScope authscope, Credentials credentials);
From source file:org.wildfly.core.test.standalone.mgmt.api.core.ResponseAttachmentTestCase.java
private CloseableHttpClient createHttpClient(URL url) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(url.getHost(), url.getPort(), "ManagementRealm", AuthSchemes.DIGEST), new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD)); return HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build(); }
From source file:groovyx.net.http.ApacheHttpBuilder.java
private void basicAuth(final HttpClientContext c, final HttpConfig.Auth auth, final URI uri) { CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, //new AuthScope(uri.getHost(), port(uri)), new UsernamePasswordCredentials(auth.getUser(), auth.getPassword())); c.setCredentialsProvider(provider);// w w w.j a v a2 s. com }
From source file:aajavafx.DevicesController.java
@FXML private void handleSaveButton(ActionEvent event) { //labelError.setText(null); try {//from w w w .ja v a 2 s .co m String devName = DevName.getText(); DevName.clear(); String devID = deviceID.getText(); deviceID.clear(); System.out.println(customerBox.getValue()); String string = (String) customerBox.getValue(); System.out.println("STRING VALUE: " + string); int customerId = Integer.parseInt("" + string.charAt(0)); System.out.println("CUSTOMER ID VALUE:" + customerId); Customers customer = getCustomerByID(customerId); Gson gson = new Gson(); //......for ssl handshake.... CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password"); provider.setCredentials(AuthScope.ANY, credentials); //........ HttpClient httpClient = HttpClientBuilder.create().build(); HttpEntityEnclosingRequestBase HttpEntity = null; //this is the superclass for post, put, get, etc if (deviceID.isEditable()) { //then we are posting a new record HttpEntity = new HttpPost(DevicesCustomerRootURL); //so make a http post object } else { //we are editing a record HttpEntity = new HttpPut(DevicesCustomerRootURL + devID); //so make a http put object } DevicesCustomers devCust = new DevicesCustomers(devID, devName, customer); String jsonString = new String(gson.toJson(devCust)); System.out.println("json string: " + jsonString); StringEntity postString = new StringEntity(jsonString); HttpEntity.setEntity(postString); HttpEntity.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(HttpEntity); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 204) { System.out.println("Device posted successfully"); } else { System.out.println("Server error: " + response.getStatusLine()); } DevName.setEditable(false); deviceID.setEditable(false); customerBox.setDisable(true); } catch (Exception ex) { System.out.println("Error: " + ex); } try { //refresh table tableCustomer.setItems(getDevicesCustomer()); } catch (IOException ex) { Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(DevicesController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:edu.lternet.pasta.doi.EzidRegistrar.java
/** * Registers the resource DOI based on the DataCite metadata object. * /*w w w. ja v a 2 s . c o m*/ * @throws EzidException */ public void registerDataCiteMetadata() throws EzidException { if (this.dataCiteMetadata == null) { String gripe = "registerDataCiteMetadata: DataCite metadata object is null."; throw new EzidException(gripe); } HttpHost httpHost = new HttpHost(this.host, Integer.valueOf(this.port), this.protocol); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.ezidUser, this.ezidPassword); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authScope, credentials); // 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(httpHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); String doi = this.dataCiteMetadata.getDigitalObjectIdentifier().getDoi(); String url = this.getEzidUrl("/id/" + doi); StringBuffer metadata = new StringBuffer(""); metadata.append("datacite: " + this.dataCiteMetadata.toDataCiteXml() + "\n"); metadata.append("_target: " + this.dataCiteMetadata.getLocationUrl() + "\n"); HttpPut httpPut = new HttpPut(url); httpPut.setHeader("Content-type", "text/plain"); HttpEntity stringEntity = null; Integer statusCode = null; String entityString = null; try { stringEntity = new StringEntity(metadata.toString()); httpPut.setEntity(stringEntity); HttpResponse httpResponse = httpClient.execute(httpHost, httpPut, context); statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); entityString = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (ClientProtocolException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (IOException e) { logger.error(e.getMessage()); e.printStackTrace(); } finally { closeHttpClient(httpClient); } logger.info("registerDataCiteMetadata: " + this.dataCiteMetadata.getLocationUrl() + "\n" + entityString); // Test for DOI collision or DOI registration failure if ((statusCode == HttpStatus.SC_BAD_REQUEST) && (entityString != null) && (entityString.contains("identifier already exists"))) { String gripe = "identifier already exists"; throw new EzidException(gripe); } else if (statusCode != HttpStatus.SC_CREATED) { logger.error(this.dataCiteMetadata.toDataCiteXml()); String gripe = "DOI registration failed for: " + doi; throw new EzidException(gripe); } }
From source file:microsoft.exchange.webservices.data.HttpClientWebRequest.java
/** * Prepare connection/*from w w w . ja v a 2 s .c om*/ * * @throws microsoft.exchange.webservices.data.EWSHttpException the eWS http exception */ @Override public void prepareConnection() throws EWSHttpException { try { HttpClientBuilder builder = HttpClients.custom(); builder.setConnectionManager(this.httpClientConnMng); //create the cookie store if (cookieStore == null) { cookieStore = new BasicCookieStore(); } builder.setDefaultCookieStore(cookieStore); if (getProxy() != null) { HttpHost proxy = new HttpHost(getProxy().getHost(), getProxy().getPort()); builder.setProxy(proxy); if (HttpProxyCredentials.isProxySet()) { NTCredentials cred = new NTCredentials(HttpProxyCredentials.getUserName(), HttpProxyCredentials.getPassword(), "", HttpProxyCredentials.getDomain()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxy), cred); builder.setDefaultCredentialsProvider(credsProvider); } } if (getUserName() != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(getUserName(), getPassword(), "", getDomain())); builder.setDefaultCredentialsProvider(credsProvider); } //fix socket config SocketConfig sc = SocketConfig.custom().setSoTimeout(getTimeout()).build(); builder.setDefaultSocketConfig(sc); RequestConfig.Builder rcBuilder = RequestConfig.custom(); rcBuilder.setAuthenticationEnabled(true); rcBuilder.setConnectionRequestTimeout(getTimeout()); rcBuilder.setConnectTimeout(getTimeout()); rcBuilder.setRedirectsEnabled(isAllowAutoRedirect()); rcBuilder.setSocketTimeout(getTimeout()); // fix issue #144 + #160: if we used NTCredentials from above: these are NT credentials if (getUserName() != null) { ArrayList<String> authPrefs = new ArrayList<String>(); authPrefs.add(AuthSchemes.NTLM); rcBuilder.setTargetPreferredAuthSchemes(authPrefs); } // builder.setDefaultRequestConfig(rcBuilder.build()); httpPostReq = new HttpPost(getUrl().toString()); httpPostReq.addHeader("Content-type", getContentType()); //httpPostReq.setDoAuthentication(true); httpPostReq.addHeader("User-Agent", getUserAgent()); httpPostReq.addHeader("Accept", getAccept()); httpPostReq.addHeader("Keep-Alive", "300"); httpPostReq.addHeader("Connection", "Keep-Alive"); if (isAcceptGzipEncoding()) { httpPostReq.addHeader("Accept-Encoding", "gzip,deflate"); } if (getHeaders().size() > 0) { for (Map.Entry<String, String> httpHeader : getHeaders().entrySet()) { httpPostReq.addHeader(httpHeader.getKey(), httpHeader.getValue()); } } //create the client client = builder.build(); } catch (Exception er) { er.printStackTrace(); } }
From source file:org.callimachusproject.webdriver.helpers.BrowserFunctionalTestCase.java
private void putTestData(String info, String jobId, String data, CloseableHttpClient client) throws IOException, ClientProtocolException { String username = decode(info.substring(0, info.indexOf(':')), "UTF-8"); String password = decode(info.substring(info.indexOf(':') + 1), "UTF-8"); UsernamePasswordCredentials cred = new UsernamePasswordCredentials(username, password); AuthScope scope = new AuthScope("saucelabs.com", 80); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(scope, cred); HttpClientContext ctx = HttpClientContext.create(); ctx.setCredentialsProvider(credsProvider); HttpPut put = new HttpPut("http://saucelabs.com/rest/v1/" + username + "/jobs/" + jobId); put.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON)); client.execute(put, new ResponseHandler<Void>() { public Void handleResponse(HttpResponse response) throws ClientProtocolException, IOException { if (300 <= response.getStatusLine().getStatusCode()) { System.err.println(EntityUtils.toString(response.getEntity())); }/* w w w .j a va 2s . co m*/ assertTrue(response.getStatusLine().toString(), 300 > response.getStatusLine().getStatusCode()); return null; } }, ctx); }
From source file:edu.lternet.pasta.doi.EzidRegistrar.java
/** * Login to the EZID web service API system and return a valid session * identifier.//ww w.j a v a2 s . c o m * * @return The EZID session id * @throws EzidException */ public void login() throws EzidException { String sessionId = null; /* * The following set of code sets up Preemptive Authentication for the HTTP * CLIENT and is done so at the warning stated within the Apache * Http-Components Client tutorial here: * http://hc.apache.org/httpcomponents- * client-ga/tutorial/html/authentication.html#d5e1031 */ HttpHost httpHost = new HttpHost(this.host, Integer.valueOf(this.port), this.protocol); CloseableHttpClient httpClient = HttpClientBuilder.create().build(); AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.ezidUser, this.ezidPassword); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(authScope, credentials); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(httpHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); HttpGet httpGet = new HttpGet(this.getEzidUrl("/login")); HttpResponse response = null; Header[] headers = null; Integer statusCode = null; try { response = httpClient.execute(httpHost, httpGet, context); headers = response.getAllHeaders(); statusCode = (Integer) response.getStatusLine().getStatusCode(); logger.info("STATUS: " + statusCode.toString()); } catch (UnsupportedEncodingException e) { logger.error(e); e.printStackTrace(); } catch (ClientProtocolException e) { logger.error(e); e.printStackTrace(); } catch (IOException e) { logger.error(e); e.printStackTrace(); } finally { closeHttpClient(httpClient); } if (statusCode == HttpStatus.SC_OK) { String headerName = null; String headerValue = null; // Loop through all headers looking for the "Set-Cookie" header. for (int i = 0; i < headers.length; i++) { headerName = headers[i].getName(); if (headerName.equals("Set-Cookie")) { headerValue = headers[i].getValue(); sessionId = this.getSessionId(headerValue); logger.info("Session: " + sessionId); } } } else { String gripe = "login: failed EZID login."; throw new EzidException(gripe); } this.sessionId = sessionId; }
From source file:org.eobjects.datacleaner.monitor.pentaho.PentahoCarteClient.java
private HttpClient createHttpClient(PentahoJobType pentahoJobType) { final String hostname = pentahoJobType.getCarteHostname(); final Integer port = pentahoJobType.getCartePort(); final String username = pentahoJobType.getCarteUsername(); final String password = pentahoJobType.getCartePassword(); final DefaultHttpClient httpClient = new DefaultHttpClient(); 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 . ja v a 2s.co m*/ authpref.add(AuthPolicy.DIGEST); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); credentialsProvider.setCredentials(new AuthScope(hostname, port), credentials); return httpClient; }