Example usage for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

List of usage examples for org.apache.http.auth UsernamePasswordCredentials UsernamePasswordCredentials

Introduction

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

Prototype

public UsernamePasswordCredentials(final String userName, final String password) 

Source Link

Document

The constructor with the username and password arguments.

Usage

From source file:org.opennms.opennms.pris.plugins.defaults.source.HttpRequisitionMergeSource.java

private Requisition getRequisition(String url, String userName, String password) {
    Requisition requisition = null;/*from   w  w w  . j a v  a  2s  .c o m*/

    if (url != null) {
        try {
            HttpClientBuilder builder = HttpClientBuilder.create();

            // If username and password was found, inject the credentials
            if (userName != null && password != null) {

                CredentialsProvider provider = new BasicCredentialsProvider();

                // Create the authentication scope
                AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

                // Create credential pair
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(userName, password);

                // Inject the credentials
                provider.setCredentials(scope, credentials);

                // Set the default credentials provider
                builder.setDefaultCredentialsProvider(provider);
            }

            HttpClient client = builder.build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            try {

                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                JAXBContext jaxbContext = JAXBContext.newInstance(Requisition.class);

                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                requisition = (Requisition) jaxbUnmarshaller.unmarshal(bufferedReader);

            } catch (JAXBException e) {
                LOGGER.error("The response did not contain a valid requisition as xml.", e);
            }
            LOGGER.debug("Got Requisition {}", requisition);
        } catch (IOException ex) {
            LOGGER.error("Requesting requisition from {} failed", url, ex);
            return null;
        }
    } else {
        LOGGER.error("Parameter requisition.url is missing in requisition.properties");
        return null;
    }
    return requisition;
}

From source file:org.olat.core.commons.services.webdav.WebDAVConnection.java

public void setCredentials(String username, String password) {
    provider.setCredentials(new AuthScope(host, port, "OLAT WebDAV Access", "Basic"),
            new UsernamePasswordCredentials(username, password));
}

From source file:org.eclipse.oomph.setup.internal.sync.SyncUtil.java

public static Executor proxyAuthentication(Executor executor, URI uri) throws IOException {
    IProxyData proxy = getProxyData(uri);
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
        String proxyUserID = proxy.getUserId();
        if (proxyUserID != null) {
            String userID = getUserName(proxyUserID);
            String password = proxy.getPassword();
            String workstation = getWorkstation();
            String domain = getUserDomain(proxyUserID);
            return executor
                    .auth(new AuthScope(proxyHost, AuthScope.ANY_REALM, "ntlm"),
                            new NTCredentials(userID, password, workstation, domain))
                    .auth(new AuthScope(proxyHost, AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
                            new UsernamePasswordCredentials(userID, password));
        }/*  ww  w .j  a  v a  2 s .  c o  m*/
    }

    return executor;
}

From source file:org.mobicents.servlet.restcomm.fax.InterfaxService.java

private URI send(final Object message) throws Exception {
    final FaxRequest request = (FaxRequest) message;
    final String to = request.to();
    final File file = request.file();
    // Prepare the request.
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpContext context = new BasicHttpContext();
    final SSLSocketFactory sockets = new SSLSocketFactory(strategy);
    final Scheme scheme = new Scheme("https", 443, sockets);
    client.getConnectionManager().getSchemeRegistry().register(scheme);
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password);
    final HttpPost post = new HttpPost(url + to);
    final String mime = URLConnection.guessContentTypeFromName(file.getName());
    final FileEntity entity = new FileEntity(file, mime);
    post.addHeader(new BasicScheme().authenticate(credentials, post, context));
    post.setEntity(entity);/*from  w w  w . j  a  v  a2  s. co  m*/
    // Handle the response.
    final HttpResponse response = client.execute(post, context);
    final StatusLine status = response.getStatusLine();
    final int code = status.getStatusCode();
    if (HttpStatus.SC_CREATED == code) {
        EntityUtils.consume(response.getEntity());
        final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
        final Header location = headers[0];
        final String resource = location.getValue();
        return URI.create(resource);
    } else {
        final StringBuilder buffer = new StringBuilder();
        buffer.append(code).append(" ").append(status.getReasonPhrase());
        throw new FaxServiceException(buffer.toString());
    }
}

From source file:fx.browser.Window.java

