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.kemri.wellcome.dhisreport.api.model.HttpDhis2Server.java

@Override
public ImportSummary postReport(DataValueSet report) throws DHIS2ReportingException {
    log.debug("Posting datavalueset report");
    ImportSummary summary = null;//from ww  w .ja  v a 2  s  . com

    StringWriter xmlReport = new StringWriter();
    try {
        JAXBContext jaxbDataValueSetContext = JAXBContext.newInstance(DataValueSet.class);
        Marshaller dataValueSetMarshaller = jaxbDataValueSetContext.createMarshaller();
        // output pretty printed
        dataValueSetMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        dataValueSetMarshaller.marshal(report, xmlReport);
    } catch (JAXBException ex) {
        log.error(ex.getMessage());
        throw new Dxf2Exception("Problem marshalling dataValueSet", ex);
    }

    String host = getUrl().getHost();
    int port = getUrl().getPort();

    HttpHost targetHost = new HttpHost(host, port, getUrl().getProtocol());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    BasicHttpContext localcontext = new BasicHttpContext();

    try {
        String postUrl = getUrl().toString() + DATAVALUESET_PATH;
        log.error("Post URL: " + postUrl);
        HttpPost httpPost = new HttpPost(postUrl);
        Credentials creds = new UsernamePasswordCredentials(username, password);
        Header bs = new BasicScheme().authenticate(creds, httpPost, localcontext);
        httpPost.addHeader("Authorization", bs.getValue());
        httpPost.addHeader("Content-Type", "application/xml; charset=utf-8");
        httpPost.addHeader("Accept", "application/xml");

        httpPost.setEntity(new StringEntity(xmlReport.toString()));
        HttpResponse response = httpclient.execute(targetHost, httpPost, localcontext);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            JAXBContext jaxbImportSummaryContext = JAXBContext.newInstance(ImportSummary.class);
            Unmarshaller importSummaryUnMarshaller = jaxbImportSummaryContext.createUnmarshaller();
            summary = (ImportSummary) importSummaryUnMarshaller.unmarshal(entity.getContent());
        }
    } catch (Exception ex) {
        log.error(ex.getMessage());
        throw new Dhis2Exception(this, "Problem accessing Dhis2 server", ex);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return summary;
}

From source file:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java

/**
 * @return Cache with preemptive auth enabled for Nexus
 *///from  ww w.  ja  v a  2 s  .  c om
protected AuthCache basicAuthCache() {
    String hostname = nexusUrl.getHost();
    AuthCache authCache = new BasicAuthCache();
    HttpHost hostHttp = new HttpHost(hostname, nexusUrl.getPort(), "http");
    HttpHost hostHttps = new HttpHost(hostname, nexusSecureUrl.getPort(), "https");
    authCache.put(hostHttp, new BasicScheme());
    authCache.put(hostHttps, new BasicScheme());
    return authCache;
}

