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.echocat.jomon.net.http.client.HttpClientAuth.java

public HttpClientAuth(@Nonnull AuthScope scope, @Nonnull HttpHost host, @Nonnull Credentials credentials) {
    this(scope, host, credentials, new BasicScheme());
}

From source file:org.fcrepo.client.utils.HttpHelper.java

/**
 * Create an HTTP helper with a pre-configured HttpClient instance.
 * @param repositoryURL Fedora base URL.
 * @param httpClient Pre-configured HttpClient instance.
 * @param readOnly If true, throw an exception when an update is attempted.
**//*from  w  w w  .  j  a  v a 2 s  .c  om*/
public HttpHelper(final String repositoryURL, final HttpClient httpClient, final boolean readOnly) {
    this.repositoryURL = repositoryURL;
    this.httpClient = httpClient;
    this.readOnly = readOnly;

    // Use pre-emptive Auth whether the repository is actually protected or not.
    final URI uri = URI.create(repositoryURL);
    final HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

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

    this.httpContext = localContext;
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

private <T> T runMethod(HttpRequestBase method, String uri, ResponseHandler<T> responseHandler)
        throws IOException {
    String protocol = _isSecure ? "https" : "http";
    ServiceError error;// w w  w .java  2s  .c om
    URL url = new URL(protocol, _host, _port, uri);

    try {
        method.setURI(url.toURI());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("The syntax of request url [" + uri + "] is invalid", e);
    }

    _log.debug("Setting URI: " + url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    if (_isSecure) {
        // To allow for self signed certificates
        configureSSL(client);
    }

    // Validate user & password inputs
    if (_user == null || _user.length() == 0) {
        error = new ServiceError();
        error.setErrorCode("LoginFailure");
        error.setReasonText("User name cannot be null or empty");

        return responseHandler.getErrorResponse(error);
    }

    if (_password == null || _password.length() == 0) {
        error = new ServiceError();
        error.setErrorCode("LoginFailure");
        error.setReasonText("Password cannot be null or empty");

        return responseHandler.getErrorResponse(error);
    }

    // Set Basic auth creds
    UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials(_user, _password);

    client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);

    // Preemptive authentication
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost host = new HttpHost(_host, _port, protocol);

    authCache.put(host, basicAuth);

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

    method.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);

    // Disable re-tries
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, true));

    HttpResponse response = client.execute(method, localContext);

    return responseHandler.handleResponse(response);
}

From source file:org.hyperic.hq.plugin.rabbitmq.core.HypericRabbitAdmin.java

public HypericRabbitAdmin(Properties props) throws PluginException {
    int port = Integer.parseInt(props.getProperty(DetectorConstants.PORT));
    String addr = props.getProperty(DetectorConstants.ADDR);
    boolean https = "true".equals(props.getProperty(DetectorConstants.HTTPS));
    this.user = props.getProperty(DetectorConstants.USERNAME);
    this.pass = props.getProperty(DetectorConstants.PASSWORD);

    targetHost = new HttpHost(addr, port, https ? "https" : "http");
    AgentKeystoreConfig config = new AgentKeystoreConfig();
    client = new HQHttpClient(config, new HttpConfig(5000, 5000, null, 0), config.isAcceptUnverifiedCert());
    client.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort(), "Management: Web UI"),
            new UsernamePasswordCredentials(user, pass));
    List authPrefs = new ArrayList(1);
    authPrefs.add("Management: Web UI");

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

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

From source file:org.jenkinsmvn.jenkins.api.JenkinsClient.java

public void authenticate(String username, String password) {
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

    client.getCredentialsProvider()/*from   w  w w.jav  a2s . c  o m*/
            .setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), 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(targetHost, basicAuth);

    context.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:org.openmrs.module.dhisreport.api.dhis.HttpDhis2Server.java

@Override
public ImportSummary postReport(DataValueSet report) throws DHIS2ReportingException {
    log.debug("Posting datavalueset report");
    ImportSummary summary = null;/*from   ww w  .  java  2  s  . c om*/

    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) {
        throw new Dxf2Exception("Problem marshalling dataValueSet", ex);
    }

    //System.out.print( "URL-" + url );

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

    //System.out.print( "URL-" + url + ":host-" + host + ":port-" );
    // System.out.println( port );

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

    try {
        HttpPost httpPost = new HttpPost(url.getPath() + DATAVALUESET_PATH);
        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+adx");
        httpPost.addHeader("Accept", "application/xml");

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

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new Dhis2Exception(this, response.getStatusLine().getReasonPhrase(), null);
        }

        if (entity != null) {
            JAXBContext jaxbImportSummaryContext = JAXBContext.newInstance(ImportSummary.class);
            Unmarshaller importSummaryUnMarshaller = jaxbImportSummaryContext.createUnmarshaller();
            summary = (ImportSummary) importSummaryUnMarshaller.unmarshal(entity.getContent());
        } else {
            summary = new ImportSummary();
            summary.setStatus(ImportStatus.ERROR);
        }
        // EntityUtils.consume( entity );

        // TODO: fix these catches ...
    } catch (JAXBException ex) {
        throw new Dhis2Exception(this, "Problem unmarshalling ImportSummary", ex);
    } catch (AuthenticationException ex) {
        throw new Dhis2Exception(this, "Problem authenticating to DHIS2 server", ex);
    } catch (IOException ex) {
        throw new Dhis2Exception(this, "Problem accessing DHIS2 server", ex);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return summary;
}

