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.openhab.binding.rwesmarthome.internal.communicator.util.HttpComponentsHelper.java

/**
 * prepare for the https connection/*from ww w .j av  a2 s.  c o  m*/
 * call this in the constructor of the class that does the connection if
 * it's used multiple times
 */
private void setup() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    // http scheme
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    // https scheme
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

    params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1));
    params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf8");

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // set the user credentials for our site "example.com"
    credentialsProvider.setCredentials(new AuthScope("example.com", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("UserNameHere", "UserPasswordHere"));
    clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

    context = new BasicHttpContext();
    context.setAttribute("http.auth.credentials-provider", credentialsProvider);
}

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

@Override
public Object dump() throws Exception {
    Requisition requisition = null;// w w  w.j  a v  a 2s  . co  m

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

        // If username and password was found, inject the credentials
        if (getUserName() != null && getPassword() != 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(getUserName(),
                    getPassword());

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

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

        HttpClient client = builder.build();
        HttpGet request = new HttpGet(getUrl());
        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);
    } else {
        LOGGER.error("Parameter requisition.url is missing in requisition.properties");
    }
    if (requisition == null) {
        LOGGER.error("Requisition is null for unknown reasons");
        return null;
    }
    LOGGER.info("HttpRequisitionSource delivered for requisition '{}'", requisition.getNodes().size());
    return requisition;
}

From source file:hu.dolphio.tprttapi.service.TrackingFlushServiceTpImpl.java

public TrackingFlushServiceTpImpl(String dateFrom, String dateTo) {
    this.dateFrom = dateFrom;
    this.dateTo = dateTo;

    targetHost = new HttpHost(propertyReader.getTpHost(), 80, "http");
    credsProvider = new BasicCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(propertyReader.getTpUserName(),
            propertyReader.getTpPassword());
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials);
    config = RequestConfig.custom().setSocketTimeout(propertyReader.getConnectionTimeout())
            .setConnectTimeout(propertyReader.getConnectionTimeout()).build();

    AuthCache authCache = new BasicAuthCache();

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

    clientContext.setAuthCache(authCache);
}

From source file:com.bluexml.side.deployer.alfresco.directcopy.AlfrescoShareDirectDeployer.java

private void reloadWebScripts() throws AuthenticationException, Exception {
    System.out.println("AlfrescoShareDirectDeployer.reloadWebScripts()");

    String alfrescoURL = getGenerationParameters().get(CONFIGURATION_PARAMETER_SHARE_URL);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost post = new HttpPost(alfrescoURL + SERVICE_RESET_ON_SUBMIT_REFRESH_WEB_SCRIPTS);

    Credentials defaultcreds = new UsernamePasswordCredentials(getAdminLogin(), getAdminPassWord());
    post.addHeader(new BasicScheme().authenticate(defaultcreds, post));

    post.addHeader("Content-Type", FORM_URL_ENCODED_CONTENT_TYPE + "; charset=UTF-8");
    String executeRequest = AlfrescoHotDeployerHelper.executeRequest(httpclient, post);

    // search for error

    System.out.println(executeRequest);
}

From source file:com.impetus.client.couchdb.utils.CouchDBTestUtils.java

/**
 * Initiate http client./*w ww .  j  av  a 2  s . c o  m*/
 * 
 * @param kunderaMetadata
 *            the kundera metadata
 * @param persistenceUnit
 *            the persistence unit
 * @return the http client
 */
public static HttpClient initiateHttpClient(final KunderaMetadata kunderaMetadata, String persistenceUnit) {
    PersistenceUnitMetadata pumMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,
            persistenceUnit);

    SchemeSocketFactory ssf = null;
    ssf = PlainSocketFactory.getSocketFactory();
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    int port = Integer.parseInt(pumMetadata.getProperty(PersistenceProperties.KUNDERA_PORT));
    String host = pumMetadata.getProperty(PersistenceProperties.KUNDERA_NODES);
    String userName = pumMetadata.getProperty(PersistenceProperties.KUNDERA_USERNAME);
    String password = pumMetadata.getProperty(PersistenceProperties.KUNDERA_PASSWORD);

    schemeRegistry.register(new Scheme("http", port, ssf));
    PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
    HttpClient httpClient = new DefaultHttpClient(ccm);

    try {
        // Http params
        httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

        // basic authentication
        if (userName != null && password != null) {
            ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(new AuthScope(host, port),
                    new UsernamePasswordCredentials(userName, password));
        }
        // request interceptor
        ((DefaultHttpClient) httpClient).addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context) throws IOException {

            }
        });
        // response interceptor
        ((DefaultHttpClient) httpClient).addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context) throws IOException {

            }
        });
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
    return httpClient;
}

