Java 类org.apache.http.impl.auth.BasicScheme 实例源码

项目:purecloud-iot    文件:TestClientAuthentication.java   
@Test
public void testPreemptiveAuthentication() throws Exception {
    final CountingAuthHandler requestHandler = new CountingAuthHandler();
    this.serverBootstrap.registerHandler("*", requestHandler);

    final HttpHost target = start();

    final HttpClientContext context = HttpClientContext.create();
    final AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());
    context.setAuthCache(authCache);
    final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("test", "test"));
    context.setCredentialsProvider(credsProvider);

    final HttpGet httpget = new HttpGet("/");
    final HttpResponse response1 = this.httpclient.execute(target, httpget, context);
    final HttpEntity entity1 = response1.getEntity();
    Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity1);
    EntityUtils.consume(entity1);

    Assert.assertEquals(1, requestHandler.getCount());
}
项目:Charrizard    文件:MyAnimeListQuery.java   
public MyAnimeListQuery(Charrizard charrizard) {
    status = MyAnimeListStatus.UNKNOWN_ERROR;
    errorDescription = "Unknown error.";
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("https://myanimelist.net/api/account/verify_credentials.xml");
        httpGet.addHeader(BasicScheme.authenticate(
                new UsernamePasswordCredentials(charrizard.getSettings().getMyAnimeList().getUsername(), charrizard.getSettings().getMyAnimeList().getUsername()),
                "UTF-8", false));

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity responseEntity = httpResponse.getEntity();
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            status = MyAnimeListStatus.AUTH_ERROR;
            errorDescription = "Authorization Error: " + httpResponse.getStatusLine().getReasonPhrase();
            return;
        }
    } catch (IOException e) {
        status = MyAnimeListStatus.REQUEST_ERROR;
        errorDescription = "Can't connect to MyAnimeList: " + e.getMessage();
        e.printStackTrace();
    }
}
项目:elasticsearch_my    文件:RestClientMultipleHostsTests.java   
@Before
@SuppressWarnings("unchecked")
public void createRestClient() throws IOException {
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class),
           any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() {
        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
            HttpUriRequest request = (HttpUriRequest)requestProducer.generateRequest();
            HttpHost httpHost = requestProducer.getTarget();
            HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2];
            assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class));
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
            //return the desired status code or exception depending on the path
            if (request.getURI().getPath().equals("/soe")) {
                futureCallback.failed(new SocketTimeoutException(httpHost.toString()));
            } else if (request.getURI().getPath().equals("/coe")) {
                futureCallback.failed(new ConnectTimeoutException(httpHost.toString()));
            } else if (request.getURI().getPath().equals("/ioe")) {
                futureCallback.failed(new IOException(httpHost.toString()));
            } else {
                int statusCode = Integer.parseInt(request.getURI().getPath().substring(1));
                StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, "");
                futureCallback.completed(new BasicHttpResponse(statusLine));
            }
            return null;
        }
    });
    int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5);
    httpHosts = new HttpHost[numHosts];
    for (int i = 0; i < numHosts; i++) {
        httpHosts[i] = new HttpHost("localhost", 9200 + i);
    }
    failureListener = new HostsTrackingFailureListener();
    restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener);
}
项目:nextcloud-java-api    文件:ConnectorCommon.java   
private HttpClientContext prepareContext()
{
    HttpHost targetHost = new HttpHost(serverConfig.getServerName(), serverConfig.getPort(), serverConfig.isUseHTTPS() ? "https" : "http");
    AuthCache authCache = new BasicAuthCache();
    authCache.put(targetHost, new BasicScheme());

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials
     = new UsernamePasswordCredentials(serverConfig.getUserName(), serverConfig.getPassword());
    credsProvider.setCredentials(AuthScope.ANY, credentials);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
    return context;
}
项目:living-documentation    文件:ConfluenceRestClient.java   
private HttpContext httpContext() {
    BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
    if (isNotBlank(this.username) && this.password != null) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);
        HttpHost httpHost = HttpHost.create(this.rootConfluenceUrl);
        AuthScope authScope = new AuthScope(httpHost);
        basicCredentialsProvider.setCredentials(authScope, credentials);

        BasicAuthCache basicAuthCache = new BasicAuthCache();
        basicAuthCache.put(httpHost, new BasicScheme());

        HttpClientContext httpClientContext = HttpClientContext.create();
        httpClientContext.setCredentialsProvider(basicCredentialsProvider);
        httpClientContext.setAuthCache(basicAuthCache);

        return httpClientContext;
    } else {
        return null;
    }
}
项目:boohee_v5.6    文件:AsyncHttpClient$3.java   
public void process(HttpRequest request, HttpContext context) throws HttpException,
        IOException {
    AuthState authState = (AuthState) context.getAttribute("http.auth.target-scope");
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute("http.auth" +
            ".credentials-provider");
    HttpHost targetHost = (HttpHost) context.getAttribute("http.target_host");
    if (authState.getAuthScheme() == null) {
        Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName
                (), targetHost.getPort()));
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}
项目:aws-sdk-java-v2    文件:ApacheUtils.java   
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     ProxyConfiguration proxyConfiguration) {

    if (proxyConfiguration.preemptiveBasicAuthenticationEnabled()) {
        HttpHost targetHost = new HttpHost(proxyConfiguration.endpoint().getHost(), proxyConfiguration.endpoint().getPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(proxyConfiguration);
        // 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);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
项目:ibm-cos-sdk-java    文件:ApacheUtils.java   
private static void addPreemptiveAuthenticationProxy(HttpClientContext clientContext,
                                                     HttpClientSettings settings) {

    if (settings.isPreemptiveBasicProxyAuth()) {
        HttpHost targetHost = new HttpHost(settings.getProxyHost(), settings
                .getProxyPort());
        final CredentialsProvider credsProvider = newProxyCredentialsProvider(settings);
        // 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);

        clientContext.setCredentialsProvider(credsProvider);
        clientContext.setAuthCache(authCache);
    }
}
项目:geoportal-server-harvester    文件:HttpClientContextBuilder.java   
/**
 * Creates client context.
 * @param url url
 * @param cred credentials
 * @return client context
 */
public static HttpClientContext createHttpClientContext(URL url, SimpleCredentials cred) {
  HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
  CredentialsProvider credsProvider = new BasicCredentialsProvider();
  credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
          new UsernamePasswordCredentials(cred.getUserName(),cred.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
  HttpClientContext context = HttpClientContext.create();
  context.setCredentialsProvider(credsProvider);
  context.setAuthCache(authCache);

  return context;
}
项目:BitcoindConnector4J    文件:BitcoindApiHandler.java   
public BitcoindApiHandler(String host, int port, String protocol, String uri, String username, String password) {
    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);
}
项目:infiniboard    文件:UrlSourceJob.java   
private HttpClientContext configureContext(CredentialsProvider credentialsProvider, String url) {
  if (credentialsProvider != null) {
    try {
      URL targetUrl = new URL(url);

      HttpHost targetHost =
          new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol());
      AuthCache authCache = new BasicAuthCache();
      authCache.put(targetHost, new BasicScheme());

      final HttpClientContext context = HttpClientContext.create();
      context.setCredentialsProvider(credentialsProvider);
      context.setAuthCache(authCache);

      return context;
    } catch (MalformedURLException e) {
      LOG.error("Cannot parse URL '{}'", url, e);
    }
  }
  return null;
}
项目:foursquared    文件:HttpApiWithBasicAuth.java   
@Override
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

    AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    CredentialsProvider credsProvider = (CredentialsProvider)context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    // If not auth scheme has been initialized yet
    if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        // Obtain credentials matching the target host
        org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope);
        // If found, generate BasicScheme preemptively
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}
项目:foursquared    文件:SpecialWebViewActivity.java   
@Override
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

    AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    CredentialsProvider credsProvider = (CredentialsProvider)context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    // If not auth scheme has been initialized yet
    if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope);
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}
项目:ibm-bpm-rest-client    文件:SimpleBpmClient.java   
private CloseableHttpClient createClient(String user, String password) {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(TOTAL_CONN);
    cm.setDefaultMaxPerRoute(ROUTE_CONN);

    logger.info("Pooling connection manager created.");

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    logger.info("Default credentials provider created.");

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();

    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicAuth);
    logger.info("Auth cache created.");

    httpContext = HttpClientContext.create();
    httpContext.setCredentialsProvider(credentialsProvider);
    httpContext.setAuthCache(authCache);
    logger.info("HttpContext filled with Auth cache.");

    return HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(cm)
            .build();
}
项目:boteco    文件:DefaultRestConfiguration.java   
@Override
public RestConfiguration withAuthentication(String user, String password) {
  // Create AuthCache instance
  AuthCache authCache = new BasicAuthCache();
  // Generate BASIC scheme object and add it to the local auth cache
  BasicScheme basicAuth = new BasicScheme();
  CredentialsProvider provider = new BasicCredentialsProvider();

  URI uri = request.getURI();
  authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth);
  provider.setCredentials(new AuthScope(uri.getHost(), AuthScope.ANY_PORT),
      new UsernamePasswordCredentials(user, password));

  this.context.setCredentialsProvider(provider);
  this.context.setAuthCache(authCache);

  return this;
}
项目:communote-server    文件:ConfluenceUserImageProvider.java   
@Override
protected HttpContext getRequestContext(URI imageUrl, String imageIdentifier,
        ConfluenceConfiguration config) {
    HttpHost targetHost = new HttpHost(imageUrl.getHost(), imageUrl.getPort());
    CredentialsProvider credentialsProviderProvider = new BasicCredentialsProvider();
    credentialsProviderProvider.setCredentials(new AuthScope(targetHost.getHostName(),
            targetHost.getPort()), new UsernamePasswordCredentials(config.getAdminLogin(),
            config.getAdminPassword()));

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    // preemptive authentication (send credentials with request) by adding host to auth cache
    // TODO maybe use real basic auth challenge?
    authCache.put(targetHost, basicAuth);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProviderProvider);
    context.setAuthCache(authCache);
    return context;
}
项目:playground    文件:BasicAuthConfigurator.java   
@Override
    public BasicHttpContext createContext(HttpHost targetHost) {

        final AuthCache authCache = new BasicAuthCache();

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

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        // OPTIMIZED
        credentialsProvider
                .setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        // NON-OPTIMIZED
//        credentialsProvider.setCredentials(
//                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
//                new UsernamePasswordCredentials(username, password));

        final BasicHttpContext context = new BasicHttpContext();
        context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        context.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider);

        return context;
    }
