Java Code Examples for org.apache.http.client.CredentialsProvider

The following are top voted examples for showing how to use org.apache.http.client.CredentialsProvider. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ticketing-service-paqx-parent-sample   File: TicketingIntegrationService.java   View source code 8 votes vote down vote up
private void delete(String url) throws IOException, HttpException {
	CredentialsProvider credentials = credentialsProvider();
	CloseableHttpClient httpclient = HttpClients.custom()
               .setDefaultCredentialsProvider(credentials)
               .build();

	try {
		HttpDelete httpDelete = new HttpDelete(url);
 		httpDelete.setHeader("Accept", "application/json");
	        
	    System.out.println("Executing request " + httpDelete.getRequestLine());
	    CloseableHttpResponse response = httpclient.execute(httpDelete);
	    try {
	        LOG.debug("----------------------------------------");
	        LOG.debug((String)response.getStatusLine().getReasonPhrase());
	    } finally {
	        response.close();
	    }
	} finally {
	    httpclient.close();
	}
}
 
Example 2
Project: Reer   File: HttpClientConfigurer.java   View source code 7 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

            if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
                return;
            }

            // If no authState has been established and this is a PUT or POST request, add preemptive authorisation
            String requestMethod = request.getRequestLine().getMethod();
            if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
                CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
                Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (credentials == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.update(authScheme, credentials);
            }
        }
 
Example 3
Project: PeSanKita-android   File: LegacyMmsConnection.java   View source code 7 votes vote down vote up
protected CloseableHttpClient constructHttpClient() throws IOException {
  RequestConfig config = RequestConfig.custom()
                                      .setConnectTimeout(20 * 1000)
                                      .setConnectionRequestTimeout(20 * 1000)
                                      .setSocketTimeout(20 * 1000)
                                      .setMaxRedirects(20)
                                      .build();

  URL                 mmsc          = new URL(apn.getMmsc());
  CredentialsProvider credsProvider = new BasicCredentialsProvider();

  if (apn.hasAuthentication()) {
    credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                                 new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
  }

  return HttpClients.custom()
                    .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
                    .setRedirectStrategy(new LaxRedirectStrategy())
                    .setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT))
                    .setConnectionManager(new BasicHttpClientConnectionManager())
                    .setDefaultRequestConfig(config)
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
}
 
Example 4
Project: dhus-core   File: ODataProductSynchronizer.java   View source code 7 votes vote down vote up
@Override
public CloseableHttpAsyncClient generateClient ()
{
   CredentialsProvider credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(new AuthScope (AuthScope.ANY),
           new UsernamePasswordCredentials(serviceUser, servicePass));
   RequestConfig rqconf = RequestConfig.custom()
         .setCookieSpec(CookieSpecs.DEFAULT)
         .setSocketTimeout(Timeouts.SOCKET_TIMEOUT)
         .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT)
         .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT)
         .build();
   CloseableHttpAsyncClient res = HttpAsyncClients.custom ()
         .setDefaultCredentialsProvider (credsProvider)
         .setDefaultRequestConfig(rqconf)
         .build ();
   res.start ();
   return res;
}
 
Example 5
Project: 0686OS   File: JiraUtils.java   View source code 7 votes vote down vote up
public static void handleError(String url, String login, String password, Scenario scenario) throws Exception {
	String issueId = "";
	for(String tag : scenario.getSourceTagNames()) {
		if (tag.contains("SAM-")) {
			issueId = tag.substring(1);
			break;
		}
	}
	if (issueId.equals("")) {
		return;
	}
	CredentialsProvider provider = new BasicCredentialsProvider();
	UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(login, password);
	provider.setCredentials(AuthScope.ANY, credentials);
	HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
       URI uri = UriBuilder.fromUri(url)
               .path("/rest/api/2/issue/" + issueId).build();
       
       String status = "Passed";
       if (scenario != null && scenario.isFailed()) {
       	status = "Failed";
       }
       HttpPut request = new HttpPut(uri);
       HttpEntity entity = new StringEntity("{\"fields\":{\"customfield_10007\": \"" + status + "\"}}");
       request.setEntity(entity);
       request.addHeader("Content-Type", "application/json");
	HttpResponse response = client.execute(request);
	client.getConnectionManager().shutdown();
}
 