From source file:com.cisco.cta.taxii.adapter.httpclient.CredentialsProviderFactory.java

private void addTaxiiCredentials(CredentialsProvider credsProvider) {
    URL url = settings.getPollEndpoint();
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(settings.getUsername(), settings.getPassword()));
}

From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPProxyConfigurator.java

/**
 * Configure HTTP Proxy settings of commons-httpclient HostConfiguration.
 * Proxy settings can be get from axis2.xml, Java proxy settings or can be
 * override through property in message context.
 * <p/>/*from  w  w  w  .  j a  v  a 2  s .c  om*/
 * HTTP Proxy setting element format: <parameter name="Proxy">
 * <Configuration> <ProxyHost>example.org</ProxyHost>
 * <ProxyPort>3128</ProxyPort> <ProxyUser>EXAMPLE/John</ProxyUser>
 * <ProxyPassword>password</ProxyPassword> <Configuration> <parameter>
 *
 * @param messageContext
 *            in message context for
 * @param httpClient
 *            instance
 * @throws org.apache.axis2.AxisFault
 *             if Proxy settings are invalid
 */
public static void configure(MessageContext messageContext, AbstractHttpClient httpClient) throws AxisFault {

    Credentials proxyCredentials = null;
    String proxyHost = null;
    String nonProxyHosts = null;
    Integer proxyPort = -1;
    String proxyUser = null;
    String proxyPassword = null;

    // Getting configuration values from Axis2.xml
    Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration()
            .getParameter(HTTPTransportConstants.ATTR_PROXY);
    if (proxySettingsFromAxisConfig != null) {
        OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig);
        proxyHost = getProxyHost(proxyConfiguration);
        proxyPort = getProxyPort(proxyConfiguration);
        proxyUser = getProxyUser(proxyConfiguration);
        proxyPassword = getProxyPassword(proxyConfiguration);
        if (proxyUser != null) {
            if (proxyPassword == null) {
                proxyPassword = "";
            }

            proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);

            int proxyUserDomainIndex = proxyUser.indexOf("\\");
            if (proxyUserDomainIndex > 0) {
                String domain = proxyUser.substring(0, proxyUserDomainIndex);
                if (proxyUser.length() > proxyUserDomainIndex + 1) {
                    String user = proxyUser.substring(proxyUserDomainIndex + 1);
                    proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain);
                }
            }
        }
    }

    // If there is runtime proxy settings, these settings will override
    // settings from axis2.xml
    HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext
            .getProperty(HTTPConstants.PROXY);
    if (proxyProperties != null) {
        String proxyHostProp = proxyProperties.getProxyHostName();
        if (proxyHostProp == null || proxyHostProp.length() <= 0) {
            throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter");
        } else {
            proxyHost = proxyHostProp;
        }
        proxyPort = proxyProperties.getProxyPort();

        // Overriding credentials
        String userName = proxyProperties.getUserName();
        String password = proxyProperties.getPassWord();
        String domain = proxyProperties.getDomain();

        if (userName != null && password != null && domain != null) {
            proxyCredentials = new NTCredentials(userName, password, proxyHost, domain);
        } else if (userName != null && domain == null) {
            proxyCredentials = new UsernamePasswordCredentials(userName, password);
        }

    }

    // Overriding proxy settings if proxy is available from JVM settings
    String host = System.getProperty(HTTPTransportConstants.HTTP_PROXY_HOST);
    if (host != null) {
        proxyHost = host;
    }

    String port = System.getProperty(HTTPTransportConstants.HTTP_PROXY_PORT);
    if (port != null) {
        proxyPort = Integer.parseInt(port);
    }

    if (proxyCredentials != null) {
        // TODO : Set preemptive authentication, but its not recommended in HC 4
        httpClient.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);

        httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, proxyCredentials);
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    }
}