项目:purecloud-iot    文件:TestRequestAuthCache.java   
@Before
public void setUp() {
    this.target = new HttpHost("localhost", 80);
    this.proxy = new HttpHost("localhost", 8080);

    this.credProvider = new BasicCredentialsProvider();
    this.creds1 = new UsernamePasswordCredentials("user1", "secret1");
    this.creds2 = new UsernamePasswordCredentials("user2", "secret2");
    this.authscope1 = new AuthScope(this.target);
    this.authscope2 = new AuthScope(this.proxy);
    this.authscheme1 = new BasicScheme();
    this.authscheme2 = new BasicScheme();

    this.credProvider.setCredentials(this.authscope1, this.creds1);
    this.credProvider.setCredentials(this.authscope2, this.creds2);

    this.targetState = new AuthState();
    this.proxyState = new AuthState();
}
项目:purecloud-iot    文件:TestClientAuthentication.java   
@Test
public void testPreemptiveAuthenticationFailure() throws Exception {
    final CountingAuthHandler requestHandler = new CountingAuthHandler();
    this.serverBootstrap.registerHandler("*", requestHandler);

    final HttpHost target = start();

    final HttpClientContext context = HttpClientContext.create();
    final AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());
    context.setAuthCache(authCache);
    final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("test", "stuff"));
    context.setCredentialsProvider(credsProvider);

    final HttpGet httpget = new HttpGet("/");
    final HttpResponse response1 = this.httpclient.execute(target, httpget, context);
    final HttpEntity entity1 = response1.getEntity();
    Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response1.getStatusLine().getStatusCode());
    Assert.assertNotNull(entity1);
    EntityUtils.consume(entity1);

    Assert.assertEquals(1, requestHandler.getCount());
}
项目:polygene-java    文件:WebRealmServiceTest.java   
@Override
public void process( final HttpRequest request, final HttpContext context )
    throws HttpException, IOException
{
    AuthState authState = (AuthState) context.getAttribute( ClientContext.TARGET_AUTH_STATE );
    CredentialsProvider credsProvider = (CredentialsProvider) context
        .getAttribute( ClientContext.CREDS_PROVIDER );
    HttpHost targetHost = (HttpHost) context.getAttribute( ExecutionContext.HTTP_TARGET_HOST );

    // If not auth scheme has been initialized yet
    if( authState.getAuthScheme() == null )
    {
        AuthScope authScope = new AuthScope( targetHost.getHostName(),
                                             targetHost.getPort() );
        // Obtain credentials matching the target host
        Credentials creds = credsProvider.getCredentials( authScope );
        // If found, generate BasicScheme preemptively
        if( creds != null )
        {
            authState.setAuthScheme( new BasicScheme() );
            authState.setCredentials( creds );
        }
    }
}
项目:foursquared.eclair    文件:HttpApiWithBasicAuth.java   
@Override
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {

    AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    CredentialsProvider credsProvider = (CredentialsProvider)context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    // If not auth scheme has been initialized yet
    if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        // Obtain credentials matching the target host
        org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope);
        // If found, generate BasicScheme preemptively
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}
项目:Cytomine-client-autobuilder    文件:HttpClient.java   
public void connect(String url, String username, String password) throws Exception {
    isAuthByPrivateKey = false;
    log.info("Connection to " + url + " with login=" + username + " and pass=" + password);
    URL = new URL(url);
    targetHost = new HttpHost(URL.getHost(), URL.getPort());
    client = new DefaultHttpClient();
    // 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
    localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Set credentials
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
}
项目:zee-jenkins    文件:RestClient.java   
private HttpClientContext createClientContext(
        String hostAddressWithProtocol, String userName, String password) {
    URL url;
    try {
        url = new URL(hostAddressWithProtocol);
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(),
                url.getProtocol());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));

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

        context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    return context;
}
项目:majordodo    文件:HTTPClientConnection.java   
private HttpClientContext getContext() throws IOException {
    if (context == null) {
        BrokerAddress broker = getBroker();
        String scheme = broker.getProtocol();
        HttpHost targetHost = new HttpHost(broker.getAddress(), broker.getPort(), scheme);

        context = HttpClientContext.create();
        if (configuration.getUsername() != null && !configuration.getUsername().isEmpty()) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword());
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME),
                creds);
            BasicAuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);
            context.setCredentialsProvider(credsProvider);
            context.setAuthCache(authCache);
        }

    }
    return context;
}
项目:fcrepo-java-client    文件:FcrepoHttpClientBuilder.java   
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    final AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);
    // If no auth scheme available yet, try to initialize it
    // preemptively
    if (authState.getAuthScheme() == null) {
        final CredentialsProvider credsProvider = (CredentialsProvider)
                context.getAttribute(HttpClientContext.CREDS_PROVIDER);
        final HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
        final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        final Credentials creds = credsProvider.getCredentials(authScope);
        if (creds == null) {
            LOGGER.debug("Cannot initiate preemtive authentication, Credentials not found!");
        }
        authState.update(new BasicScheme(), creds);
    }
}
项目:dss    文件:CommonsDataLoader.java   
protected HttpResponse getHttpResponse(final CloseableHttpClient client, final HttpUriRequest httpRequest, final String url) throws DSSException {

        final String host = httpRequest.getURI().getHost();
        final int port = httpRequest.getURI().getPort();
        final String scheme = httpRequest.getURI().getScheme();
        final HttpHost targetHost = new HttpHost(host, port, scheme);

        // 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);

        try {
            final HttpResponse response = client.execute(targetHost, httpRequest, localContext);
            return response;
        } catch (IOException e) {
            throw new DSSException(e);
        }

    }
