List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme
public BasicScheme()
From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java
@Override public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException { final HttpUriRequest request = getUriHttpRequest(clientRequest); final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request); try {/*from www . ja v a 2 s .c o m*/ final CloseableHttpResponse response; final HttpClientContext context = HttpClientContext.create(); if (preemptiveBasicAuth) { final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicScheme = new BasicScheme(); authCache.put(getHost(request), basicScheme); context.setAuthCache(authCache); } response = client.execute(getHost(request), request, context); HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName()); final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null ? Statuses.from(response.getStatusLine().getStatusCode()) : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); final ClientResponse responseContext = new ApacheConnectorClientResponse(status, clientRequest, response); final List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null && !redirectLocations.isEmpty()) { responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1)); } final Header[] respHeaders = response.getAllHeaders(); final MultivaluedMap<String, String> headers = responseContext.getHeaders(); for (final Header header : respHeaders) { final String headerName = header.getName(); List<String> list = headers.get(headerName); if (list == null) { list = new ArrayList<String>(); } list.add(header.getValue()); headers.put(headerName, list); } final HttpEntity entity = response.getEntity(); if (entity != null) { if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) { headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength())); } final Header contentEncoding = entity.getContentEncoding(); if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) { headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue()); } } try { responseContext.setEntityStream(new HttpClientResponseInputStream(response)); } catch (final IOException e) { LOGGER.log(Level.SEVERE, null, e); } return responseContext; } catch (final Exception e) { throw new ProcessingException(e); } }
From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java
protected HttpResponse getHttpResponse(final HttpUriRequest httpRequest, final URI uri) throws DSSException { final HttpClient client = getHttpClient(uri); final String host = uri.getHost(); final int port = uri.getPort(); final String scheme = uri.getScheme(); final HttpHost targetHost = new HttpHost(host, port, scheme); // 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(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); try {/*from w ww . j ava2 s .c o m*/ final HttpResponse response = client.execute(targetHost, httpRequest, localContext); return response; } catch (IOException e) { throw new DSSException(e); } }
From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java
@Override public String postDataToDHISEndpoint(String endpoint, String data) { String url = Context.getAdministrationService().getGlobalProperty("dhisconnector.url"); String user = Context.getAdministrationService().getGlobalProperty("dhisconnector.user"); String pass = Context.getAdministrationService().getGlobalProperty("dhisconnector.pass"); DefaultHttpClient client = null;/*from w w w . ja v a 2 s . co m*/ String payload = ""; String extension = ".json"; try { URL dhisURL = new URL(url); String host = dhisURL.getHost(); int port = dhisURL.getPort(); HttpHost targetHost = new HttpHost(host, port, dhisURL.getProtocol()); client = new DefaultHttpClient(); BasicHttpContext localcontext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(dhisURL.getPath() + endpoint + (configs.useAdxInsteadOfDxf() ? (endpoint.indexOf("?") > -1 ? "&" : "?" + "dataElementIdScheme=CODE&orgUnitIdScheme=CODE&idScheme=CODE") : "")); Credentials creds = new UsernamePasswordCredentials(user, pass); Header bs = new BasicScheme().authenticate(creds, httpPost, localcontext); httpPost.addHeader("Authorization", bs.getValue()); if (configs.useAdxInsteadOfDxf()) { extension = ".xml"; httpPost.addHeader("Content-Type", "application/xml+adx"); httpPost.addHeader("Accept", "application/xml"); } else { httpPost.addHeader("Content-Type", "application/json"); httpPost.addHeader("Accept", "application/json"); } httpPost.setEntity(new StringEntity(data)); HttpResponse response = client.execute(targetHost, httpPost, localcontext); HttpEntity entity = response.getEntity(); if (entity != null) { payload = EntityUtils.toString(entity); } else { backUpData(endpoint, data, extension); System.out.println("Failed to get entity from dhis2 server, network failure!"); } } catch (Exception ex) { backUpData(endpoint, data, extension); ex.printStackTrace(); } finally { if (client != null) { client.getConnectionManager().shutdown(); } } return payload; }
From source file:de.undercouch.gradle.tasks.download.DownloadAction.java
@Override public void authScheme(Object authScheme) { if (authScheme instanceof AuthScheme) { this.authScheme = (AuthScheme) authScheme; } else if (authScheme instanceof String) { String sa = (String) authScheme; if (sa.equalsIgnoreCase("Basic")) { this.authScheme = new BasicScheme(); } else if (sa.equalsIgnoreCase("Digest")) { this.authScheme = new DigestScheme(); } else {/*from w w w . j av a2 s .c o m*/ throw new IllegalArgumentException( "Invalid authentication scheme: " + "'" + sa + "'. Valid values are 'Basic' and 'Digest'."); } } else { throw new IllegalArgumentException("Invalid authentication " + "scheme. Provide either a String or an instance of " + AuthScheme.class.getName() + "."); } }
From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java
private void put(int wait, Resource resource, File source, HttpEntity httpEntity, String url) throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException { //Parent directories need to be created before posting try {//ww w . j a v a 2 s . c om mkdirs(PathUtils.dirname(resource.getName())); } catch (HttpException he) { fireTransferError(resource, he, TransferEvent.REQUEST_GET); } catch (IOException e) { fireTransferError(resource, e, TransferEvent.REQUEST_GET); } // preemptive for put // TODO: is it a good idea, though? 'Expect-continue' handshake would serve much better Repository repo = getRepository(); HttpHost targetHost = new HttpHost(repo.getHost(), repo.getPort(), repo.getProtocol()); AuthScope targetScope = getBasicAuthScope().getScope(targetHost); if (credentialsProvider.getCredentials(targetScope) != null) { BasicScheme targetAuth = new BasicScheme(); try { targetAuth.processChallenge(new BasicHeader(AUTH.WWW_AUTH, "BASIC preemptive")); authCache.put(targetHost, targetAuth); } catch (MalformedChallengeException ignore) { // ignore } } HttpPut putMethod = new HttpPut(url); firePutStarted(resource, source); try { putMethod.setEntity(httpEntity); CloseableHttpResponse response = execute(putMethod); try { int statusCode = response.getStatusLine().getStatusCode(); String reasonPhrase = ", ReasonPhrase: " + response.getStatusLine().getReasonPhrase() + "."; fireTransferDebug(url + " - Status code: " + statusCode + reasonPhrase); // Check that we didn't run out of retries. switch (statusCode) { // Success Codes case HttpStatus.SC_OK: // 200 case HttpStatus.SC_CREATED: // 201 case HttpStatus.SC_ACCEPTED: // 202 case HttpStatus.SC_NO_CONTENT: // 204 break; // handle all redirect even if http specs says " the user agent MUST NOT automatically redirect // the request unless it can be confirmed by the user" case HttpStatus.SC_MOVED_PERMANENTLY: // 301 case HttpStatus.SC_MOVED_TEMPORARILY: // 302 case HttpStatus.SC_SEE_OTHER: // 303 put(resource, source, httpEntity, calculateRelocatedUrl(response)); return; case HttpStatus.SC_FORBIDDEN: fireSessionConnectionRefused(); throw new AuthorizationException("Access denied to: " + url + reasonPhrase); case HttpStatus.SC_NOT_FOUND: throw new ResourceDoesNotExistException("File: " + url + " does not exist" + reasonPhrase); case SC_TOO_MANY_REQUESTS: put(backoff(wait, url), resource, source, httpEntity, url); break; //add more entries here default: TransferFailedException e = new TransferFailedException( "Failed to transfer file: " + url + ". Return code is: " + statusCode + reasonPhrase); fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw e; } firePutCompleted(resource, source); EntityUtils.consume(response.getEntity()); } finally { response.close(); } } catch (IOException e) { fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw new TransferFailedException(e.getMessage(), e); } catch (HttpException e) { fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw new TransferFailedException(e.getMessage(), e); } catch (InterruptedException e) { fireTransferError(resource, e, TransferEvent.REQUEST_PUT); throw new TransferFailedException(e.getMessage(), e); } }
From source file:run.var.teamcity.cloud.docker.client.apcon.ApacheConnector.java
@Override public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException { final HttpUriRequest request = getUriHttpRequest(clientRequest); final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request); try {/*w w w.jav a 2 s . c o m*/ final CloseableHttpResponse response; final HttpClientContext context = HttpClientContext.create(); if (preemptiveBasicAuth) { final AuthCache authCache = new BasicAuthCache(); final BasicScheme basicScheme = new BasicScheme(); authCache.put(getHost(request), basicScheme); context.setAuthCache(authCache); } response = client.execute(getHost(request), request, context); HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName()); final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null ? Statuses.from(response.getStatusLine().getStatusCode()) : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); final ClientResponse responseContext = new ClientResponse(status, clientRequest); final List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null && !redirectLocations.isEmpty()) { responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1)); } final Header[] respHeaders = response.getAllHeaders(); final MultivaluedMap<String, String> headers = responseContext.getHeaders(); for (final Header header : respHeaders) { final String headerName = header.getName(); List<String> list = headers.get(headerName); if (list == null) { list = new ArrayList<>(); } list.add(header.getValue()); headers.put(headerName, list); } final HttpEntity entity = response.getEntity(); if (entity != null) { if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) { headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength())); } final Header contentEncoding = entity.getContentEncoding(); if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) { headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue()); } } try { responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response))); } catch (final IOException e) { LOGGER.log(Level.SEVERE, null, e); } localHttpContext.set(context); return responseContext; } catch (final Exception e) { throw new ProcessingException(e); } }
From source file:com.baidubce.http.BceHttpClient.java
/** * Creates HttpClient Context object based on the internal request. * * @param request The internal request.//from w w w . j a v a 2 s . c om * @return HttpClient Context object. */ protected HttpClientContext createHttpContext(InternalRequest request) { HttpClientContext context = HttpClientContext.create(); context.setRequestConfig( this.requestConfigBuilder.setExpectContinueEnabled(request.isExpectContinueEnabled()).build()); if (this.credentialsProvider != null) { context.setCredentialsProvider(this.credentialsProvider); } if (this.config.isProxyPreemptiveAuthenticationEnabled()) { AuthCache authCache = new BasicAuthCache(); authCache.put(this.proxyHttpHost, new BasicScheme()); context.setAuthCache(authCache); } return context; }
From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java
@Override public boolean testDHISServerDetails(String url, String user, String pass) { URL testURL;//from www . java 2 s. c o m Boolean success = true; // Check if the URL makes sense try { testURL = new URL(url + "/api/resources"); // Add the root API // endpoint to the URL } catch (MalformedURLException e) { e.printStackTrace(); return false; } HttpHost targetHost = new HttpHost(testURL.getHost(), testURL.getPort(), testURL.getProtocol()); DefaultHttpClient httpclient = new DefaultHttpClient(); BasicHttpContext localcontext = new BasicHttpContext(); try { HttpGet httpGet = new HttpGet(testURL.toURI()); Credentials creds = new UsernamePasswordCredentials(user, pass); Header bs = new BasicScheme().authenticate(creds, httpGet, localcontext); httpGet.addHeader("Authorization", bs.getValue()); httpGet.addHeader("Content-Type", "application/json"); httpGet.addHeader("Accept", "application/json"); HttpResponse response = httpclient.execute(targetHost, httpGet, localcontext); // Execute // the // test // query if (response.getStatusLine().getStatusCode() != 200) { success = false; } } catch (Exception ex) { ex.printStackTrace(); success = false; } finally { httpclient.getConnectionManager().shutdown(); } return success; }
From source file:com.danielme.muspyforandroid.services.MuspyClient.java
private BasicHttpContext getBasicHttpContext() { if (localContext == null) { localContext = new BasicHttpContext(); BasicScheme basicAuth = new BasicScheme(); localContext.setAttribute("preemptive-auth", basicAuth); }//from w w w. j a va2s. c om return localContext; }