From source file:org.metaeffekt.dcc.commons.ant.HttpRequestTask.java

/**
 * Executes the task./*from w ww .  j  a  v a  2 s . c om*/
 * 
 * @see org.apache.tools.ant.Task#execute()
 */
@Override
public void execute() {

    StringBuilder sb = new StringBuilder();
    sb.append(serverScheme).append("://").append(serverHostName).append(':').append(serverPort);
    sb.append("/").append(uri);
    String url = sb.toString();

    BasicCredentialsProvider credentialsProvider = null;
    if (username != null) {
        log("User: " + username, Project.MSG_DEBUG);
        credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(serverHostName, serverPort),
                new UsernamePasswordCredentials(username, password));
    }

    HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
            .build();

    try {
        switch (httpMethod) {
        case GET:
            HttpGet get = new HttpGet(url);
            doRequest(httpClient, get);
            break;
        case PUT:
            HttpPut put = new HttpPut(url);
            if (body == null) {
                body = "";
            }
            log("Setting body: " + body, Project.MSG_DEBUG);
            put.setEntity(new StringEntity(body, ContentType.create(contentType)));
            doRequest(httpClient, put);
            break;
        case POST:
            HttpPost post = new HttpPost(url);
            if (body == null) {
                body = "";
            }
            log("Setting body: " + body, Project.MSG_DEBUG);
            post.setEntity(new StringEntity(body, ContentType.create(contentType)));
            doRequest(httpClient, post);
            break;
        case DELETE:
            HttpDelete delete = new HttpDelete(url);
            doRequest(httpClient, delete);
            break;
        default:
            throw new IllegalArgumentException("HttpMethod " + httpMethod + " not supported!");
        }
    } catch (IOException e) {
        throw new BuildException(e);
    }
}

From source file:org.oscarehr.fax.core.FaxImporter.java

public void poll() {

    List<FaxConfig> faxConfigList = faxConfigDao.findAll(null, null);
    DefaultHttpClient client = new DefaultHttpClient();

    for (FaxConfig faxConfig : faxConfigList) {
        if (faxConfig.isActive()) {

            client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(faxConfig.getSiteUser(), faxConfig.getPasswd()));

            HttpGet mGet = new HttpGet(faxConfig.getUrl() + PATH + "/" + faxConfig.getFaxUser());
            mGet.setHeader("accept", "application/json");
            mGet.setHeader("user", faxConfig.getFaxUser());
            mGet.setHeader("passwd", faxConfig.getFaxPasswd());

            try {
                HttpResponse response = client.execute(mGet);
                log.info("RESPONSE: " + response.getStatusLine().getStatusCode());

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    HttpEntity httpEntity = response.getEntity();
                    String content = EntityUtils.toString(httpEntity);

                    log.info("CONTENT: " + content);
                    ObjectMapper mapper = new ObjectMapper();

                    List<FaxJob> faxList = mapper.readValue(content, new TypeReference<List<FaxJob>>() {
                    });/*from   w  w w.j  av a  2  s .  co  m*/

                    FaxJob faxFile;
                    for (FaxJob receivedFax : faxList) {
                        if ((faxFile = downloadFax(client, faxConfig, receivedFax)) != null) {
                            if (saveAndInsertIntoQueue(faxConfig, receivedFax, faxFile)) {
                                deleteFax(client, faxConfig, receivedFax);
                            }
                        }
                    }

                }

                mGet.releaseConnection();
            } catch (ClientProtocolException e) {
                log.error("HTTP WS CLIENT ERROR", e);

            } catch (IOException e) {
                log.error("IO ERROR", e);

            } catch (Exception e) {
                log.error("UNKNOWN ERROR ", e);
            } finally {
                mGet.releaseConnection();
            }

        }
    }

}

From source file:edu.si.services.camel.fcrepo.FcrepoIntegrationTest.java

@BeforeClass
public static void loadObjectsIntoFedora() throws IOException, InterruptedException {
    BasicCredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(ANY, new UsernamePasswordCredentials(System.getProperty("si.fedora.user"),
            System.getProperty("si.fedora.password")));
    httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    ingest(PID, Paths.get(BUILD_DIR, TEST_FOXML));
}