Example 6
Project: Reer   File: HttpClientConfigurer.java   View source code 6 votes vote down vote up
private void configureCredentials(HttpClientBuilder builder, CredentialsProvider credentialsProvider, Collection<Authentication> authentications) {
    if(authentications.size() > 0) {
        useCredentials(credentialsProvider, AuthScope.ANY_HOST, AuthScope.ANY_PORT, authentications);

        // Use preemptive authorisation if no other authorisation has been established
        builder.addInterceptorFirst(new PreemptiveAuth(new BasicScheme(), isPreemptiveEnabled(authentications)));
    }
}
 
Example 7
Project: Reer   File: HttpClientConfigurer.java   View source code 6 votes vote down vote up
private void useCredentials(CredentialsProvider credentialsProvider, String host, int port, Collection<? extends Authentication> authentications) {
    Credentials httpCredentials;

    for (Authentication authentication : authentications) {
        String scheme = getAuthScheme(authentication);
        PasswordCredentials credentials = getPasswordCredentials(authentication);

        if (authentication instanceof AllSchemesAuthentication) {
            NTLMCredentials ntlmCredentials = new NTLMCredentials(credentials);
            httpCredentials = new NTCredentials(ntlmCredentials.getUsername(), ntlmCredentials.getPassword(), ntlmCredentials.getWorkstation(), ntlmCredentials.getDomain());
            credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, AuthSchemes.NTLM), httpCredentials);

            LOGGER.debug("Using {} and {} for authenticating against '{}:{}' using {}", credentials, ntlmCredentials, host, port, AuthSchemes.NTLM);
        }

        httpCredentials = new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword());
        credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, scheme), httpCredentials);
        LOGGER.debug("Using {} for authenticating against '{}:{}' using {}", credentials, host, port, scheme);
    }
}
 
Example 8
Project: SensorThingsProcessor   File: AuthBasic.java   View source code 6 votes vote down vote up
@Override
public void setAuth(SensorThingsService service) {
    try {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        URL url = service.getEndpoint().toURL();
        credsProvider.setCredentials(
                new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(editorUsername.getValue(), editorPassword.getValue()));
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build();
        service.setClient(httpclient);
    } catch (MalformedURLException ex) {
        LOGGER.error("Failed to initialise basic auth.", ex);
    }
}
 
Example 9
Project: dhus-core   File: ODataClient.java   View source code 6 votes vote down vote up
@Override
public CloseableHttpAsyncClient generateClient ()
{
   CredentialsProvider credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(new AuthScope (AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
   RequestConfig rqconf = RequestConfig.custom()
         .setCookieSpec(CookieSpecs.DEFAULT)
         .setSocketTimeout(Timeouts.SOCKET_TIMEOUT)
         .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT)
         .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT)
         .build();
   CloseableHttpAsyncClient res = HttpAsyncClients.custom ()
         .setDefaultCredentialsProvider (credsProvider)
         .setDefaultRequestConfig(rqconf)
         .build ();
   res.start ();
   return res;
}
 
Example 10
Project: ticketing-service-paqx-parent-sample   File: TicketingIntegrationService.java   View source code 6 votes vote down vote up
private Map put(String url, String data) throws IOException, HttpException {
	Map<String,Object> map = null;
	CredentialsProvider credentials = credentialsProvider();
	CloseableHttpClient httpclient = HttpClients.custom()
               .setDefaultCredentialsProvider(credentials)
               .build();

	try {
		HttpPut httpPut = new HttpPut(url);
 		httpPut.setHeader("Accept", "application/json");
 		httpPut.setHeader("Content-Type", "application/json");
        HttpEntity entity = new ByteArrayEntity(data.getBytes("utf-8"));
 		httpPut.setEntity(entity);
	        
	    System.out.println("Executing request " + httpPut.getRequestLine());
	    CloseableHttpResponse response = httpclient.execute(httpPut);
	    try {
	        LOG.debug("----------------------------------------");
	        LOG.debug((String)response.getStatusLine().getReasonPhrase());
	        String responseBody = EntityUtils.toString(response.getEntity());
	        LOG.debug(responseBody);
	        Gson gson = new Gson();
	        map = new HashMap<String,Object>();
			map = (Map<String,Object>) gson.fromJson(responseBody, map.getClass());
	        LOG.debug(responseBody);
	    } finally {
	        response.close();
	    }
	} finally {
	    httpclient.close();
	}

	return map;
}
 
