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:com.fibon.maven.confluence.ExportPageConfluenceMojo.java

private HttpGet prepareExportPageRequest(Format format, Long pageId) throws MojoFailureException {
    HttpGet get = new HttpGet(url + format.url + "?pageId=" + pageId);
    AuthenticationInfo info = wagonManager.getAuthenticationInfo(serverId);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(info.getUserName(),
            info.getPassword());/* w  w  w.j a va2 s .  co  m*/
    BasicScheme scheme = new BasicScheme();
    try {
        Header authorizationHeader = scheme.authenticate(credentials, get);
        get.addHeader(authorizationHeader);
        return get;
    } catch (AuthenticationException e) {
        throw fail("Unable to set authentication data", e);
    }
}

From source file:com.sulacosoft.bitcoindconnector4j.BitcoindApiHandler.java

public BitcoindApiHandler(String host, int port, String protocol, String uri, String username,
        String password) {/*w  ww.  j a  v a 2 s.  c om*/
    this.uri = uri;

    httpClient = HttpClients.createDefault();
    targetHost = new HttpHost(host, port, protocol);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));

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

    context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
}

From source file:com.unispezi.cpanelremotebackup.http.HTTPClient.java

public HTTPClient(String hostName, int port, boolean secure, String userName, String password) {
    this.httpClient = new DefaultHttpClient();
    host = new HttpHost(hostName, port, secure ? "https" : null);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostName, port),
            new UsernamePasswordCredentials(userName, password));

    //        HttpHost proxy = new HttpHost("localhost", 8888);
    //        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    // Set up HTTP basic auth (without challenge) or "preemptive auth"
    // Taken from http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html#d5e1031

    // Create AuthCache instance
    BasicAuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);//from  ww  w . j a va2s . c o  m

    // Add AuthCache to the execution context
    localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, 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.arcbees.vcs.AbstractVcsApi.java

protected void includeAuthentication(HttpRequest request, Credentials credentials) throws IOException {
    try {//  w  ww  .  j  a v a 2  s  .  co  m
        request.addHeader(new BasicScheme().authenticate(credentials, request, null));
    } catch (AuthenticationException e) {
        throw new IOException("Failed to set authentication for request. " + e.getMessage(), e);
    }
}

From source file:com.arduino2fa.xbee.ReceivePacket.java

private ReceivePacket() throws Exception {
    XBee xbee = new XBee();

    int count = 0;
    int errors = 0;

    // Transmit stuff
    final int timeout = 5000;

    int ackErrors = 0;
    int ccaErrors = 0;
    int purgeErrors = 0;
    long now;//  w  w w.  ja va2 s  .c o m

    // HTTP stuff
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpHost httpHost = new HttpHost("ec2-54-186-213-97.us-west-2.compute.amazonaws.com", 3000, "http");

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials("admin", "admin") // TODO get from command line
    );

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(httpHost, basicScheme);

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

    HttpGet httpGet = new HttpGet("/token-requests/1");

    CloseableHttpResponse httpResponse;

    BufferedReader br;
    StringBuffer result;
    String line;

    try {
        // Connect to the XBee
        xbee.open(XbeeConfig.PORT, XbeeConfig.BAUD_RATE);

        now = System.currentTimeMillis();

        // Loop indefinitely; sleeps for a few seconds at the end of every iteration
        while (true) {

            // Check if there are queued tx requests on the server
            httpResponse = httpClient.execute(httpHost, httpGet, httpClientContext);
            br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

            result = new StringBuffer();

            while ((line = br.readLine()) != null) {
                result.append(line);
            }

            // Check if the result is a JSON object
            if (result.charAt(0) != '{') {
                log.error("Result " + result.toString() + " is not a JSON object");
                continue;
            }

            JSONObject object = (JSONObject) JSONValue.parse(result.toString());

            if (object != null) {
                Long time = (Long) object.get("time");

                // Check if the request is a new one (created after last check)
                if (time > last) {
                    String token = (String) object.get("token");
                    byte[] tokenHex = SimpleCrypto.toByte(token);

                    int[] payload = new int[] { tokenHex[0], tokenHex[1], tokenHex[2] };

                    XBeeAddress16 destination = new XBeeAddress16(0xFF, 0xFF);
                    TxRequest16 tx = new TxRequest16(destination, payload);

                    try {
                        log.info("sending tx request with payload: " + token);
                        XBeeResponse response = xbee.sendSynchronous(tx, timeout);

                        if (response.getApiId() != ApiId.TX_STATUS_RESPONSE) {
                            log.debug("expected tx status but received " + response);
                        } else {
                            log.debug("got tx status");

                            if (((TxStatusResponse) response).getFrameId() != tx.getFrameId()) {
                                throw new RuntimeException("frame id does not match");
                            }

                            if (((TxStatusResponse) response).getStatus() != TxStatusResponse.Status.SUCCESS) {
                                errors++;

                                if (((TxStatusResponse) response).isAckError()) {
                                    ackErrors++;
                                } else if (((TxStatusResponse) response).isCcaError()) {
                                    ccaErrors++;
                                } else if (((TxStatusResponse) response).isPurged()) {
                                    purgeErrors++;
                                }

                                log.debug("Tx status failure with status: "
                                        + ((TxStatusResponse) response).getStatus());
                            } else {
                                // success
                                log.debug("Success.  count is " + count + ", errors is " + errors + ", in "
                                        + (System.currentTimeMillis() - now) + ", ack errors " + ackErrors
                                        + ", ccaErrors " + ccaErrors + ", purge errors " + purgeErrors);
                            }

                            count++;

                        }
                    } catch (XBeeTimeoutException e) {
                        e.printStackTrace();
                    }
                }
            }

            last = System.currentTimeMillis();
            httpGet.releaseConnection();

            // Delay
            Thread.sleep(2000);
        }
    } finally {
        xbee.close();
    }
}

