Example usage for org.apache.http.impl.auth BasicScheme BasicScheme

List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme

Introduction

In this page you can find the example usage for org.apache.http.impl.auth BasicScheme BasicScheme.

Prototype

public BasicScheme() 

Source Link

Usage

From source file:org.wso2.bam.integration.tests.reciever.RESTAPITestCase.java

private static HttpPost getHTTPPost(String url, String entityBody, String username, String password)
        throws UnsupportedEncodingException, AuthenticationException {
    HttpPost post = new HttpPost(url);
    //            post.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64("admin:admin".getBytes())));
    HttpEntity httpEntity = new StringEntity(entityBody, "application/json", "UTF-8");
    post.setEntity(httpEntity);//from ww  w.  j a v a  2  s. c  o m

    post.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), post));
    return post;
}

From source file:org.opennms.smoketest.OpenNMSSeleniumTestCase.java

private Integer doRequest(final HttpRequestBase request)
        throws ClientProtocolException, IOException, InterruptedException {
    final CountDownLatch waitForCompletion = new CountDownLatch(1);

    final URI uri = request.getURI();
    final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials("admin", "admin"));
    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 context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);//w  w w. java 2 s  . co m

    final CloseableHttpClient client = HttpClients.createDefault();

    final ResponseHandler<Integer> responseHandler = new ResponseHandler<Integer>() {
        @Override
        public Integer handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
            try {
                final int status = response.getStatusLine().getStatusCode();
                // 400 because we return that if you try to delete something that is already deleted
                // 404 because it's OK if it's already not there
                if (status >= 200 && status < 300 || status == 400 || status == 404) {
                    EntityUtils.consume(response.getEntity());
                    return status;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            } finally {
                waitForCompletion.countDown();
            }
        }
    };

    final Integer status = client.execute(targetHost, request, responseHandler, context);

    waitForCompletion.await();
    client.close();
    return status;
}

From source file:com.cheddargetter.client.service.CheddarGetterPaymentService.java

private BasicHttpContext createHttpContext() {
    AuthCache authCache = new BasicAuthCache();
    authCache.put(host, new BasicScheme());
    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTH_CACHE, authCache);
    return context;
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java

protected HttpResponse getHttpResponse(final HttpUriRequest httpRequest, final String url) throws DSSException {

    final HttpClient client = getHttpClient(url);

    final String host = httpRequest.getURI().getHost();
    final int port = httpRequest.getURI().getPort();
    final String scheme = httpRequest.getURI().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  a v  a2s. c o m*/
        final HttpResponse response = client.execute(targetHost, httpRequest, localContext);
        return response;
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:net.yacy.cora.federate.solr.instance.RemoteInstance.java

/**
 * @param solraccount eventual user name used to authenticate on the target Solr
 * @param solraccount eventual password used to authenticate on the target Solr
 * @param trustSelfSignedCertificates when true, https connections to an host providing a self-signed certificate are accepted
* @param maxBytesPerReponse//from   w  ww. j  a  v  a  2 s  .  co  m
*            maximum acceptable decompressed size in bytes for a response from
*            the remote Solr server. Negative value or Long.MAX_VALUE means no
*            limit.
 * @return a new apache HttpClient instance usable as a custom http client by SolrJ
 */
private static HttpClient buildCustomHttpClient(final int timeout, final MultiProtocolURL u,
        final String solraccount, final String solrpw, final String host,
        final boolean trustSelfSignedCertificates, final long maxBytesPerResponse) {

    /* Important note : use of deprecated Apache classes is required because SolrJ still use them internally (see HttpClientUtil). 
     * Upgrade only when Solr implementation will become compatible */

    org.apache.http.impl.client.DefaultHttpClient result = new org.apache.http.impl.client.DefaultHttpClient(
            CONNECTION_MANAGER) {
        @Override
        protected HttpContext createHttpContext() {
            HttpContext context = super.createHttpContext();
            AuthCache authCache = new org.apache.http.impl.client.BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            HttpHost targetHost = new HttpHost(u.getHost(), u.getPort(), u.getProtocol());
            authCache.put(targetHost, basicAuth);
            context.setAttribute(org.apache.http.client.protocol.HttpClientContext.AUTH_CACHE, authCache);
            if (trustSelfSignedCertificates && SCHEME_REGISTRY != null) {
                context.setAttribute(ClientContext.SCHEME_REGISTRY, SCHEME_REGISTRY);
            }
            this.setHttpRequestRetryHandler(
                    new org.apache.http.impl.client.DefaultHttpRequestRetryHandler(0, false)); // no retries needed; we expect connections to fail; therefore we should not retry
            return context;
        }
    };
    org.apache.http.params.HttpParams params = result.getParams();
    /* Set the maximum time to establish a connection to the remote server */
    org.apache.http.params.HttpConnectionParams.setConnectionTimeout(params, timeout);
    /* Set the maximum time between data packets reception one a connection has been established */
    org.apache.http.params.HttpConnectionParams.setSoTimeout(params, timeout);
    /* Set the maximum time to get a connection from the shared connections pool */
    HttpClientParams.setConnectionManagerTimeout(params, timeout);
    result.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (!request.containsHeader(HeaderFramework.ACCEPT_ENCODING))
                request.addHeader(HeaderFramework.ACCEPT_ENCODING, HeaderFramework.CONTENT_ENCODING_GZIP);
            if (!request.containsHeader(HTTP.CONN_DIRECTIVE))
                request.addHeader(HTTP.CONN_DIRECTIVE, "close"); // prevent CLOSE_WAIT
        }

    });
    result.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(final HttpResponse response, final HttpContext context) throws IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (HeaderElement codec : codecs) {
                        if (codec.getName().equalsIgnoreCase(HeaderFramework.CONTENT_ENCODING_GZIP)) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }
    });
    if (solraccount != null && !solraccount.isEmpty()) {
        org.apache.http.impl.client.BasicCredentialsProvider credsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(solraccount, solrpw));
        result.setCredentialsProvider(credsProvider);
    }

    if (maxBytesPerResponse >= 0 && maxBytesPerResponse < Long.MAX_VALUE) {
        /*
         * Add in last position the eventual interceptor limiting the response size, so
         * that this is the decompressed amount of bytes that is considered
         */
        result.addResponseInterceptor(new StrictSizeLimitResponseInterceptor(maxBytesPerResponse),
                result.getResponseInterceptorCount());
    }

    return result;
}