Example 11
Project: es-log4j2-appender   File: ElasticBulkSender.java   View source code 6 votes vote down vote up
public ElasticBulkSender(String user, String password, HttpHost... hosts) {
	this.user = user;
	this.password = password;
	this.hosts = hosts;
	this.restClient = RestClient.builder(hosts)
			.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
				@Override
				public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
					if (!Strings.isBlank(user)) {
						CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
						credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
		                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
					} else {
						return httpClientBuilder;
					}
				}
	        })
			.build();
}
 
Example 12
Project: SensorThingsManager   File: AuthBasic.java   View source code 6 votes vote down vote up
@Override
public void setAuth(SensorThingsService service) {
    try {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        URL url = service.getEndpoint().toURL();
        credsProvider.setCredentials(
                new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(editorUsername.getValue(), editorPassword.getValue()));
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(credsProvider)
                .build();
        service.setClient(httpclient);
    } catch (MalformedURLException ex) {
        LOGGER.error("Failed to initialise basic auth.", ex);
    }
}
 
Example 13
Project: lams   File: RequestAuthCache.java   View source code 6 votes vote down vote up
private void doPreemptiveAuth(
        final HttpHost host,
        final AuthScheme authScheme,
        final AuthState authState,
        final CredentialsProvider credsProvider) {
    String schemeName = authScheme.getSchemeName();
    if (this.log.isDebugEnabled()) {
        this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
    }

    AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName);
    Credentials creds = credsProvider.getCredentials(authScope);

    if (creds != null) {
        authState.setState(AuthProtocolState.SUCCESS);
        authState.update(authScheme, creds);
    } else {
        this.log.debug("No credentials for preemptive authentication");
    }
}
 
Example 14
Project: teamcity-msteams-notifier   File: MsTeamsNotificationImpl.java   View source code 6 votes vote down vote up
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) {
      this.proxyHost = proxyHost;
      this.proxyPort = proxyPort;
      
if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) {
          HttpClientBuilder clientBuilder = HttpClients.custom()
              .useSystemProperties()
              .setProxy(new HttpHost(proxyHost, proxyPort, "http"));
              
          if (credentials != null) {
              CredentialsProvider credsProvider = new BasicCredentialsProvider();
              credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials);
              clientBuilder.setDefaultCredentialsProvider(credsProvider);
              Loggers.SERVER.debug("MsTeamsNotification ::using proxy credentials " + credentials.getUserPrincipal().getName());
          }
          
          this.client = clientBuilder.build();
}
  }
 
Example 15
Project: boohee_v5.6   File: AsyncHttpClient$3.java   View source code 6 votes vote down vote up
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);
        }
    }
}
 