From source file:org.kaaproject.kaa.server.common.admin.HttpComponentsRequestFactoryBasicAuth.java

private HttpContext createHttpContext() {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);/*from w ww.  j  a  v  a2  s  .  c  om*/
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}

From source file:org.nuxeo.connect.registration.RegistrationHelper.java

protected static HttpClientContext getHttpClientContext(String url, String login, String password) {
    HttpClientContext context = HttpClientContext.create();

    // Set credentials provider
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    if (login != null) {
        Credentials ba = new UsernamePasswordCredentials(login, password);
        credentialsProvider.setCredentials(AuthScope.ANY, ba);
    }/* w  w  w. ja  v  a2  s.co  m*/
    context.setCredentialsProvider(credentialsProvider);

    // Create AuthCache instance for preemptive authentication
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    try {
        authCache.put(URIUtils.extractHost(new URI(url)), basicAuth);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    context.setAuthCache(authCache);

    // Create request configuration
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(10000);

    // Configure the http proxy if needed
    ProxyHelper.configureProxyIfNeeded(requestConfigBuilder, credentialsProvider, url);

    context.setRequestConfig(requestConfigBuilder.build());
    return context;
}

From source file:org.nekorp.workflow.desktop.rest.util.RestTemplateFactory.java

@PostConstruct
public void init() {
    targetHost = new HttpHost(host, port, protocol);
    //connectionPool = new PoolingHttpClientConnectionManager();
    //connectionPool.setDefaultMaxPerRoute(10);
    //connectionPool.setMaxTotal(20);

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    //wildcard ssl certificate
    SSLContext sslContext = SSLContexts.createDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);

    httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            //.setConnectionManager(connectionPool)
            .setSSLSocketFactory(sslsf).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(targetHost, basicAuth);

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

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactoryBasicAuth(
            httpclient, localContext);/*from   w  w  w .  jav  a  2  s  . c  om*/
    this.template = new RestTemplate();
    template.getMessageConverters().add(new BufferedImageHttpMessageConverter());
    template.setRequestFactory(factory);
}

From source file:com.ibm.connectors.splunklog.SplunkHttpConnection.java

public Properties sendLogEvent(SplunkConnectionData connData, byte[] thePayload, Properties properties)
        throws ConnectorException {
    HttpClient myhClient = HttpClients.custom().setConnectionManager(this.cm).build();

    HttpClientContext myhContext = HttpClientContext.create();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(connData.getUser(), connData.getPass()));
    AuthCache authCache = new BasicAuthCache();
    authCache.put(new HttpHost(connData.getHost(), Integer.parseInt(connData.getPort()), connData.getScheme()),
            new BasicScheme());

    myhContext.setCredentialsProvider(credsProvider);
    myhContext.setAuthCache(authCache);//from   w w  w.j  av a 2 s . c  o  m

    HttpPost myhPost = new HttpPost(connData.getSplunkURI());

    ByteArrayEntity payload = new ByteArrayEntity(thePayload);
    try {
        myhPost.setEntity(payload);
        HttpResponse response = myhClient.execute(myhPost, myhContext);
        Integer statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200 && !connData.getIgnoreSplunkErrors()) {
            throw new ConnectorException(
                    "Error posting log event to Splunk: " + response.getStatusLine().toString());
        }
        System.out.println(response.getStatusLine().toString());
        properties.setProperty("status", String.valueOf(statusCode));
        Integer leasedConns = Integer
                .valueOf(((PoolingHttpClientConnectionManager) this.cm).getTotalStats().getLeased());
        properties.setProperty("conns_leased", leasedConns.toString());
        Integer availConns = Integer
                .valueOf(((PoolingHttpClientConnectionManager) this.cm).getTotalStats().getAvailable());
        properties.setProperty("conns_available", availConns.toString());
    } catch (IOException e) {
        e.fillInStackTrace();
        throw new ConnectorException(e.toString());
    }
    return properties;
}