From source file:org.openmrs.module.dhisreport.api.dhis.HttpDhis2Server.java

@Override
public ImportSummaries postAdxReport(AdxType report) throws DHIS2ReportingException {
    log.debug("Posting A report");
    ImportSummaries summaries = null;// w  ww  .  j a va  2  s .c  o m

    StringWriter xmlReport = new StringWriter();
    try {
        JAXBContext jaxbDataValueSetContext = JAXBContext.newInstance(AdxType.class);

        Marshaller adxTypeMarshaller = jaxbDataValueSetContext.createMarshaller();
        // output pretty printed
        adxTypeMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        adxTypeMarshaller.marshal(report, xmlReport);
    } catch (JAXBException ex) {
        throw new Dxf2Exception("Problem marshalling adxtype", ex);
    }

    //System.out.print( "URL-" + url );

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

    //System.out.print( "URL-" + url + ":host-" + host + ":port-" );
    // System.out.println( port );

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

    try {
        HttpPost httpPost = new HttpPost(url.getPath() + DATAVALUESET_PATH);
        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+adx");
        httpPost.addHeader("Accept", "application/xml");

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

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new Dhis2Exception(this, response.getStatusLine().getReasonPhrase(), null);
        }

        if (entity != null) {
            JAXBContext jaxbImportSummaryContext = JAXBContext.newInstance(ImportSummaries.class);
            Unmarshaller importSummaryUnMarshaller = jaxbImportSummaryContext.createUnmarshaller();
            summaries = (ImportSummaries) importSummaryUnMarshaller.unmarshal(entity.getContent());
        } else {
            summaries = new ImportSummaries();
        }
        // EntityUtils.consume( entity );

        // TODO: fix these catches ...
    } catch (JAXBException ex) {
        throw new Dhis2Exception(this, "Problem unmarshalling ImportSummary", ex);
    } catch (AuthenticationException ex) {
        throw new Dhis2Exception(this, "Problem authenticating to DHIS2 server", ex);
    } catch (IOException ex) {
        throw new Dhis2Exception(this, "Problem accessing DHIS2 server", ex);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return summaries;
}

From source file:org.opennms.core.web.HttpClientWrapper.java

protected void enablePreemptiveAuth(final HttpClientBuilder builder) {
    /**/*  w ww .j av  a  2 s. c  om*/
     * Add an HttpRequestInterceptor that will perform preemptive authentication
     * @see http://hc.apache.org/httpcomponents-client-4.0.1/tutorial/html/authentication.html
     */
    final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (context instanceof HttpClientContext) {
                final HttpClientContext clientContext = (HttpClientContext) context;
                final AuthState authState = clientContext.getTargetAuthState();
                final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
                final HttpHost targetHost = clientContext.getTargetHost();
                // If not authentication scheme has been initialized yet
                if (authState.getAuthScheme() == null) {
                    final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    final Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                        authState.update(new BasicScheme(), creds);
                    }
                }
            } else {
                throw new IllegalArgumentException("Not sure how to handle a non-HttpClientContext context.");
            }
        }

    };
    builder.addInterceptorFirst(preemptiveAuth);
}

From source file:org.xwiki.extension.repository.xwiki.internal.XWikiExtensionRepository.java

public XWikiExtensionRepository(ExtensionRepositoryDescriptor repositoryDescriptor,
        XWikiExtensionRepositoryFactory repositoryFactory, ExtensionLicenseManager licenseManager,
        HttpClientFactory httpClientFactory) throws Exception {
    super(repositoryDescriptor.getURI().getPath().endsWith("/")
            ? new DefaultExtensionRepositoryDescriptor(repositoryDescriptor.getId(),
                    repositoryDescriptor.getType(),
                    new URI(StringUtils.chop(repositoryDescriptor.getURI().toString())))
            : repositoryDescriptor);/*from ww  w. j ava  2 s. co m*/

    this.repositoryFactory = repositoryFactory;
    this.licenseManager = licenseManager;
    this.httpClientFactory = httpClientFactory;

    // Uri builders
    this.rootUriBuider = createUriBuilder(Resources.ENTRYPOINT);
    this.extensionVersionUriBuider = createUriBuilder(Resources.EXTENSION_VERSION);
    this.extensionVersionFileUriBuider = createUriBuilder(Resources.EXTENSION_VERSION_FILE);
    this.extensionVersionsUriBuider = createUriBuilder(Resources.EXTENSION_VERSIONS);
    this.searchUriBuider = createUriBuilder(Resources.SEARCH);

    // Setup preemptive authentication
    if (getDescriptor().getProperty("auth.user") != null) {
        // 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(new HttpHost(getDescriptor().getURI().getHost(), getDescriptor().getURI().getPort(),
                getDescriptor().getURI().getScheme()), basicAuth);

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