Example 16
Project: Cognizant-Intelligent-Test-Scripter   File: RemoteProxy.java   View source code 6 votes vote down vote up
public static HttpCommandExecutor getProxyExecutor(URL url, Properties prop) {

        prop = decrypt(prop);

        String proxyHost = prop.getProperty("proxyHost");
        int proxyPort = Integer.valueOf(prop.getProperty("proxyPort"));
        String proxyUserDomain = prop.getProperty("proxyUserDomain");
        String proxyUser = prop.getProperty("proxyUser");
        String proxyPassword = prop.getProperty("proxyPassword");

        HttpClientBuilder builder = HttpClientBuilder.create();
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                new NTCredentials(proxyUser, proxyPassword, getWorkstation(), proxyUserDomain));
        if (url.getUserInfo() != null && !url.getUserInfo().isEmpty()) {
            credsProvider.setCredentials(new AuthScope(url.getHost(), (url.getPort() > 0 ? url.getPort() : url.getDefaultPort())),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
        builder.setProxy(proxy);
        builder.setDefaultCredentialsProvider(credsProvider);
        HttpClient.Factory factory = new SimpleHttpClientFactory(builder);
        return new HttpCommandExecutor(new HashMap<String, CommandInfo>(), url, factory);

    }
 
Example 17
Project: aws-sdk-java-v2   File: ApacheUtils.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 18
Project: Cable-Android   File: LegacyMmsConnection.java   View source code 6 votes vote down vote up
protected CloseableHttpClient constructHttpClient() throws IOException {
  RequestConfig config = RequestConfig.custom()
                                      .setConnectTimeout(20 * 1000)
                                      .setConnectionRequestTimeout(20 * 1000)
                                      .setSocketTimeout(20 * 1000)
                                      .setMaxRedirects(20)
                                      .build();

  URL                 mmsc          = new URL(apn.getMmsc());
  CredentialsProvider credsProvider = new BasicCredentialsProvider();

  if (apn.hasAuthentication()) {
    credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                                 new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
  }

  return HttpClients.custom()
                    .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
                    .setRedirectStrategy(new LaxRedirectStrategy())
                    .setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT))
                    .setConnectionManager(new BasicHttpClientConnectionManager())
                    .setDefaultRequestConfig(config)
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
}
 
Example 19
Project: ibm-cos-sdk-java   File: ApacheUtils.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 20
Project: elasticsearch-full   File: XPackBaseDemo.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    /**
     * 如果es集群安装了x-pack插件则以此种方式连接集群
     * 1. java客户端的方式是以tcp协议在9300端口上进行通信
     * 2. http客户端的方式是以http协议在9200端口上进行通信
     */
    Settings settings = Settings.builder(). put("xpack.security.user", "elastic:changeme").build();
    client = new PreBuiltXPackTransportClient(settings)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
    elasticsearchTemplate = new ElasticsearchTemplate(client);
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("elastic", "changeme"));
    restClient = RestClient.builder(new HttpHost("localhost",9200,"http"))
            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                @Override
                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                }
            }).build();
}
 
Example 21
Project: geoportal-server-harvester   File: HttpClientContextBuilder.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 22
Project: yunpian-java-sdk   File: AsyncClientAuthentication.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 443),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    try {
        HttpGet httpget = new HttpGet("http://localhost/");

        System.out.println("Executing request " + httpget.getRequestLine());
        Future<HttpResponse> future = httpclient.execute(httpget, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}
 
Example 23
Project: Brutusin-RPC   File: HttpEndpoint.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        HttpClientContextFactory ctxFact = new HttpClientContextFactory() {
            public HttpClientContext create() {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(
                        new AuthScope("localhost", 8080, AuthScope.ANY_REALM, "basic"),
                        new UsernamePasswordCredentials("user", "password"));
                HttpClientContext context = HttpClientContext.create();
                context.setCredentialsProvider(credsProvider);
                return context;
            }
        };

        HttpEndpoint endpoint = new HttpEndpoint(new URI("http://localhost:8080/rpc/http"), ctxFact);

        HttpResponse resp = endpoint.exec("rpc.http.version", null, null);
        if (resp.isIsBinary()) {
            System.out.println("binary");
            System.out.println(resp.getInputStream().getName());
        } else {
            System.out.println(resp.getRpcResponse().getResult());
        }
    }
 