From source file:com.bosch.iot.things.tutorial.ui.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;//from w  w  w  .  j  a v  a  2s.co  m
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(Base64.getDecoder().decode(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.cloudant.client.org.lightcouch.CouchDbClientAndroid.java

@Override
HttpContext createContext() {/*from   w ww.j  av a 2 s  .c o  m*/
    HttpContext context = new BasicHttpContext();
    BasicScheme basicAuth = new BasicScheme();
    context.setAttribute("preemptive-auth", basicAuth);
    ((AbstractHttpClient) httpClient).addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);
    return context;
}

From source file:org.aludratest.service.gui.web.selenium.TAFMSSeleniumResourceService.java

@Override
public String acquire() {
    // prepare a JSON query to the given TAFMS server
    JSONObject query = new JSONObject();

    try {//from   w  ww  .ja v a 2s .c  o  m
        query.put("resourceType", "selenium");
        query.put("niceLevel", configuration.getIntValue("tafms.niceLevel", 0));
        String jobName = configuration.getStringValue("tafms.jobName");
        if (jobName != null && !"".equals(jobName)) {
            query.put("jobName", jobName);
        }
    } catch (JSONException e) {
    }

    // prepare authentication
    BasicCredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            configuration.getStringValue("tafms.user"), configuration.getStringValue("tafms.password")));

    CloseableHttpClient client = HttpClientBuilder.create()
            .setConnectionReuseStrategy(new NoConnectionReuseStrategy()).disableConnectionState()
            .disableAutomaticRetries().setDefaultCredentialsProvider(provider).build();

    String message = null;
    try {
        boolean wait;

        // use preemptive authentication to avoid double connection count
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        URL url = new URL(getTafmsUrl());
        HttpHost host = new HttpHost(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort(),
                url.getProtocol());
        authCache.put(host, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

        do {
            // send a POST request to resource URL
            HttpPost request = new HttpPost(getTafmsUrl() + "resource");

            // attach query as JSON string data
            request.setEntity(new StringEntity(query.toString(), ContentType.APPLICATION_JSON));

            CloseableHttpResponse response = null;

            // fire request
            response = client.execute(request, localcontext);

            try {
                if (response.getStatusLine() == null) {
                    throw new ClientProtocolException("No HTTP status line transmitted");
                }

                message = extractMessage(response);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    LOG.error("Exception when querying TAFMS server for resource. HTTP Status: "
                            + response.getStatusLine().getStatusCode() + ", message: " + message);
                    return null;
                }

                JSONObject object = new JSONObject(message);
                if (object.has("errorMessage")) {
                    LOG.error("TAFMS server reported an error: " + object.get("errorMessage"));
                    return null;
                }

                // continue wait?
                if (object.has("waiting") && object.getBoolean("waiting")) {
                    wait = true;
                    query.put("requestId", object.getString("requestId"));
                } else {
                    JSONObject resource = object.optJSONObject("resource");
                    if (resource == null) {
                        LOG.error("TAFMS server response did not provide a resource. Message was: " + message);
                        return null;
                    }

                    String sUrl = resource.getString("url");
                    hostResourceIds.put(sUrl, object.getString("requestId"));

                    return sUrl;
                }
            } finally {
                IOUtils.closeQuietly(response);
            }
        } while (wait);

        // should never come here
        return null;
    } catch (ClientProtocolException e) {
        LOG.error("Exception in HTTP transmission", e);
        return null;
    } catch (IOException e) {
        LOG.error("Exception in communication with TAFMS server", e);
        return null;
    } catch (JSONException e) {
        LOG.error("Invalid JSON received from TAFMS server. JSON message was: " + message, e);
        return null;
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.offbytwo.jenkins.client.JenkinsHttpClient.java

/**
 * Create an authenticated Jenkins HTTP client
 *
 * @param uri/*w w w  .j av a  2s .  c o m*/
 *            Location of the jenkins server (ex. http://localhost:8080)
 * @param username
 *            Username to use when connecting
 * @param password
 *            Password or auth token to use when connecting
 */
public JenkinsHttpClient(URI uri, String username, String password) {
    this(uri, addAuthentication(HttpClientBuilder.create(), uri, username, password));
    if (isNotBlank(username)) {
        localContext = new BasicHttpContext();
        localContext.setAttribute("preemptive-auth", new BasicScheme());
    }
}

From source file:org.zenoss.app.consumer.metric.impl.MetricServicePoster.java

/**
 * Login to the ZAuth service using the zenoss credentials.  Grab the tenant id from the http response and cache
 * the results for future requests./*from   ww  w .j  ava2  s .c o m*/
 * @return tenant id
 * @throws IOException
 */
String getTenantId() throws IOException {
    if (tenantId == null) {
        log.debug("Requesting tenant id");
        // get the hostname and port from ProxyConfiguration
        ProxyConfiguration proxyConfig = configuration.getProxyConfiguration();
        String hostname = proxyConfig.getHostname();
        int port = proxyConfig.getPort();

        //configure request
        HttpContext context = new BasicHttpContext();
        HttpHost host = new HttpHost(hostname, port, "http");
        HttpPost post = new HttpPost(AUTHENTICATE_URL);
        post.addHeader(ACCEPT, APPLICATION_JSON.toString());

        //configure authentication
        String username = configuration.getZenossCredentials().getUsername();
        String password = configuration.getZenossCredentials().getPassword();
        if (!Strings.nullToEmpty(username).isEmpty()) {
            //configure credentials
            CredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                    new UsernamePasswordCredentials(username, password));
            context.setAttribute(ClientContext.CREDS_PROVIDER, provider);

            //setup auth cache
            AuthCache cache = new BasicAuthCache();
            BasicScheme scheme = new BasicScheme();
            cache.put(host, scheme);
            context.setAttribute(ClientContext.AUTH_CACHE, cache);
        }

        //handle response and collect tenantId
        HttpResponse response = null;
        try {
            response = httpClient.execute(host, post, context);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            log.debug("Tenant id request complete with status: {}", statusCode);
            if (statusCode >= 200 && statusCode <= 299) {
                Header id = response.getFirstHeader(ZenossTenant.ID_HTTP_HEADER);
                if (id == null) {
                    log.warn("Failed to get zauth tenant id after login");
                    throw new RuntimeException("Failed to get zauth tenant id after successful login");
                }
                tenantId = id.getValue();
                log.info("Got tenant id: {}", tenantId);
            } else {
                log.warn("Unsuccessful response from server: {}", response.getStatusLine());
                throw new IOException("Login for tenantId failed");
            }
        } catch (NullPointerException ex) {
            log.warn("npe retrieving tenantId: {}", ex);
        } finally {
            try {
                if (response != null) {
                    response.getEntity().getContent().close();
                }
            } catch (NullPointerException | IOException ex) {
                log.warn("Failed to close request: {}", ex);
            }
        }
    }
    return tenantId;
}

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

protected HttpResponse executePostXml(URI uri, java.lang.Object object) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);

    HttpPost request = new HttpPost(uri);
    request.addHeader(new BasicScheme().authenticate(creds, request));
    request.addHeader("Content-type", "text/xml; charset=UTF-8");
    request.addHeader("Accept", MediaType.APPLICATION_XML);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    marshaller.marshal(object, os);//from   www.java  2 s. co m
    HttpEntity entity = new ByteArrayEntity(os.toByteArray());
    request.setEntity(entity);
    HttpResponse response = httpClient.execute(request);

    return response;
}