项目:gaeproxy    文件:WeaveTransport.java   
@Override
public void process(final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    AuthState authState = (AuthState) context
            .getAttribute(ClientContext.TARGET_AUTH_STATE);
    CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    HttpHost targetHost = (HttpHost) context
            .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    if (authState.getAuthScheme() == null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(),
                targetHost.getPort());
        Credentials creds = credsProvider.getCredentials(authScope);
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }
    }
}
项目:zfj-jenkins    文件:RestClient.java   
private HttpClientContext createClientContext(
        String hostAddressWithProtocol, String userName, String password) {
    URL url;
    try {
        url = new URL(hostAddressWithProtocol);
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(),
                url.getProtocol());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(userName, password));

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

        context = HttpClientContext.create();
        context.setCredentialsProvider(credsProvider);
        context.setAuthCache(authCache);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    return context;
}
项目:Cytomine-java-client    文件:HttpClient.java   
public void connect(String url, String username, String password) throws IOException {
    isAuthByPrivateKey = false;
    log.info("Connection to " + url + " with login=" + username + " and pass=" + password);
    URL = new URL(url);
    targetHost = new HttpHost(URL.getHost(), URL.getPort());
    client = HttpClientBuilder.create().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);

    // Set credentials
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    credsProvider.setCredentials(AuthScope.ANY, creds);

    // Add AuthCache to the execution context
    localcontext = HttpClientContext.create();
    localcontext.setCredentialsProvider(credsProvider);
    localcontext.setAuthCache(authCache);
}
项目:slack4gerrit    文件:HttpHelper.java   
public static String getFromHttp(URL url, String user, String password) throws IOException
{
    HttpClientContext context = HttpClientContext.create();
    if (user != null)
    {

        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        AuthCache authCache = new BasicAuthCache();
        authCache.put(targetHost, new BasicScheme());

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
        context.setCredentialsProvider(credentialsProvider);
        context.setAuthCache(authCache);
    }
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url.toExternalForm());
    HttpResponse response = client.execute(request, context);
    InputStreamReader streamReader = new InputStreamReader(response.getEntity().getContent());
    String data = CharStreams.toString(streamReader);
    streamReader.close();
    return data;

}
项目:wiremock-velocity-transformer    文件:WireMockTestClient.java   
public WireMockResponse getWithPreemptiveCredentials(String url, int port, String username, String password) {
    HttpHost target = new HttpHost("localhost", port);
    HttpClient httpClient = httpClientWithPreemptiveAuth(target, username, password);

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    try {
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpClient.execute(target, httpget, localContext);
        return new WireMockResponse(response);
    } catch (IOException e) {
        return throwUnchecked(e, WireMockResponse.class);
    }
}
项目:artifactory    文件:PreemptiveAuthInterceptor.java   
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    HttpClientContext clientContext = HttpClientContext.adapt(context);
    AuthState authState = clientContext.getTargetAuthState();

    // If there's no auth scheme available yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
        CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
        HttpHost targetHost = clientContext.getTargetHost();
        Credentials creds = credsProvider.getCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()));
        if (creds == null) {
            log.debug("No credentials found for host " + targetHost);
        } else {
            log.debug("Updating credentials for host " + targetHost);
            authState.update(new BasicScheme(), creds);
        }
    }
}
项目:Lucee4    文件:HTTPEngine4Impl.java   
public static BasicHttpContext setCredentials(DefaultHttpClient client, HttpHost httpHost, String username,String password, boolean preAuth) {
       // set Username and Password
       if(!StringUtil.isEmpty(username,true)) {
           if(password==null)password="";
           CredentialsProvider cp = client.getCredentialsProvider();
           cp.setCredentials(
               new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
               new UsernamePasswordCredentials(username,password));



           BasicHttpContext httpContext = new BasicHttpContext();
           if(preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
           }
           return httpContext;
       }
       return null;
}
项目:Lucee4    文件:HTTPEngineImpl.java   
public static BasicHttpContext setCredentials(HttpClientBuilder builder, HttpHost httpHost, String username,String password, boolean preAuth) {
       // set Username and Password
       if(!StringUtil.isEmpty(username,true)) {
           if(password==null)password="";
           CredentialsProvider cp = new BasicCredentialsProvider();
           builder.setDefaultCredentialsProvider(cp);

           cp.setCredentials(
               new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), 
               new UsernamePasswordCredentials(username,password));



           BasicHttpContext httpContext = new BasicHttpContext();
           if(preAuth) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(httpHost, new BasicScheme());
            httpContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
           }
           return httpContext;
       }
       return null;
}
项目:elderberry    文件:TaxiiConnection.java   
@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort());
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    authCache.put(targetHost, basicAuth);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    return context;
}
项目:PP-UnifiedViews-Plugins    文件:ConceptExtractor.java   
/**
 * Create an HTTP state after authentication with credentials for future requests
 * @return a class wrapping HTTP host, client and context used for future requests
 */
