@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; }
public MyPageProcessor(SpiderInfo info, Task task) { this.site = Site.me().setDomain(info.getDomain()).setTimeOut(info.getTimeout()) .setRetryTimes(info.getRetry()).setSleepTime(info.getSleep()) .setCharset(StringUtils.isBlank(info.getCharset()) ? null : info.getCharset()) .setUserAgent(info.getUserAgent()); //设置抓取代理IP与接口 if (StringUtils.isNotBlank(info.getProxyHost()) && info.getProxyPort() > 0) { this.site.setHttpProxy(new HttpHost(info.getProxyHost(), info.getProxyPort())); //设置代理的认证 if (StringUtils.isNotBlank(info.getProxyUsername()) && StringUtils.isNotBlank(info.getProxyPassword())) { this.site.setUsernamePasswordCredentials(new UsernamePasswordCredentials(info.getProxyUsername(), info.getProxyPassword())); } } this.info = info; this.task = task; }
public void afterPropertiesSet() throws UnsupportedEncodingException { Collection<Header> defaultHeaders = new ArrayList<Header>(); Header header = new BasicHeader("Authorization", "Basic " + BaseEncoding.base64().encode("apollo:".getBytes("UTF-8"))); defaultHeaders.add(header); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("apollo", "")); CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider) .setDefaultHeaders(defaultHeaders).build(); restTemplate = new RestTemplate(httpMessageConverters.getConverters()); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); requestFactory.setConnectTimeout(portalConfig.connectTimeout()); requestFactory.setReadTimeout(portalConfig.readTimeout()); restTemplate.setRequestFactory(requestFactory); }
protected HttpContext createHttpContext(HttpProxy httpProxy, CookieStore cookieStore) { HttpContext httpContext = new HttpClientContext(); if (cookieStore != null) { httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); } if (httpProxy != null && StringUtils.isNotBlank(httpProxy.getUsername())) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(httpProxy.getHost(), httpProxy.getPort()), new UsernamePasswordCredentials(httpProxy.getUsername(), httpProxy.getPassword())); httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider); } return httpContext; }
@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); } }
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(); } }
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(); }
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; }
@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; }
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; } }
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(); }
public static void deleteRESTUser(String usrName){ try{ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); HttpDelete delete = new HttpDelete("http://"+host+":8002/manage/v2/users/"+usrName); HttpResponse response = client.execute(delete); if(response.getStatusLine().getStatusCode()== 202){ Thread.sleep(3500); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public static void deleteUserRole(String roleName){ try{ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); HttpDelete delete = new HttpDelete("http://"+host+":8002/manage/v2/roles/"+roleName); HttpResponse response = client.execute(delete); if(response.getStatusLine().getStatusCode()== 202){ Thread.sleep(3500); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public static void deleteRESTServerWithDB(String restServerName) { try{ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); HttpDelete delete = new HttpDelete("http://"+host+":8002/v1/rest-apis/"+restServerName+"?include=content&include=modules"); HttpResponse response = client.execute(delete); if(response.getStatusLine().getStatusCode()== 202){ Thread.sleep(9500); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public static void deleteRESTServer(String restServerName) { try{ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); HttpDelete delete = new HttpDelete("http://"+host+":8002/v1/rest-apis/"+restServerName+"&include=modules"); HttpResponse response = client.execute(delete); if(response.getStatusLine().getStatusCode()== 202){ Thread.sleep(3500); waitForServerRestart(); } else System.out.println("Server response "+response.getStatusLine().getStatusCode()); }catch (Exception e) { // writing error to Log System.out.println("Inside Deleting Rest server is throwing an error"); e.printStackTrace(); } }
public static void loadBug18993(){ try{ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8011), new UsernamePasswordCredentials("admin", "admin")); String document ="<foo>a space b</foo>"; String perm = "perm:rest-writer=read&perm:rest-writer=insert&perm:rest-writer=update&perm:rest-writer=execute"; HttpPut put = new HttpPut("http://"+host+":8011/v1/documents?uri=/a%20b&"+perm); put.addHeader("Content-type", "application/xml"); put.setEntity(new StringEntity(document)); HttpResponse response = client.execute(put); HttpEntity respEntity = response.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public static void setAuthentication(String level,String restServerName) throws ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); String body = "{\"authentication\": \""+level+"\"}"; HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(body)); HttpResponse response2 = client.execute(put); HttpEntity respEntity = response2.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }
public static void setDefaultUser(String usr,String restServerName) throws ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); String body = "{\"default-user\": \""+usr+"\"}"; HttpPut put = new HttpPut("http://"+host+":8002/manage/v2/servers/"+restServerName+"/properties?server-type=http&group-id=Default"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(body)); HttpResponse response2 = client.execute(put); HttpEntity respEntity = response2.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }
public static void setPathRangeIndexInDatabase(String dbName, JsonNode jnode) throws IOException { try { DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials( new AuthScope(host, 8002), new UsernamePasswordCredentials("admin", "admin")); HttpPut put = new HttpPut("http://"+host+":8002"+ "/manage/v2/databases/"+dbName+"/properties?format=json"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(jnode.toString())); HttpResponse response = client.execute(put); HttpEntity respEntity = response.getEntity(); if(respEntity != null){ String content = EntityUtils.toString(respEntity); System.out.println(content); } }catch (Exception e) { // writing error to Log e.printStackTrace(); } }
public void builder(String twoFact){ instagram = Instagram4j.builder().username(username).password(password).build(); instagram.setup(); if(sneakUsername.equals("")){ sneakUsername = username; } if (proxyEnabled){ HttpHost proxy = new HttpHost(serverIp, portNumber, "http"); instagram.getClient().getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); instagram.getClient().getParams().setIntParameter("http.connection.timeout", 600000); instagram.getClient().getCredentialsProvider().setCredentials( new AuthScope(serverIp, portNumber), new UsernamePasswordCredentials(netUser, netPass)); } try { if(!twoFact.equals("")) instagram.login(twoFact); else{instagram.login();} refreshResult(); } catch (IOException e) { e.printStackTrace(); } }
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); }
@Override public void setUsernamePassword(AuthenticationType authType, String username, String password) { this.credentials = new UsernamePasswordCredentials( Objects.requireNonNull(username), Objects.requireNonNull(password)); this.credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create(); switch (authType) { case BASIC: authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); break; case DIGEST: authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; default: throw new IllegalArgumentException("Unsupported authentiation type: " + authType); } this.authRegistry = authRegistryBuilder.build(); }
@Override protected HttpHost determineProxy(HttpHost host, HttpRequest request, HttpContext context) throws HttpException { HttpClientContext httpClientContext = HttpClientContext.adapt(context); Proxy proxy = proxyPlanner.determineProxy(host, request, context, ipPool, crawlerSession); if (proxy == null) { return null; } if (log.isDebugEnabled()) { log.debug("{} 当前使用IP为:{}:{}", host.getHostName(), proxy.getIp(), proxy.getPort()); } context.setAttribute(VSCRAWLER_AVPROXY_KEY, proxy); if (proxy.getAuthenticationHeaders() != null) { for (Header header : proxy.getAuthenticationHeaders()) { request.addHeader(header); } } if (StringUtils.isNotEmpty(proxy.getUsername()) && StringUtils.isNotEmpty(proxy.getPassword())) { BasicCredentialsProvider credsProvider1 = new BasicCredentialsProvider(); httpClientContext.setCredentialsProvider(credsProvider1); credsProvider1.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword())); } return new HttpHost(proxy.getIp(), proxy.getPort()); }
@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(); }
public HttpClientConfigurer basicAuthCredentials(String username, String password) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); useBasicAuth = true; return this; }
@PostConstruct public void init() { objectMapper = new ObjectMapper(); final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); if (StringUtils.hasText(camundaUser)) { final BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(camundaUser, camundaPass)); clientBuilder.setDefaultCredentialsProvider(provider); } httpClient = clientBuilder.build(); }
/** * Resolve metadata dynamically. * * @param service the service * @param metadataResolvers the metadata resolvers * @throws Exception the exception */ protected void resolveMetadataDynamically(final SamlRegisteredService service, final List<MetadataResolver> metadataResolvers) throws Exception { LOGGER.info("Loading metadata dynamically for [{}]", service.getName()); final SamlIdPProperties.Metadata md = casProperties.getAuthn().getSamlIdp().getMetadata(); final FunctionDrivenDynamicHTTPMetadataResolver resolver = new FunctionDrivenDynamicHTTPMetadataResolver(this.httpClient.getWrappedHttpClient()); resolver.setMinCacheDuration(TimeUnit.MILLISECONDS.convert(md.getCacheExpirationMinutes(), TimeUnit.MINUTES)); resolver.setRequireValidMetadata(md.isRequireValidMetadata()); if (StringUtils.isNotBlank(md.getBasicAuthnPassword()) && StringUtils.isNotBlank(md.getBasicAuthnUsername())) { resolver.setBasicCredentials(new UsernamePasswordCredentials(md.getBasicAuthnUsername(), md.getBasicAuthnPassword())); } if (!md.getSupportedContentTypes().isEmpty()) { resolver.setSupportedContentTypes(md.getSupportedContentTypes()); } resolver.setRequestURLBuilder(new Function<String, String>() { @Nullable @Override public String apply(@Nullable final String input) { try { if (StringUtils.isNotBlank(input)) { final String metadataLocation = service.getMetadataLocation().replace("{0}", EncodingUtils.urlEncode(input)); LOGGER.info("Constructed dynamic metadata query [{}] for [{}]", metadataLocation, service.getName()); return metadataLocation; } return null; } catch (final Exception e) { throw new RuntimeException(e.getMessage(), e); } } }); buildSingleMetadataResolver(resolver, service); metadataResolvers.add(resolver); }
private CredentialsProvider getCredentialsProvider() { CredentialsProvider creds = new BasicCredentialsProvider(); creds.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( model.userNameProperty().get(), model.passwordProperty().get() )); return creds; }
/** * Sets basic authentication on web request using plain credentials * @param username The plain text username * @param password The plain text password */ public void setBasicAuthentication(String username, String password) { ((DefaultHttpClient) client).getCredentialsProvider().setCredentials( new AuthScope(postMethod.getURI().getHost(), postMethod.getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password)); }
public MarkLogicWriter(final Map<String, String> config){ connectionUrl = config.get(MarkLogicSinkConfig.CONNECTION_URL); user = config.get(MarkLogicSinkConfig.CONNECTION_USER); password = config.get(MarkLogicSinkConfig.CONNECTION_PASSWORD); requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5 * 1000).build(); localContext = HttpClientContext.create(); httpClient = HttpClientBuilder.create().build(); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); localContext.setCredentialsProvider(credentialsProvider); localContext.setRequestConfig(requestConfig); }
protected HttpResponse get(String url) throws ClientProtocolException, IOException, URISyntaxException { final CloseableHttpClient httpClient = HttpClients.createDefault(); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin")); final HttpClientContext localContext = HttpClientContext.create(); localContext.setCredentialsProvider(credentialsProvider); return httpClient.execute(createGet(url), localContext); }
protected HttpResponse delete(String url) throws ClientProtocolException, IOException, URISyntaxException{ final CloseableHttpClient httpClient = HttpClients.createDefault(); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin")); final HttpClientContext localContext = HttpClientContext.create(); localContext.setCredentialsProvider(credentialsProvider); return httpClient.execute(createDelete(url), localContext); }
public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) { HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); if (trustSelfSignedCerts) { httpClientBuilder.setSslcontext(buildSslContext()); httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); } if (httpProxyConfiguration != null) { HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()); httpClientBuilder.setProxy(proxy); if (httpProxyConfiguration.isAuthRequired()) { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials( new AuthScope(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()), new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(), httpProxyConfiguration .getPassword())); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); httpClientBuilder.setRoutePlanner(routePlanner); } HttpClient httpClient = httpClientBuilder.build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); return requestFactory; }
/** * Build the {@link RestClient} used for reindexing from remote clusters. * @param remoteInfo connection information for the remote cluster * @param taskId the id of the current task. This is added to the thread name for easier tracking * @param threadCollector a list in which we collect all the threads created by the client */ static RestClient buildRestClient(RemoteInfo remoteInfo, long taskId, List<Thread> threadCollector) { Header[] clientHeaders = new Header[remoteInfo.getHeaders().size()]; int i = 0; for (Map.Entry<String, String> header : remoteInfo.getHeaders().entrySet()) { clientHeaders[i] = new BasicHeader(header.getKey(), header.getValue()); } return RestClient.builder(new HttpHost(remoteInfo.getHost(), remoteInfo.getPort(), remoteInfo.getScheme())) .setDefaultHeaders(clientHeaders) .setRequestConfigCallback(c -> { c.setConnectTimeout(Math.toIntExact(remoteInfo.getConnectTimeout().millis())); c.setSocketTimeout(Math.toIntExact(remoteInfo.getSocketTimeout().millis())); return c; }) .setHttpClientConfigCallback(c -> { // Enable basic auth if it is configured if (remoteInfo.getUsername() != null) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(remoteInfo.getUsername(), remoteInfo.getPassword()); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, creds); c.setDefaultCredentialsProvider(credentialsProvider); } // Stick the task id in the thread name so we can track down tasks from stack traces AtomicInteger threads = new AtomicInteger(); c.setThreadFactory(r -> { String name = "es-client-" + taskId + "-" + threads.getAndIncrement(); Thread t = new Thread(r, name); threadCollector.add(t); return t; }); // Limit ourselves to one reactor thread because for now the search process is single threaded. c.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build()); return c; }).build(); }
private static RestClient createRestClient(final boolean useAuth, final boolean usePreemptiveAuth) { // provide the username/password for every request final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "pass")); final RestClientBuilder restClientBuilder = RestClient.builder( new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort())).setDefaultHeaders(defaultHeaders); if (pathPrefix.length() > 0) { // sometimes cut off the leading slash restClientBuilder.setPathPrefix(randomBoolean() ? pathPrefix.substring(1) : pathPrefix); } if (useAuth) { restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() { @Override public HttpAsyncClientBuilder customizeHttpClient(final HttpAsyncClientBuilder httpClientBuilder) { if (usePreemptiveAuth == false) { // disable preemptive auth by ignoring any authcache httpClientBuilder.disableAuthCaching(); } return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } }); } return restClientBuilder.build(); }
private RestTemplate getRestTemplate ( long maxConnectionInMs, JsonNode user, JsonNode pass, String desc ) { logger.debug( "maxConnectionInMs: {} , user: {} , Pass: {} ", maxConnectionInMs, user, pass ); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); // "user" : "$csapUser1", "pass" : "$csapPass1" if ( user != null && pass != null ) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope( null, -1 ), new UsernamePasswordCredentials( user.asText(), csapApplication.decode( pass.asText(), desc ) ) ); HttpClient httpClient = HttpClients .custom() .setDefaultCredentialsProvider( credsProvider ) .build(); factory.setHttpClient( httpClient ); // factory = new HttpComponentsClientHttpRequestFactory(httpClient); } factory.setConnectTimeout( (int) maxConnectionInMs ); factory.setReadTimeout( (int) maxConnectionInMs ); RestTemplate restTemplate = new RestTemplate( factory ); return restTemplate; }
/** * Set up authentication for HTTP Basic/HTTP Digest/SPNEGO. * * @param httpClientBuilder The client builder * @return The context * @throws HttpException */ private void setupAuthentication( HttpClientBuilder httpClientBuilder ) throws HttpException { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); if (authType == AuthType.always) { AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); HttpHost target = new HttpHost(host, port, isOverSsl ? "https" : "http"); authCache.put(target, basicAuth); // Add AuthCache to the execution context httpContext.setAuthCache(authCache); } else { if (!StringUtils.isNullOrEmpty(kerberosServicePrincipalName)) { GssClient gssClient = new GssClient(username, password, kerberosClientKeytab, krb5ConfFile); AuthSchemeProvider nsf = new SPNegoSchemeFactory(gssClient, kerberosServicePrincipalName, kerberosServicePrincipalType); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create() .register(AuthSchemes.SPNEGO, nsf) .build(); httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry); } } }
private CredentialsProvider credentialsProvider() { // sets up credentials object CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(new HttpHost(HOST)), new UsernamePasswordCredentials(USER, PASS)); return credsProvider; }