List of usage examples for org.apache.http.client CredentialsProvider setCredentials
void setCredentials(AuthScope authscope, Credentials credentials);
From source file:com.sun.jersey.client.apache4.impl.AuthTest.java
public void testPreemptiveAuth() { ResourceConfig rc = new DefaultResourceConfig(PreemptiveAuthResource.class); rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, LoggingFilter.class.getName()); startServer(rc);//from w w w . j a v a 2 s . c om CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password")); DefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config(); config.getProperties().put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER, credentialsProvider); config.getProperties().put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION, true); ApacheHttpClient4 c = ApacheHttpClient4.create(config); WebResource r = c.resource(getUri().build()); assertEquals("GET", r.get(String.class)); }
From source file:com.sun.jersey.client.apache4.impl.AuthTest.java
public void testPreemptiveAuthPost() { ResourceConfig rc = new DefaultResourceConfig(PreemptiveAuthResource.class); rc.getProperties().put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, LoggingFilter.class.getName()); startServer(rc);/*from ww w . j a v a 2 s . c o m*/ CredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("name", "password")); DefaultApacheHttpClient4Config config = new DefaultApacheHttpClient4Config(); config.getProperties().put(ApacheHttpClient4Config.PROPERTY_CREDENTIALS_PROVIDER, credentialsProvider); config.getProperties().put(ApacheHttpClient4Config.PROPERTY_PREEMPTIVE_BASIC_AUTHENTICATION, true); ApacheHttpClient4 c = ApacheHttpClient4.create(config); WebResource r = c.resource(getUri().build()); assertEquals("POST", r.post(String.class, "POST")); }
From source file:org.activiti.webservice.WebServiceSendActivitiBehavior.java
public void execute(ActivityExecution execution) throws Exception { 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); ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines(); Object payload = scriptingEngines.evaluate(payloadExpressionValue, languageValue, execution); if (endpointUrlValue.startsWith("vm:")) { LocalWebServiceClient client = this.getWebServiceContext().getClient(); WebServiceMessage message = new DefaultWebServiceMessage(payload, this.getWebServiceContext()); WebServiceMessage resultMessage = client.send(endpointUrlValue, message); Object result = resultMessage.getPayload(); if (resultVariableValue != null) { execution.setVariable(resultVariableValue, result); }//w w w . j a va 2 s .c o m } 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, "webservice-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 ActivitiException("Error setting message payload", e); } byte[] responseBytes = null; try { // execute the POST request HttpResponse response = client.execute(request); responseBytes = IOUtils.toByteArray(response.getEntity().getContent()); } 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 ActivitiException("Failed to read response value", e); } } } this.leave(execution); }
From source file:fr.univsavoie.ltp.client.LoginActivity.java
/** * Pav de code permetant de se connecter de faon scuris au serveur *//* w ww .j a v a2 s .c o m*/ private void auth() { try { 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.getText().toString(), password.getText().toString()); authCred.setCredentials(AuthScope.ANY, creds); httpClient.addRequestInterceptor(preemptiveAuth, 0); httpClient.setCredentialsProvider(authCred); } catch (Exception e) { Log.e("Catch", "Auth: " + e.getLocalizedMessage()); } }
From source file:tools.devnull.boteco.client.rest.impl.DefaultRestConfiguration.java
@Override public RestConfiguration withAuthentication(String user, String password) { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); CredentialsProvider provider = new BasicCredentialsProvider(); URI uri = request.getURI();//from w ww . j ava 2 s. co m authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth); provider.setCredentials(new AuthScope(uri.getHost(), AuthScope.ANY_PORT), new UsernamePasswordCredentials(user, password)); this.context.setCredentialsProvider(provider); this.context.setAuthCache(authCache); return this; }
From source file:org.syncany.operations.init.ApplicationLink.java
private CloseableHttpClient createHttpClient() { RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(2000) .setConnectTimeout(2000).setRedirectsEnabled(false); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // do we use a https proxy? String proxyHost = System.getProperty("https.proxyHost"); String proxyPortStr = System.getProperty("https.proxyPort"); String proxyUser = System.getProperty("https.proxyUser"); String proxyPassword = System.getProperty("https.proxyPassword"); if (proxyHost != null && proxyPortStr != null) { try {// ww w . j a va 2 s . c o m Integer proxyPort = Integer.parseInt(proxyPortStr); requestConfigBuilder.setProxy(new HttpHost(proxyHost, proxyPort)); logger.log(Level.INFO, "Using proxy: " + proxyHost + ":" + proxyPort); if (proxyUser != null && proxyPassword != null) { logger.log(Level.INFO, "Proxy required credentials; using '" + proxyUser + "' (username) and *** (hidden password)"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, proxyPassword)); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); } } catch (NumberFormatException e) { logger.log(Level.WARNING, "Invalid proxy settings found. Not using proxy.", e); } } httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()); return httpClientBuilder.build(); }
From source file:com.shenit.commons.utils.HttpUtils.java
/** * Create a basic login context.//w w w. j ava 2s .co m * * @param username * @param pass * @return */ public static HttpContext basicLoginContext(String username, String pass) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, pass); provider.setCredentials(AuthScope.ANY, credentials); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(provider); return context; }
From source file:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java
/** * Constructor. Create a session.// w w w . ja v a 2s .c o m */ public JiraSession(String clientId, String clientSecret, String protocol, String host, int port, String path, String proxyHost, int proxyPort, String proxyDomain, String proxyUsername, String proxyPassword) throws ManifoldCFException { this.host = new HttpHost(host, port, protocol); this.path = path; this.clientId = clientId; this.clientSecret = clientSecret; int socketTimeout = 900000; int connectionTimeout = 60000; javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory(); SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory( new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); connectionManager = new PoolingHttpClientConnectionManager(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // If authentication needed, set that if (clientId != null) { credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(clientId, clientSecret)); } RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true) .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout); // If there's a proxy, set that too. if (proxyHost != null && proxyHost.length() > 0) { // Configure proxy authentication if (proxyUsername != null && proxyUsername.length() > 0) { if (proxyPassword == null) proxyPassword = ""; if (proxyDomain == null) proxyDomain = ""; credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain)); } HttpHost proxy = new HttpHost(proxyHost, proxyPort); requestBuilder.setProxy(proxy); } httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1) .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build()) .setDefaultSocketConfig( SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build()) .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()).build(); }
From source file:org.guvnor.ala.wildfly.access.WildflyClient.java
public WildflyAppState getAppState(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("read-resource"); operation.get("address").add("deployment", deploymentName); operation.get("resolve-expressions").set("true"); post.setEntity(new StringEntity(operation.toJSONString(true), APPLICATION_JSON)); try {//from w ww . ja v a 2 s . c o m HttpResponse response = httpclient.execute(post); String json = EntityUtils.toString(response.getEntity()); JsonParser parser = new JsonParser(); JsonElement element = parser.parse(json); // use the isxxx methods to find out the type of jsonelement. In our // example we know that the root object is the Albums object and // contains an array of dataset objects if (element.isJsonObject()) { JsonObject outcome = element.getAsJsonObject(); JsonElement resultElement = outcome.get("result"); String enabled = null; if (resultElement != null) { JsonObject result = resultElement.getAsJsonObject(); enabled = result.get("enabled").getAsString(); } String state; if (Boolean.TRUE.toString().equals(enabled)) { state = RUNNING; } else if (Boolean.FALSE.toString().equals(enabled)) { state = STOPPED; } else { state = UNKNOWN; } return new WildflyAppState(state, new Date()); } } catch (IOException ex) { LOG.error("Error Getting App State : " + ex.getMessage(), ex); throw new WildflyClientException("Error Getting App State : " + ex.getMessage(), ex); } return new WildflyAppState(UNKNOWN, new Date()); }
From source file:org.guvnor.ala.wildfly.access.WildflyClient.java
public int deploy(File file) throws WildflyClientException { // the digest auth backend CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, managementPort), new UsernamePasswordCredentials(user, password)); CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build(); HttpPost post = new HttpPost("http://" + host + ":" + managementPort + "/management-upload"); post.addHeader("X-Management-Client-Name", "HAL"); // the file to be uploaded FileBody fileBody = new FileBody(file); // the DMR operation ModelNode operation = new ModelNode(); operation.get("address").add("deployment", file.getName()); operation.get("operation").set("add"); operation.get("runtime-name").set(file.getName()); operation.get("enabled").set(true); operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used ByteArrayOutputStream bout = new ByteArrayOutputStream(); try {//from ww w . ja v a 2 s . c o m operation.writeBase64(bout); } catch (IOException ex) { getLogger(WildflyClient.class.getName()).log(SEVERE, null, ex); } // the multipart MultipartEntityBuilder builder = create(); builder.setMode(BROWSER_COMPATIBLE); builder.addPart("uploadFormElement", fileBody); builder.addPart("operation", new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob")); HttpEntity entity = builder.build(); post.setEntity(entity); try { HttpResponse response = httpclient.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { throw new WildflyClientException("Error Deploying App Status Code: " + statusCode); } return statusCode; } catch (IOException ex) { LOG.error("Error Deploying App : " + ex.getMessage(), ex); throw new WildflyClientException("Error Deploying App : " + ex.getMessage(), ex); } }