List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme
public BasicScheme()
From source file:com.redhat.jenkins.nodesharing.RestEndpoint.java
private @Nonnull HttpClientContext getAuthenticatingContext(@Nonnull HttpRequestBase method) { AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(URIUtils.extractHost(method.getURI()), basicAuth); CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new org.apache.http.auth.UsernamePasswordCredentials( creds.getUsername(), creds.getPassword().getPlainText())); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(provider); context.setAuthCache(authCache);//from w w w. j a v a 2s .c om return context; }
From source file:com.github.tomakehurst.wiremock.testsupport.WireMockTestClient.java
public WireMockResponse getWithPreemptiveCredentials(String url, int port, String username, String password) { HttpHost target = new HttpHost("localhost", port); HttpClient httpClient = httpClientWithPreemptiveAuth(target, username, password); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth);//from ww w . ja va 2 s .com HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); try { HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(target, httpget, localContext); return new WireMockResponse(response); } catch (IOException e) { return throwUnchecked(e, WireMockResponse.class); } }
From source file:io.kahu.hawaii.util.call.http.HttpRequestBuilder.java
private void addAuthentication(AbortableHttpRequest<T> request, URI uri) { if (credentials != null) { CredentialsProvider credentialsProvider = null; switch (credentials.getAuthenticationType()) { case BASIC: // fall-through to default default:// w w w. ja v a 2 s .co m BasicScheme authenticationScheme = new BasicScheme(); credentialsProvider = new BasicCredentialsProvider(); // Explicitly set the AuthScope to ANY_REALM in order to get // 'preemptive authentication' to work credentialsProvider.setCredentials( new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, authenticationScheme.getSchemeName()), new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword())); // Create an auth cache for preemptive authentication. AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), authenticationScheme); request.getHttpClientContext().setAuthCache(authCache); break; } request.getHttpClientContext().setCredentialsProvider(credentialsProvider); } }
From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java
@Test public void pre_emptive_basic_authentication_scenario() throws IOException { System.out.println("pre_emptive_basic_authentication_scenario"); privateAppFilter.setAuthenticationEntryPoint(PrivateAppFilter.AuthenticationEntryPoint.BASIC_AUTH); httpClient.getCredentialsProvider().setCredentials( new AuthScope(httpHost.getHostName(), httpHost.getPort()), new UsernamePasswordCredentials(accessKey, secretKey)); // 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);/* ww w . ja v a 2 s .c om*/ // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpGet httpget = new HttpGet("/"); for (int i = 0; i < 3; i++) { HttpResponse response = httpClient.execute(httpHost, httpget, localcontext); assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK)); assertThat(response.containsHeader("x-response"), is(true)); dumpHttpResponse(response); EntityUtils.consumeQuietly(response.getEntity()); } }
From source file:edu.lternet.pasta.doi.EzidRegistrar.java
/** * Registers the resource DOI based on the DataCite metadata object. * //from w w w. j av a 2 s. c om * @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:org.apache.hadoop.gateway.GatewayMultiFuncTest.java
@Test(timeout = TestUtils.MEDIUM_TIMEOUT) public void testPostWithContentTypeKnox681() throws Exception { LOG_ENTER();// w w w .j av a 2 s . c om 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:ca.etsmtl.applets.etsmobile.ProfileActivity.java
private void getBandwith(String phase, String appt) { appt_input.setEnabled(false);//from w ww . j ava 2 s. c om phase_input.setEnabled(false); final Editor edit = prefs.edit(); creds.setPhase(phase); creds.setAppt(appt); edit.putString(UserCredentials.REZ, phase); edit.putString(UserCredentials.APPT, appt); edit.commit(); // get bandwidth from cooptel, parse html, extract floats, etc etc new AsyncTask<String, Void, float[]>() { final Pattern usageRegex = Pattern.compile( "<TR><TD>(.*)</TD><TD>(.*)</TD><TD ALIGN=\"RIGHT\">(.*)</TD><TD ALIGN=\"RIGHT\">(.*)</TD></TR>"); final Pattern quotaRegex = Pattern.compile( "<TR><TD>Quota permis pour la période</TD><TD ALIGN=\"RIGHT\">(.*)</TD></TD></TR>"); @Override protected float[] doInBackground(String... params) { final float[] result = new float[2]; try { final HttpGet get = new HttpGet(URI.create( String.format("http://www2.cooptel.qc.ca/services/temps/?mois=%d&cmd=Visualiser", Calendar.getInstance().get(Calendar.MONTH) + 1))); final BasicScheme scheme = new BasicScheme(); final Credentials credentials = new UsernamePasswordCredentials( "ets-res" + params[0] + "-" + params[1], "ets" + params[1]); try { final Header h = scheme.authenticate(credentials, get); get.addHeader(h); final HttpClient client = new DefaultHttpClient(); final HttpResponse re = client.execute(get); // if HTTP200 if (re.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { final String ent = EntityUtils.toString(re.getEntity()); final Matcher matcher = usageRegex.matcher(ent); float total = 0; // String[] usageResult = matcher.; // parse all results while (matcher.find()) { final Number upload = Float.parseFloat(matcher.group(3)); final Number download = Float.parseFloat(matcher.group(4)); total += upload.floatValue(); total += download.floatValue(); } final Matcher quotaResult = quotaRegex.matcher(ent); float totalBandwithAvail = 0; if (quotaResult.find()) { totalBandwithAvail = Float.parseFloat(quotaResult.group(1)); } result[0] = total / 1024; result[1] = totalBandwithAvail / 1024; } } catch (final AuthenticationException e) { e.printStackTrace(); } } catch (final IOException e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(float[] result) { handlerBandwith.obtainMessage(2, result).sendToTarget(); super.onPostExecute(result); } }.execute(phase, appt); }
From source file:org.duracloud.common.web.RestHttpHelper.java
private HttpResponse executeRequest(String url, Method method, HttpEntity requestEntity, Map<String, String> headers) throws IOException { if (url == null || url.length() == 0) { throw new IllegalArgumentException("URL must be a non-empty value"); }// w ww . j a v a 2s. com HttpRequestBase httpRequest = method.getMethod(url, requestEntity); if (headers != null && headers.size() > 0) { addHeaders(httpRequest, headers); } if (log.isDebugEnabled()) { log.debug(loggingRequestText(url, method, requestEntity, headers)); } org.apache.http.HttpResponse response; if (null != credsProvider) { HttpClientBuilder builder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider); if (socketTimeoutMs > -1) { BasicHttpClientConnectionManager cm = new BasicHttpClientConnectionManager(); cm.setSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeoutMs).build()); builder.setConnectionManager(cm); } CloseableHttpClient httpClient = buildClient(builder, method); // Use preemptive basic auth URI requestUri = httpRequest.getURI(); HttpHost target = new HttpHost(requestUri.getHost(), requestUri.getPort(), requestUri.getScheme()); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); response = httpClient.execute(httpRequest, localContext); } else { CloseableHttpClient httpClient = buildClient(HttpClients.custom(), method); response = httpClient.execute(httpRequest); } HttpResponse httpResponse = new HttpResponse(response); if (log.isDebugEnabled()) { log.debug(loggingResponseText(httpResponse)); } return httpResponse; }
From source file:de.javakaffee.web.msm.integration.TestUtils.java
private static HttpResponse executeRequestWithAuth(final DefaultHttpClient client, final HttpUriRequest method, final Credentials credentials) throws IOException, ClientProtocolException { client.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); final BasicHttpContext localcontext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local // execution context final BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); // System.out.println( "cookies: " + method.getParams().getCookiePolicy() ); //method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); return client.execute(method, localcontext); }