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:de.mendelson.comm.as2.send.MessageHttpUploader.java

/**Sets necessary HTTP authentication for this partner, depending on if it is an asny MDN that will be sent or an AS2 message.
 *If the partner is not configured to use HTTP authentication in any kind nothing will happen in here
 *///www .j  a  va2  s .  co m
private void setHTTPAuthentication(DefaultHttpClient client, Partner receiver, boolean isMDN) {
    HTTPAuthentication authentication = null;
    if (isMDN) {
        authentication = receiver.getAuthenticationAsyncMDN();
    } else {
        authentication = receiver.getAuthentication();
    }
    if (authentication.isEnabled()) {
        Credentials userPassCredentials = new UsernamePasswordCredentials(authentication.getUser(),
                authentication.getPassword());
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, userPassCredentials);
        BasicHttpContext localcontext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local
        // execution context
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        // Add as the first request interceptor
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }
}

From source file:com.hp.octane.integrations.services.coverage.SonarServiceImpl.java

private void setTokenInHttpRequest(HttpRequest request, String token) throws AuthenticationException {
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(token, "");
    request.addHeader(new BasicScheme().authenticate(creds, request, null));
}

From source file:com.github.pascalgn.jiracli.web.HttpClient.java

private void setCredentials() {
    AuthState authState = httpClientContext.getTargetAuthState();
    if (authState != null) {
        CredentialsProvider credentialsProvider = httpClientContext.getCredentialsProvider();
        AuthScope authScope = new AuthScope(HttpHost.create(getBaseUrl()));
        org.apache.http.auth.Credentials credentials = credentialsProvider.getCredentials(authScope);
        if (credentials != null) {
            authState.update(new BasicScheme(), credentials);
            authState.setState(AuthProtocolState.CHALLENGED);
        }/* w  ww .j  a  v  a  2s  .c o  m*/
    }
}

From source file:org.sonatype.nexus.plugins.crowd.client.rest.RestClient.java

private <T extends HttpRequestBase> T enablePreemptiveAuth(T method, HttpClientContext hcc)
        throws AuthenticationException {
    HttpClientContext localContext = HttpClientContext.adapt(hcc);
    method.addHeader(new BasicScheme().authenticate(crowdCreds, method, localContext));
    return method;
}

From source file:org.opendatakit.dwc.server.GreetingServiceImpl.java

private static HttpRequestInterceptor getPreemptiveAuth() {
    return 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);
                }//from www  . j  a v  a  2s  .  c o m
            }
        }
    };
}

From source file:com.arangodb.http.HttpManager.java

/**
 * Executes the request/* w  w  w. j av a 2s  .co m*/
 * 
 * @param requestEntity
 *            the request
 * @return the response of the request
 * @throws ArangoException
 */
private HttpResponseEntity executeInternal(String baseUrl, HttpRequestEntity requestEntity)
        throws ArangoException, SocketException {

    String url = buildUrl(baseUrl, requestEntity);

    if (logger.isDebugEnabled()) {
        if (requestEntity.type == RequestType.POST || requestEntity.type == RequestType.PUT
                || requestEntity.type == RequestType.PATCH) {
            logger.debug("[REQ]http-{}: url={}, headers={}, body={}",
                    new Object[] { requestEntity.type, url, requestEntity.headers, requestEntity.bodyText });
        } else {
            logger.debug("[REQ]http-{}: url={}, headers={}",
                    new Object[] { requestEntity.type, url, requestEntity.headers });
        }
    }

    HttpRequestBase request = null;
    switch (requestEntity.type) {
    case GET:
        request = new HttpGet(url);
        break;
    case POST:
        HttpPost post = new HttpPost(url);
        configureBodyParams(requestEntity, post);
        request = post;
        break;
    case PUT:
        HttpPut put = new HttpPut(url);
        configureBodyParams(requestEntity, put);
        request = put;
        break;
    case PATCH:
        HttpPatch patch = new HttpPatch(url);
        configureBodyParams(requestEntity, patch);
        request = patch;
        break;
    case HEAD:
        request = new HttpHead(url);
        break;
    case DELETE:
        request = new HttpDelete(url);
        break;
    }

    // common-header
    String userAgent = "Mozilla/5.0 (compatible; ArangoDB-JavaDriver/1.1; +http://mt.orz.at/)";
    request.setHeader("User-Agent", userAgent);

    // optinal-headers
    if (requestEntity.headers != null) {
        for (Entry<String, Object> keyValue : requestEntity.headers.entrySet()) {
            request.setHeader(keyValue.getKey(), keyValue.getValue().toString());
        }
    }

    // Basic Auth
    Credentials credentials = null;
    if (requestEntity.username != null && requestEntity.password != null) {
        credentials = new UsernamePasswordCredentials(requestEntity.username, requestEntity.password);
    } else if (configure.getUser() != null && configure.getPassword() != null) {
        credentials = new UsernamePasswordCredentials(configure.getUser(), configure.getPassword());
    }
    if (credentials != null) {
        BasicScheme basicScheme = new BasicScheme();
        try {
            request.addHeader(basicScheme.authenticate(credentials, request, null));
        } catch (AuthenticationException e) {
            throw new ArangoException(e);
        }
    }

    if (this.getHttpMode().equals(HttpMode.ASYNC)) {
        request.addHeader("x-arango-async", "store");
    } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) {
        request.addHeader("x-arango-async", "true");
    }
    // CURL/httpie Logger
    if (configure.isEnableCURLLogger()) {
        CURLLogger.log(url, requestEntity, userAgent, credentials);
    }
    HttpResponse response = null;
    if (preDefinedResponse != null) {
        return preDefinedResponse;
    }
    try {
        response = client.execute(request);
        if (response == null) {
            return null;
        }

        HttpResponseEntity responseEntity = new HttpResponseEntity();

        // http status
        StatusLine status = response.getStatusLine();
        responseEntity.statusCode = status.getStatusCode();
        responseEntity.statusPhrase = status.getReasonPhrase();

        logger.debug("[RES]http-{}: statusCode={}", requestEntity.type, responseEntity.statusCode);

        // ??
        // // TODO etag???
        Header etagHeader = response.getLastHeader("etag");
        if (etagHeader != null) {
            responseEntity.etag = Long.parseLong(etagHeader.getValue().replace("\"", ""));
        }
        // Map???
        responseEntity.headers = new TreeMap<String, String>();
        for (Header header : response.getAllHeaders()) {
            responseEntity.headers.put(header.getName(), header.getValue());
        }

        // ???
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            Header contentType = entity.getContentType();
            if (contentType != null) {
                responseEntity.contentType = contentType.getValue();
                if (responseEntity.isDumpResponse()) {
                    responseEntity.stream = entity.getContent();
                    logger.debug("[RES]http-{}: stream, {}", requestEntity.type, contentType.getValue());
                }
            }
            // Close stream in this method.
            if (responseEntity.stream == null) {
                responseEntity.text = IOUtils.toString(entity.getContent());
                logger.debug("[RES]http-{}: text={}", requestEntity.type, responseEntity.text);
            }
        }

        if (this.getHttpMode().equals(HttpMode.ASYNC)) {
            Map<String, String> map = responseEntity.getHeaders();
            this.addJob(map.get("X-Arango-Async-Id"), this.getCurrentObject());
        } else if (this.getHttpMode().equals(HttpMode.FIREANDFORGET)) {
            return null;
        }

        return responseEntity;
    } catch (SocketException ex) {
        throw ex;
    } catch (ClientProtocolException e) {
        throw new ArangoException(e);
    } catch (IOException e) {
        throw new ArangoException(e);
    }
}