Example 24
Project: Peking-University-Open-Research-Data-Platform   File: DataCiteRESTfullClient.java   View source code 6 votes vote down vote up
public DataCiteRESTfullClient(String url, String username, String password) {
    this.url = url;
    try {
        context = HttpClientContext.create();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1),
                new UsernamePasswordCredentials(username, password));
        context.setCredentialsProvider(credsProvider);
        
        httpClient = HttpClients.createDefault();
    } catch (Exception ioe) {
        close();
        logger.log(Level.SEVERE,"Fail to init Client",ioe);
        throw new RuntimeException("Fail to init Client", ioe);
    }
}
 
Example 25
Project: axon-eventstore   File: ESHttpEventStore.java   View source code 6 votes vote down vote up
public ESHttpEventStore(final String identifier, final ThreadFactory threadFactory, final URL url, final CredentialsProvider credentialsProvider, final int longPollSec, final int connectTimeout,
      final int connectionRequestTimeout, final int socketTimeout) {
   super();
   this.identifier = identifier;
   this.threadFactory = threadFactory;
   this.url = url;
   this.credentialsProvider = credentialsProvider;
   this.longPollSec = longPollSec;
   this.connectTimeout = connectTimeout;
   this.connectionRequestTimeout = connectionRequestTimeout;
   this.socketTimeout = socketTimeout;
   this.open = false;
   this.hostAndPort = url.getHost() + ":" + url.getPort();
   this.host = url.getHost();
   atomFeedReader = new AtomFeedJsonReader();
}
 
Example 26
Project: BitcoindConnector4J   File: BitcoindApiHandler.java   View source code 6 votes vote down vote up
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);
}
 
Example 27
Project: beyondj   File: HttpSender.java   View source code 6 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    
    // If no auth scheme avaialble yet, try to initialize it preemptively
    if (authState.getAuthScheme() == null) {
        AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (authScheme != null) {
            Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
            if (creds == null) {
                throw new HttpException("No credentials for preemptive authentication");
            }
            authState.setAuthScheme(authScheme);
            authState.setCredentials(creds);
        }
    }
    
}
 
Example 28
Project: infiniboard   File: UrlSourceJob.java   View source code 6 votes vote down vote up
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;
}
 
Example 29
Project: alexa-meets-polly   File: Mp3Converter.java   View source code 6 votes vote down vote up
public static String convertMp3(final String mp3Path) throws URISyntaxException, IOException {
    // get credentials for webservice from application config
    final String apiKey = SkillConfig.getTranslatorConvertServiceUser();
    final String apiPass = SkillConfig.getTranslatorConvertServicePass();
    // build uri
    final String bucketName = SkillConfig.getS3BucketName();
    final URIBuilder uri = new URIBuilder(SkillConfig.getTranslatorConvertServiceUrl()).addParameter("bucket", bucketName).addParameter("path", mp3Path);
    // set up web request
    final HttpGet httpGet = new HttpGet(uri.build());
    httpGet.setHeader("Content-Type", "text/plain");
    // set up credentials
    final CredentialsProvider provider = new BasicCredentialsProvider();
    final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(apiKey, apiPass);
    provider.setCredentials(AuthScope.ANY, credentials);
    // send request to convert webservice
    final HttpResponse response =
            HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build().execute(httpGet);

    //Validate.inclusiveBetween(200, 399, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
    // work on response
    final HttpEntity entity = response.getEntity();
    return IOUtils.toString(entity.getContent(), "UTF-8");
}
 
Example 30
Project: OHMS   File: HttpUtil.java   View source code 6 votes vote down vote up
/**
 * Returns HttpClient with basic auth.
 *
 * @param userName the user name
 * @param password the password
 * @return the http client with basic auth
 */
private static HttpClient getHttpClientWithBasicAuth( final String userName, final String password )
{
    // check that userName is not null
    if ( StringUtils.isBlank( userName ) )
    {
        logger.warn( "In getHttpClientWithBasicAuth, userName is either null or blank." );
        return null;
    }
    // check that password is not null
    if ( StringUtils.isBlank( password ) )
    {
        logger.warn( "In getHttpClientWithBasicAuth, password is either null or blank." );
        return null;
    }
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials( userName, password );
    credentialsProvider.setCredentials( AuthScope.ANY, usernamePasswordCredentials );
    return HttpClientBuilder.create().setDefaultCredentialsProvider( credentialsProvider ).build();
}
 