private HttpStateWrapper createHttpStateWithAuth() {
    HttpHost host = new HttpHost(config.getHost(), Integer.parseInt(config.getPort()), "http");
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(host.getHostName(), host.getPort()),
            new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    return new HttpStateWrapper(host, httpclient, localContext);
}
项目:activemq-artemis    文件:UriStrategy.java   
protected void initAuthentication() {
   if (registration.getAuthenticationMechanism() != null) {
      if (registration.getAuthenticationMechanism().getType() instanceof BasicAuth) {
         BasicAuth basic = (BasicAuth) registration.getAuthenticationMechanism().getType();
         UsernamePasswordCredentials creds = new UsernamePasswordCredentials(basic.getUsername(), basic.getPassword());
         AuthScope authScope = new AuthScope(AuthScope.ANY);
         ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(authScope, creds);

         localContext = new BasicHttpContext();

         // Generate BASIC scheme object and stick it to the local execution context
         BasicScheme basicAuth = new BasicScheme();
         localContext.setAttribute("preemptive-auth", basicAuth);

         // Add as the first request interceptor
         ((DefaultHttpClient) client).addRequestInterceptor(new PreemptiveAuth(), 0);
         executor.setHttpContext(localContext);
      }
   }
}
项目:metron    文件:TaxiiHandler.java   
private static HttpClientContext createContext(URL endpoint, String username, String password, int port) {
  HttpClientContext context = null;
  HttpHost target = new HttpHost(endpoint.getHost(), port, endpoint.getProtocol());
  if (username != null && password != null) {

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
        new AuthScope(target.getHostName(), target.getPort()),
        new UsernamePasswordCredentials(username, password));

    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html
    AuthCache authCache = new BasicAuthCache();
    authCache.put(target, new BasicScheme());

    // Add AuthCache to the execution context
    context = HttpClientContext.create();
    context.setCredentialsProvider(credsProvider);
    context.setAuthCache(authCache);
  } else {
    context = null;
  }
  return context;
}
项目:contest-votesapp    文件:AuthHttpComponentsClientHttpRequestFactory.java   
@Override
protected HttpContext createHttpContext(final HttpMethod httpMethod, final URI uri) {
    // Create AuthCache instance
    final AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local auth cache
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);

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

    if (userName != null) {
        final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials(userName, password));
        localcontext.setCredentialsProvider(credsProvider);
    }
    return localcontext;
}
项目:hql-builder    文件:HqlWebServiceClientFactory.java   
@SuppressWarnings("deprecation")
protected org.jboss.resteasy.client.ClientExecutor setupClientExecutor() {
    AuthCache authCache = new BasicAuthCache();
    AuthScheme basicAuth = new BasicScheme();
    authCache.put(new HttpHost(getServiceUrl()), basicAuth);

    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(URI.create(getServiceUrl()).getHost(), authCache);

    // BasicCredentialsProvider credentialsProvider = new
    // BasicCredentialsProvider();
    // Credentials credentials = new
    // UsernamePasswordCredentials("hqlbuilder", "hqlbuilder");
    // credentialsProvider.setCredentials(new
    // AuthScope(URI.create(getServiceUrl()).getHost(),
    // URI.create(getServiceUrl()).getPort()),
    // credentials);

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

    return new ApacheHttpClient4Executor(httpClient, localContext);
}