List of usage examples for org.apache.http.client CredentialsProvider setCredentials
void setCredentials(AuthScope authscope, Credentials credentials);
From source file:majordodo.client.http.HTTPClientConnection.java
private HttpClientContext getContext() throws IOException { if (context == null) { BrokerAddress broker = getBroker(); String scheme = broker.getProtocol(); HttpHost targetHost = new HttpHost(broker.getAddress(), broker.getPort(), scheme); context = HttpClientContext.create(); if (configuration.getUsername() != null && !configuration.getUsername().isEmpty()) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME), creds); BasicAuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); }//from w ww.ja va 2 s . c o m } return context; }
From source file:aajavafx.CustomerMedicineController.java
@FXML private void handleRemoveButton(ActionEvent event) { //remove is annotated with @DELETE on server so we use a HttpDelete object try {/*w ww. j av a 2 s .com*/ //.......SSL Update.... CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password"); provider.setCredentials(AuthScope.ANY, credentials); //...... HttpClient httpClient = HttpClientBuilder.create().build(); String idToDelete = startDate.getText(); //add the id to the end of the URL so this will call the method at MainServerREST/api/visitors/id HttpDelete delete = new HttpDelete(MedicineCustomerRootURL + idToDelete); HttpResponse response = httpClient.execute(delete); System.out.println("response from server " + response.getStatusLine()); } catch (Exception ex) { System.out.println(ex); } try { //refresh table tableCustomer.setItems(getCustomersTakesMedicines()); } catch (IOException ex) { Logger.getLogger(VisitorController.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(VisitorController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.opennms.opennms.pris.plugins.defaults.source.HttpRequisitionSource.java
@Override public Object dump() throws Exception { Requisition requisition = null;/*w ww . j av a2 s.co m*/ if (getUrl() != null) { HttpClientBuilder builder = HttpClientBuilder.create(); // If username and password was found, inject the credentials if (getUserName() != null && getPassword() != null) { CredentialsProvider provider = new BasicCredentialsProvider(); // Create the authentication scope AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM); // Create credential pair UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getUserName(), getPassword()); // Inject the credentials provider.setCredentials(scope, credentials); // Set the default credentials provider builder.setDefaultCredentialsProvider(provider); } HttpClient client = builder.build(); HttpGet request = new HttpGet(getUrl()); HttpResponse response = client.execute(request); try { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); JAXBContext jaxbContext = JAXBContext.newInstance(Requisition.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); requisition = (Requisition) jaxbUnmarshaller.unmarshal(bufferedReader); } catch (JAXBException e) { LOGGER.error("The response did not contain a valid requisition as xml.", e); } LOGGER.debug("Got Requisition {}", requisition); } else { LOGGER.error("Parameter requisition.url is missing in requisition.properties"); } if (requisition == null) { LOGGER.error("Requisition is null for unknown reasons"); return null; } LOGGER.info("HttpRequisitionSource delivered for requisition '{}'", requisition.getNodes().size()); return requisition; }
From source file:org.opensaml.util.http.HttpClientBuilder.java
/** * Constructs an {@link HttpClient} using the settings of this builder. * /* w w w. j ava2s. c om*/ * @return the constructed client */ public HttpClient buildClient() { final DefaultHttpClient client = new DefaultHttpClient(buildConnectionManager()); client.addRequestInterceptor(new RequestAcceptEncoding()); client.addResponseInterceptor(new ResponseContentEncoding()); final HttpParams httpParams = client.getParams(); if (socketLocalAddress != null) { httpParams.setParameter(AllClientPNames.LOCAL_ADDRESS, socketLocalAddress); } if (socketTimeout > 0) { httpParams.setIntParameter(AllClientPNames.SO_TIMEOUT, socketTimeout); } httpParams.setIntParameter(AllClientPNames.SOCKET_BUFFER_SIZE, socketBufferSize); if (connectionTimeout > 0) { httpParams.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, connectionTimeout); } httpParams.setBooleanParameter(AllClientPNames.STALE_CONNECTION_CHECK, connectionStalecheck); if (connectionProxyHost != null) { final HttpHost proxyHost = new HttpHost(connectionProxyHost, connectionProxyPort); httpParams.setParameter(AllClientPNames.DEFAULT_PROXY, proxyHost); if (connectionProxyUsername != null && connectionProxyPassword != null) { final CredentialsProvider credProvider = client.getCredentialsProvider(); credProvider.setCredentials(new AuthScope(connectionProxyHost, connectionProxyPort), new UsernamePasswordCredentials(connectionProxyUsername, connectionProxyPassword)); } } httpParams.setBooleanParameter(AllClientPNames.HANDLE_REDIRECTS, httpFollowRedirects); httpParams.setParameter(AllClientPNames.HTTP_CONTENT_CHARSET, httpContentCharSet); return client; }
From source file:aajavafx.CustomerMedicineController.java
public ObservableList<CustomersTakesMedicines> getCustomersTakesMedicines() throws IOException, JSONException { ObservableList<CustomersTakesMedicines> ctMeds = FXCollections.observableArrayList(); //Managers manager = new Managers(); Gson gson = new Gson(); JSONObject jo = new JSONObject(); //........SSL Update CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("EMPLOYEE", "password"); provider.setCredentials(AuthScope.ANY, credentials); HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); HttpGet get = new HttpGet("http://localhost:8080/MainServerREST/api/customersmedicines/"); HttpResponse response = client.execute(get); System.out.println("RESPONSE IS: " + response); //................... // JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(MedicineRootURL), Charset.forName("UTF-8"))); JSONArray jsonArray = new JSONArray( IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8"))); //JSONArray jsonArray = new JSONArray(IOUtils.toString(new URL(MedicineCustomerRootURL), Charset.forName("UTF-8"))); System.out.println(jsonArray); for (int i = 0; i < jsonArray.length(); i++) { //get the main json object, which contains customer object, pk object, dosage, start date, schedule and medicine object jo = (JSONObject) jsonArray.getJSONObject(i); System.out.println("JSON OBJECT #" + i + " " + jo); //get the customer json sub-string JSONObject custObj = (JSONObject) jo.get("customers"); Customers customer = gson.fromJson(custObj.toString(), Customers.class); //get the primary key json sub-string JSONObject pkObj = (JSONObject) jo.get("customersTakesMedicinesPK"); CustomersTakesMedicinesPK ctmPK = gson.fromJson(pkObj.toString(), CustomersTakesMedicinesPK.class); //get the medicine json sub-string JSONObject medObj = (JSONObject) jo.get("medicines"); Medicines medicine = gson.fromJson(medObj.toString(), Medicines.class); //get the individual strings String dose = jo.getString("medDosage"); String startDate = jo.getString("medStartDate"); double schedule = jo.getDouble("medicationintakeschedule"); CustomersTakesMedicines cuTaMe = new CustomersTakesMedicines(ctmPK, dose, startDate, schedule); cuTaMe.setCustomers(customer);/*from w w w .ja v a 2 s.c om*/ cuTaMe.setMedicines(medicine); ctMeds.add(cuTaMe); } return ctMeds; }
From source file:org.iipg.hurricane.jmx.client.JMXClientBuilder.java
private void setupProxyIfNeeded(HttpClientBuilder builder) { if (httpProxy != null) { builder.setProxy(new HttpHost(httpProxy.getHost(), httpProxy.getPort())); if (httpProxy.getUser() != null) { AuthScope proxyAuthScope = new AuthScope(httpProxy.getHost(), httpProxy.getPort()); UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(httpProxy.getUser(), httpProxy.getPass()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(proxyAuthScope, proxyCredentials); builder.setDefaultCredentialsProvider(credentialsProvider); }/* ww w .j a v a 2s .c o m*/ } }
From source file:fr.univsavoie.ltp.client.map.Session.java
/** * Procdure qui s'authentifie sur le serveur REST avec les donnes utilisateurs de faon scuris (protocole HTTPS). * Appeler secureAuth() avant chaque nouvelles requtes HTTP (get, post, ...) *//* w ww.j a v a 2s. co m*/ private void secureAuth() { try { // Instance de SharedPreferences pour lire les donnes dans un fichier SharedPreferences myPrefs = activity.getSharedPreferences("UserPrefs", activity.MODE_WORLD_READABLE); String login = myPrefs.getString("Login", null); String password = myPrefs.getString("Password", null); HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; // Setup a custom SSL Factory object which simply ignore the certificates validation and accept all type of self signed certificates SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null); sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Enable HTTP parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object. SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sslFactory, 443)); // Create a new connection manager using the newly created registry and then create a new HTTP client using this connection manager ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); httpClient = new DefaultHttpClient(ccm, params); CredentialsProvider authCred = new BasicCredentialsProvider(); Credentials creds = new UsernamePasswordCredentials(login, password); authCred.setCredentials(AuthScope.ANY, creds); httpClient.addRequestInterceptor(preemptiveAuth, 0); httpClient.setCredentialsProvider(authCred); } catch (KeyManagementException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } }
From source file:com.fourspaces.couchdb.Session.java
/** * Constructor for obtaining a Session with an HTTP-AUTH username/password * and (optionally) a secure connection This isn't supported by CouchDB - * you need a proxy in front to use this * * @param host - hostname/*from ww w .j av a2 s.c om*/ * @param port - port to use * @param user - username * @param pass - password * @param usesAuth * @param secure - use an SSL connection? */ public Session(String host, int port, String user, String pass, boolean usesAuth, boolean secure) { this.host = host; this.port = port; this.user = user; this.pass = pass; this.usesAuth = usesAuth; this.secure = secure; PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf).register("https", sslsf).build(); this.connManager = new PoolingHttpClientConnectionManager(r); this.requestConfig = RequestConfig.custom().setConnectTimeout(15 * 1000).setSocketTimeout((30 * 1000)) .setAuthenticationEnabled(usesAuth).build(); this.httpContext = HttpClientContext.create(); if (user != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass)); this.httpContext.setCredentialsProvider(credsProvider); } this.httpClient = createHttpClient(); }