Example 31
Project: diadocsdk-java   File: DiadocPreemptiveAuthRequestInterceptor.java   View source code 6 votes vote down vote up
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    // If no auth scheme has been initialized yet
    if (authState.getAuthScheme() == null) {
        CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        // Obtain credentials matching the target host
        Credentials credentials = credentialsProvider.getCredentials(authScope);
        // If found, generate BasicScheme preemptively
        if (credentials != null) {
            authState.setAuthScheme(new DiadocAuthScheme());
            authState.setCredentials(credentials);
        }
    }
}
 
Example 32
Project: meituanwaimai-sdk   File: MtWmClientImpl.java   View source code 6 votes vote down vote up
public void setConfigStorage(MtWmConfigStorage configStorage) {

        this.configStorage = configStorage;

        String http_proxy_host = configStorage.getHttp_proxy_host();
        int http_proxy_port = configStorage.getHttp_proxy_port();
        String http_proxy_username = configStorage.getHttp_proxy_username();
        String http_proxy_password = configStorage.getHttp_proxy_password();

        final HttpClientBuilder builder = HttpClients.custom();
        if (StringUtils.isNotBlank(http_proxy_host)) {
            // 使用代理服务器
            if (StringUtils.isNotBlank(http_proxy_username)) {
                // 需要用户认证的代理服务器
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(
                        new AuthScope(http_proxy_host, http_proxy_port),
                        new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
                builder
                        .setDefaultCredentialsProvider(credsProvider);
            }
            httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
        }
        httpClient = builder.build();
    }
 
Example 33
Project: remote-files-sync   File: RequestAuthCache.java   View source code 6 votes vote down vote up
private void doPreemptiveAuth(
        final HttpHost host,
        final AuthScheme authScheme,
        final AuthStateHC4 authState,
        final CredentialsProvider credsProvider) {
    final String schemeName = authScheme.getSchemeName();
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Re-using cached '" + schemeName + "' auth scheme for " + host);
    }

    final AuthScope authScope = new AuthScope(host.getHostName(), host.getPort(), AuthScope.ANY_REALM, schemeName);
    final Credentials creds = credsProvider.getCredentials(authScope);

    if (creds != null) {
        if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) {
            authState.setState(AuthProtocolState.CHALLENGED);
        } else {
            authState.setState(AuthProtocolState.SUCCESS);
        }
        authState.update(authScheme, creds);
    } else {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "No credentials for preemptive authentication");
        }
    }
}
 
Example 34
Project: TextSecure   File: MmsConnection.java   View source code 6 votes vote down vote up
protected CloseableHttpClient constructHttpClient()
    throws IOException {
  RequestConfig config = RequestConfig.custom()
                                      .setConnectTimeout(20 * 1000)
                                      .setConnectionRequestTimeout(20 * 1000)
                                      .setSocketTimeout(20 * 1000)
                                      .setMaxRedirects(20)
                                      .build();

  URL mmsc = new URL(apn.getMmsc());
  CredentialsProvider credsProvider = new BasicCredentialsProvider();

  if (apn.hasAuthentication()) {
    credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()),
                                 new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
  }

  return HttpClients.custom()
                    .setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4())
                    .setRedirectStrategy(new LaxRedirectStrategy())
                    .setUserAgent("Android-Mms/2.0")
                    .setConnectionManager(new BasicHttpClientConnectionManager())
                    .setDefaultRequestConfig(config)
                    .setDefaultCredentialsProvider(credsProvider)
                    .build();
}
 