From source file:org.xwiki.eclipse.storage.rest.XWikiRestClient.java

/**
 * FIXME: need to return different response code so that the UI can respond correspondingly
 *///from   w  w w  .  ja va2 s  .  co m
public void uploadAttachment(String wiki, String space, String page, String attachmentName, URL fileUrl)
        throws Exception {
    URI attachmentURI = getURI(
            String.format("/wikis/%s/spaces/%s/pages/%s/attachments/%s", wiki, space, page, attachmentName));

    DefaultHttpClient httpClient = new DefaultHttpClient();

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

    HttpPut request = new HttpPut(attachmentURI);

    request.addHeader(new BasicScheme().authenticate(creds, request));
    request.addHeader("Accept", MediaType.APPLICATION_XML);

    File file = new File(fileUrl.toURI());
    byte[] bytes = FileUtils.readFileToByteArray(file);
    ByteArrayEntity bin = new ByteArrayEntity(bytes);

    request.setEntity(bin);

    HttpResponse response = httpClient.execute(request);

    /* file created */
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
        // System.out.println("SC_CREATED");
    }
    /* file updated */
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) {
        // System.out.println("SC_ACCEPTED");
    }

    /* user UNAUTHORIZED */
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
        // System.out.println("SC_UNAUTHORIZED");
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

/**
 * Get rest response and fill the query results
 * //w w w .j a  v  a2s . c om
 * @param rightside
 * @param response
 * @throws IOException
 * @throws ResponseException
 */
public void getRest(String rightside, ConfluenceJSONResponse response) throws IOException, ResponseException {

    // 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(host, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    String executionUrl = host.toURI() + path + (path.endsWith("/") ? "" : "/") + rightside;
    if (Logging.connectors != null)
        Logging.connectors.info("Execution url is :" + executionUrl);
    final HttpRequestBase method = new HttpGet(executionUrl);
    method.addHeader("Accept", "application/json");

    try {
        HttpResponse httpResponse = httpClient.execute(method, localContext);

        int resultCode = httpResponse.getStatusLine().getStatusCode();
        if (resultCode == 200) {
            // Logging.connectors.info("Successfully retrived response");
            Object jo = convertToJSON(httpResponse);
            response.acceptJSONObject(jo);
        } else if (resultCode == 401) {
            throw new IOException("There is Authentication failure, this may be due to capcha : "
                    + convertToString(httpResponse));
        } else {
            throw new IOException(
                    "Unexpected result code " + resultCode + ": " + convertToString(httpResponse));
        }

    } finally {
        method.abort();
    }
}

From source file:org.apache.abdera2.common.protocol.Session.java

public void usePreemptiveAuthentication(String target, String realm) throws URISyntaxException {
    AuthCache cache = (AuthCache) localContext.getAttribute(ClientContext.AUTH_CACHE);
    if (cache == null) {
        String host = AuthScope.ANY_HOST;
        int port = AuthScope.ANY_PORT;
        if (target != null) {
            URI uri = new URI(target);
            host = uri.getHost();//  w w  w. j  ava 2 s .  c o m
            port = uri.getPort();
        }
        BasicScheme basicAuth = new BasicScheme();
        HttpHost targetHost = new HttpHost(host, port, basicAuth.getSchemeName());
        cache = new BasicAuthCache();
        cache.put(targetHost, basicAuth);
        localContext.setAttribute(ClientContext.AUTH_CACHE, cache);
    }
}