From source file:org.glassfish.jersey.apache.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  2s.co 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);
        }

        return responseContext;
    } catch (final Exception e) {
        throw new ProcessingException(e);
    }
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java

private void put(int wait, Resource resource, File source, HttpEntity httpEntity, String url)
        throws TransferFailedException, AuthorizationException, ResourceDoesNotExistException {

    // preemptive for put
    // TODO: is it a good idea, though? 'Expect-continue' handshake would serve much better

    Repository repo = getRepository();//w  w w  . j  av a  2  s .c o  m
    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) {
        }
    }

    //Parent directories need to be created before posting
    try {
        mkdirs(PathUtils.dirname(resource.getName()));
    } catch (HttpException he) {
        fireTransferError(resource, he, TransferEvent.REQUEST_GET);
    }

    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:nl.sogeti.android.gpstracker.actions.ShareTrack.java

/**
 * POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website publishing 
 * this track to the public./*from   ww w.  j ava2s .c  o  m*/
 * 
 * @param fileUri
 * @param contentType
 */
private void sendToOsm(Uri fileUri, Uri trackUri, String contentType) {
    String username = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_USERNAME, "");
    String password = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_PASSWORD, "");
    String visibility = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_VISIBILITY,
            "trackable");
    File gpxFile = new File(fileUri.getEncodedPath());
    String hostname = getString(R.string.osm_post_host);
    Integer port = new Integer(getString(R.string.osm_post_port));
    HttpHost targetHost = new HttpHost(hostname, port, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;
    String responseText = "";
    int statusCode = 0;
    Cursor metaData = null;
    String sources = null;
    try {
        metaData = this.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"),
                new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ",
                new String[] { Constants.DATASOURCES_KEY }, null);
        if (metaData.moveToFirst()) {
            sources = metaData.getString(0);
        }
        if (sources != null && sources.contains(LoggerMap.GOOGLE_PROVIDER)) {
            throw new IOException("Unable to upload track with materials derived from Google Maps.");
        }

        // The POST to the create node
        HttpPost method = new HttpPost(getString(R.string.osm_post_context));

        // Preemptive basic auth on the first request 
        method.addHeader(
                new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), method));

        // Build the multipart body with the upload data
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("file", new FileBody(gpxFile));
        entity.addPart("description", new StringBody(queryForTrackName()));
        entity.addPart("tags", new StringBody(queryForNotes()));
        entity.addPart("visibility", new StringBody(visibility));
        method.setEntity(entity);

        // Execute the POST to OpenStreetMap
        response = httpclient.execute(targetHost, method);

        // Read the response
        statusCode = response.getStatusLine().getStatusCode();
        InputStream stream = response.getEntity().getContent();
        responseText = convertStreamToString(stream);
    } catch (IOException e) {
        Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e);
        responseText = getString(R.string.osm_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG);
        toast.show();
    } catch (AuthenticationException e) {
        Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e);
        responseText = getString(R.string.osm_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG);
        toast.show();
    } finally {
        if (metaData != null) {
            metaData.close();
        }
    }

    if (statusCode == 200) {
        Log.i(TAG, responseText);
        CharSequence text = getString(R.string.osm_success) + responseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    } else {
        Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText);
        CharSequence text = getString(R.string.osm_failed) + responseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    }
}

From source file:org.sinekartads.integration.cms.SignCMSonAlfresco.java

public static <SkdsResponse extends BaseResponse> SkdsResponse postJsonRequest(BaseRequest request,
        Class<SkdsResponse> responseClass) throws IllegalStateException, IOException {

    SkdsResponse response = null;//w w  w . j a v a2  s .c  o  m
    InputStream respIs = null;
    DefaultHttpClient httpclient = null;
    try {
        HttpHost targetHost = new HttpHost(HOST_NAME, PORT, "http");

        httpclient = new DefaultHttpClient();

        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(USER, PWD));

        AuthCache authCache = new BasicAuthCache();

        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        HttpPost httppost = new HttpPost("/alfresco/service" + request.getJSONUrl() + ".json?requestType=json");

        String req = request.toJSON();
        ByteArrayEntity body = new ByteArrayEntity(req.getBytes());
        httppost.setEntity(body);
        HttpResponse resp = httpclient.execute(targetHost, httppost, localcontext);
        HttpEntity entityResp = resp.getEntity();
        respIs = entityResp.getContent();

        response = TemplateUtils.Encoding.deserializeJSON(responseClass, respIs);

        EntityUtils.consume(entityResp);
        //      } catch(Exception e) {
        //         String message = e.getMessage();
        //         if ( StringUtils.isBlank(message) ) {
        //            message = e.toString();
        //         }
        //         tracer.error(message, e);
        //         throw new RuntimeException(message, e);
    } finally {
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
        IOUtils.closeQuietly(respIs);
    }
    return response;
}