Example 35
Project: purecloud-iot   File: WinHttpClients.java   View source code 6 votes vote down vote up
private static HttpClientBuilder createBuilder() {
    if (isWinAuthAvailable()) {
        final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
                .register(AuthSchemes.BASIC, new BasicSchemeFactory())
                .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
                .register(AuthSchemes.NTLM, new WindowsNTLMSchemeFactory(null))
                .register(AuthSchemes.SPNEGO, new WindowsNegotiateSchemeFactory(null))
                .build();
        final CredentialsProvider credsProvider = new WindowsCredentialsProvider(new SystemDefaultCredentialsProvider());
        return HttpClientBuilder.create()
                .setDefaultCredentialsProvider(credsProvider)
                .setDefaultAuthSchemeRegistry(authSchemeRegistry);
    } else {
        return HttpClientBuilder.create();
    }
}
 
Example 36
Project: binjr   File: HttpClientKerberosDoAS.java   View source code 6 votes vote down vote up
private HttpClient getHttpClient() {

        Credentials use_jaas_creds = new Credentials() {
            public String getPassword() {
                return null;
            }

            public Principal getUserPrincipal() {
                return null;
            }
        };

        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds);
        Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
        CloseableHttpClient httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credsProvider).build();

        return httpclient;
    }
 
Example 37
Project: api-snippets   File: lookup-get-addon-payfone-1.6.x.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope("lookups.twilio.com", 80),
            new UsernamePasswordCredentials("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "your_auth_token"));
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credsProvider)
            .build();
    try {
        HttpGet httpget = new HttpGet("https://lookups.twilio.com/v1/PhoneNumbers/+16502530000/?AddOns=payfone_tcpa_compliance&AddOns.payfone_tcpa_compliance.RightPartyContactedDate=20160101");

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}
 
Example 38
Project: rundeck-device42-nodes-plugin   File: AbstractAsynchronousRestClient.java   View source code 6 votes vote down vote up
/**
 * Create the HTTP clean with basic authentication mechanism using specified
 * credentials
 * 
 * @param username
 *            Authentication username
 * @param password
 *            Authentication password
 * @return
 */
protected static CloseableHttpClient createHttpClient(String username, String password) {
	SSLContext sslContext = createSslContext();
	HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
	SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);

	CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
	credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

	Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
	List<Header> headers = Arrays.asList(header);

	return HttpClients.custom()
			.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
			.setSSLSocketFactory(sslSocketFactory)
			.setDefaultCredentialsProvider(credentialsProvider)
			.setDefaultHeaders(headers)
			.build();
}
 
Example 39
Project: crauler_ISI   File: GenericRestClientAuth.java   View source code 6 votes vote down vote up
public static void getConnection(String username, String password, String API, int port, String method, String CollObject) throws ClientProtocolException, IOException {
	HttpHost targetHost = new HttpHost(API, port, "https");
	CredentialsProvider provider = new BasicCredentialsProvider();
	provider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
			new UsernamePasswordCredentials(username, password));

	CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();

	// create a GET method that queries some API operation
	HttpGet request = new HttpGet(method);

	try {
		// execute the operation
		HttpResponse response = client.execute(targetHost, request);

		// print the status and the contents of the response
		System.out.println(response.getStatusLine());

		JSONObject jsonObj = new JSONObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
		JSONArray array = jsonObj.getJSONArray(CollObject);

	} finally {
		// release any connection resources used by the method
		client.close();
	}
}
 
Example 40
Project: pay-java-parent   File: HttpRequestTemplate.java   View source code 6 votes vote down vote up
/**
 * 创建代理服务器
 * @param configStorage 请求配置
 * @return 代理服务器配置
 */
public CredentialsProvider createProxy(HttpConfigStorage configStorage){

    if (StringUtils.isBlank(configStorage.getHttpProxyHost())) {
        return null;
    }
    //http代理地址设置
    httpProxy = new HttpHost(configStorage.getHttpProxyHost(), configStorage.getHttpProxyPort());

    if (StringUtils.isNotBlank(configStorage.getHttpProxyHost())) {
        return null;
    }

    // 需要用户认证的代理服务器
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
            new AuthScope(configStorage.getHttpProxyHost(), configStorage.getHttpProxyPort()),
            new UsernamePasswordCredentials(configStorage.getHttpProxyUsername(), configStorage.getHttpProxyPassword()));


    return credsProvider;
}