public void setLocation(String location) throws URISyntaxException {
    System.out.println("# " + this.toString() + "-Classloader: " + getClass().getClassLoader().toString()
            + " setLocation()");
    this.location = location;
    HttpGet httpGet = new HttpGet(new URI(location));

    try (CloseableHttpResponse response = Browser.getHttpClient().execute(httpGet)) {
        switch (response.getStatusLine().getStatusCode()) {

        case HttpStatus.SC_OK:
            FXMLLoader loader = new FXMLLoader();
            Header header = response.getFirstHeader("class-loader-url");

            if (header != null) {
                URL url = new URL(location);

                url = new URL(url.getProtocol(), url.getHost(), url.getPort(), header.getValue());
                if (logger.isLoggable(Level.INFO)) {
                    logger.log(Level.INFO, "Set up remote classloader: {0}", url);
                }//from   w  w  w . j  a v  a  2s .c  o m

                loader.setClassLoader(HttpClassLoader.getInstance(url, getClass().getClassLoader()));
            }

            try {
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();

                response.getEntity().writeTo(buffer);
                response.close();
                setContent(loader.load(new ByteArrayInputStream(buffer.toByteArray())));
            } catch (Exception e) {
                response.close();
                logger.log(Level.INFO, e.toString(), e);
                Node node = loader.load(getClass().getResourceAsStream("/fxml/webview.fxml"));
                WebViewController controller = (WebViewController) loader.getController();

                controller.view(location);
                setContent(node);
            }

            break;

        case HttpStatus.SC_UNAUTHORIZED:
            response.close();
            Optional<Pair<String, String>> result = new LoginDialog().showAndWait();

            if (result.isPresent()) {
                URL url = new URL(location);

                Browser.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                        new UsernamePasswordCredentials(result.get().getKey(), result.get().getValue()));
                setLocation(location);
            }

            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.xwiki.contrib.jira.macro.internal.source.HTTPJIRAFetcher.java

private void setPreemptiveBasicAuthentication(HttpClientContext context, JIRAServer jiraServer,
        HttpHost targetHost) {/*from  w  w w . java 2 s  .c  o  m*/
    // Connect to JIRA using basic authentication if username and password are defined
    // Note: Set up preemptive basic authentication since JIRA can accept both unauthenticated and authenticated
    // requests. See https://developer.atlassian.com/server/jira/platform/basic-authentication/
    if (StringUtils.isNotBlank(jiraServer.getUsername()) && StringUtils.isNotBlank(jiraServer.getPassword())) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(jiraServer.getUsername(), jiraServer.getPassword()));
        // 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
        context.setCredentialsProvider(provider);
        context.setAuthCache(authCache);
    }
}

From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java

@Test
public void testCookieForStateFullClient() throws Exception {
    setAnonymousAccess(false);/*from   w w w.j  a  v  a2  s .c  o  m*/

    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + "content/";
    URI nexusBaseURI = new URI(url);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "SomeUAThatWillMakeMeLookStateful/1.0");
    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(),
            nexusBaseURI.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // stateful clients must login first, since other rest urls create no sessions
    String loginUrl = this.getBaseNexusUrl() + "service/local/authentication/login";
    assertThat(executeAndRelease(httpClient, new HttpGet(loginUrl), localcontext), equalTo(200));

    // after login check content but make sure only cookie is used
    httpClient.getCredentialsProvider().clear();
    HttpGet getMethod = new HttpGet(url);
    assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200));
    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    assertThat("Session Cookie not set", sessionCookie, notNullValue());
    httpClient.getCookieStore().clear(); // remove cookies

    // do not set the cookie, expect failure
    HttpGet failedGetMethod = new HttpGet(url);
    assertThat(executeAndRelease(httpClient, failedGetMethod, null), equalTo(401));

    // set the cookie expect a 200, If a cookie is set, and cannot be found on the server, the response will fail
    // with a 401
    httpClient.getCookieStore().addCookie(sessionCookie);
    getMethod = new HttpGet(url);
    assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200));
}

From source file:com.amalto.workbench.utils.HttpClientUtil.java

private static DefaultHttpClient wrapAuthClient(String url, String username, String password)
        throws SecurityException {
    DefaultHttpClient client = createClient();
    URI uri = URI.create(url);
    AuthScope authScope = new AuthScope(uri.getHost(), uri.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    client.getCredentialsProvider().setCredentials(authScope, credentials);
    return client;
}

From source file:pl.wavesoftware.wfirma.api.simple.mapper.SimpleGateway.java

private String get(@Nonnull HttpRequest httpRequest) throws WFirmaException {
    httpRequest.setHeader("Accept", "text/xml");
    HttpHost target = getTargetHost();// www.ja v  a  2s  . com
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(credentials.getConsumerKey(), credentials.getConsumerSecret()));
    try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build()) {

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

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

        try (CloseableHttpResponse response = httpclient.execute(target, httpRequest, localContext)) {
            return getContent(response);
        }
    } catch (IOException ioe) {
        throw new RemoteGatewayException(ioe);
    }
}