use of org.apache.hc.client5.http.auth.CredentialsProvider in project ecf by eclipse.
the class HttpClientRetrieveFileTransfer method openStreams.
/* (non-Javadoc)
* @see org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer#openStreams()
*/
@Override
protected void openStreams() throws IncomingFileTransferException {
// $NON-NLS-1$
Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "openStreams");
final String urlString = getRemoteFileURL().toString();
this.doneFired = false;
int code = -1;
try {
getMethod = new HttpGet(urlString);
RequestConfig.Builder rcfgBuilder = getRequestConfigBuilder();
rcfgBuilder.setConnectTimeout(getConnectTimeout(), TimeUnit.MILLISECONDS);
setupAuthentication(urlString);
// Define a CredentialsProvider - found that possibility while debugging in org.apache.commons.httpclient.HttpMethodDirector.processProxyAuthChallenge(HttpMethod)
// Seems to be another way to select the credentials.
setRequestHeaderValues();
// $NON-NLS-1$
Trace.trace(Activator.PLUGIN_ID, "retrieve=" + urlString);
// 2) The target remote file does *not* end in .gz (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=280205)
if (getFileRangeSpecification() == null && !targetHasGzSuffix(super.getRemoteFileName())) {
// The interceptors to provide gzip are always added and are enabled by default
// $NON-NLS-1$
Trace.trace(Activator.PLUGIN_ID, "Accept-Encoding: gzip,deflate added to request header");
} else {
// Disable the interceptors to provide gzip
// $NON-NLS-1$
Trace.trace(Activator.PLUGIN_ID, "Accept-Encoding NOT added to header");
rcfgBuilder.setContentCompressionEnabled(false);
}
getMethod.setConfig(rcfgBuilder.build());
fireConnectStartEvent();
if (checkAndHandleDone()) {
return;
}
// redirect response code handled internally
if (connectJob == null) {
performConnect(new NullProgressMonitor());
} else {
connectJob.schedule();
connectJob.join();
connectJob = null;
}
if (checkAndHandleDone()) {
return;
}
code = responseCode;
responseHeaders = getResponseHeaders();
// $NON-NLS-1$
Trace.trace(Activator.PLUGIN_ID, "retrieve resp=" + code);
// Check for NTLM proxy in response headers
// This check is to deal with bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=252002
boolean ntlmProxyFound = NTLMProxyDetector.detectNTLMProxy(httpContext);
if (ntlmProxyFound)
ECFHttpClientFactory.getNTLMProxyHandler(httpContext).handleNTLMProxy(getProxy(), code);
if (NTLMProxyDetector.detectSPNEGOProxy(httpContext))
ECFHttpClientFactory.getNTLMProxyHandler(httpContext).handleSPNEGOProxy(getProxy(), code);
if (code == HttpStatus.SC_PARTIAL_CONTENT || code == HttpStatus.SC_OK) {
getResponseHeaderValues();
setInputStream(httpResponse.getEntity().getContent());
fireReceiveStartEvent();
} else if (code == HttpStatus.SC_NOT_FOUND) {
EntityUtils.consume(httpResponse.getEntity());
// $NON-NLS-1$
throw new IncomingFileTransferException(NLS.bind("File not found: {0}", urlString), code);
} else if (code == HttpStatus.SC_UNAUTHORIZED) {
EntityUtils.consume(httpResponse.getEntity());
throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code);
} else if (code == HttpStatus.SC_FORBIDDEN) {
EntityUtils.consume(httpResponse.getEntity());
// $NON-NLS-1$
throw new IncomingFileTransferException("Forbidden", code);
} else if (code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
EntityUtils.consume(httpResponse.getEntity());
throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required, code);
} else {
HttpEntity httpResponseEntity = httpResponse.getEntity();
if (httpResponseEntity != null) {
Trace.trace(Activator.PLUGIN_ID, EntityUtils.toString(httpResponseEntity));
}
throw new IncomingFileTransferException(NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE, Integer.valueOf(code)), code);
}
} catch (final Exception e) {
// $NON-NLS-1$
Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "openStreams", e);
if (code == -1) {
if (!isDone()) {
setDoneException(e);
}
fireTransferReceiveDoneEvent();
} else {
IncomingFileTransferException ex = (IncomingFileTransferException) ((e instanceof IncomingFileTransferException) ? e : new IncomingFileTransferException(NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT, urlString), e, code));
throw ex;
}
}
// $NON-NLS-1$
Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(), "openStreams");
}
use of org.apache.hc.client5.http.auth.CredentialsProvider in project ecf by eclipse.
the class HttpClientRetrieveFileTransfer method openStreamsForResume.
private boolean openStreamsForResume() {
// $NON-NLS-1$
Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "openStreamsForResume");
final String urlString = getRemoteFileURL().toString();
this.doneFired = false;
int code = -1;
try {
getMethod = new HttpGet(urlString);
requestConfigBuilder.setContentCompressionEnabled(false);
setupAuthentication(urlString);
// Define a CredentialsProvider - found that possibility while debugging in org.apache.commons.httpclient.HttpMethodDirector.processProxyAuthChallenge(HttpMethod)
// Seems to be another way to select the credentials.
setResumeRequestHeaderValues();
// $NON-NLS-1$
Trace.trace(Activator.PLUGIN_ID, "resume=" + urlString);
getMethod.setConfig(requestConfigBuilder.build());
// Gzip encoding is not an option for resume
fireConnectStartEvent();
if (checkAndHandleDone()) {
return false;
}
// redirect response code handled internally
if (connectJob == null) {
performConnect(new NullProgressMonitor());
} else {
connectJob.schedule();
connectJob.join();
connectJob = null;
}
if (checkAndHandleDone()) {
return false;
}
code = responseCode;
responseHeaders = getResponseHeaders();
// $NON-NLS-1$
Trace.trace(Activator.PLUGIN_ID, "retrieve resp=" + code);
if (code == HttpStatus.SC_PARTIAL_CONTENT || code == HttpStatus.SC_OK) {
getResumeResponseHeaderValues();
setInputStream(httpResponse.getEntity().getContent());
this.paused = false;
fireReceiveResumedEvent();
} else if (code == HttpStatus.SC_NOT_FOUND) {
EntityUtils.consume(httpResponse.getEntity());
// $NON-NLS-1$
throw new IncomingFileTransferException(NLS.bind("File not found: {0}", urlString), code, responseHeaders);
} else if (code == HttpStatus.SC_UNAUTHORIZED) {
EntityUtils.consume(httpResponse.getEntity());
throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code, responseHeaders);
} else if (code == HttpStatus.SC_FORBIDDEN) {
EntityUtils.consume(httpResponse.getEntity());
// $NON-NLS-1$
throw new IncomingFileTransferException("Forbidden", code, responseHeaders);
} else if (code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
EntityUtils.consume(httpResponse.getEntity());
throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required, code, responseHeaders);
} else {
EntityUtils.consume(httpResponse.getEntity());
throw new IncomingFileTransferException(NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE, Integer.valueOf(code)), code, responseHeaders);
}
// $NON-NLS-1$
Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(), "openStreamsForResume", Boolean.TRUE);
return true;
} catch (final Exception e) {
// $NON-NLS-1$
Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, this.getClass(), "openStreamsForResume", e);
if (code == -1) {
if (!isDone()) {
setDoneException(e);
}
} else {
setDoneException((e instanceof IncomingFileTransferException) ? e : new IncomingFileTransferException(NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT, urlString), e, code, responseHeaders));
}
fireTransferReceiveDoneEvent();
// $NON-NLS-1$
Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(), "openStreamsForResume", Boolean.FALSE);
return false;
}
}
use of org.apache.hc.client5.http.auth.CredentialsProvider in project mercury by yellow013.
the class ClientConfiguration method main.
public static final void main(final String[] args) throws Exception {
// Use custom message parser / writer to customize the way HTTP
// messages are parsed from and written out to the data stream.
final HttpMessageParserFactory<ClassicHttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {
@Override
public HttpMessageParser<ClassicHttpResponse> create(final Http1Config h1Config) {
final LineParser lineParser = new BasicLineParser() {
@Override
public Header parseHeader(final CharArrayBuffer buffer) {
try {
return super.parseHeader(buffer);
} catch (final ParseException ex) {
return new BasicHeader(buffer.toString(), null);
}
}
};
return new DefaultHttpResponseParser(lineParser, DefaultClassicHttpResponseFactory.INSTANCE, h1Config);
}
};
final HttpMessageWriterFactory<ClassicHttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();
// Create HTTP/1.1 protocol configuration
final Http1Config h1Config = Http1Config.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
// Create connection configuration
final CharCodingConfig connectionConfig = CharCodingConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE).setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(StandardCharsets.UTF_8).build();
// Use a custom connection factory to customize the process of
// initialization of outgoing HTTP connections. Beside standard connection
// configuration parameters HTTP connection factory can define message
// parser / writer routines to be employed by individual connections.
@SuppressWarnings("unused") final HttpConnectionFactory<ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(h1Config, connectionConfig, requestWriterFactory, responseParserFactory);
// Client HTTP connection objects when fully initialized can be bound to
// an arbitrary network socket. The process of network socket initialization,
// its connection to a remote address and binding to a local one is controlled
// by a connection socket factory.
// SSL context for secure connections can be created either based on
// system or application specific properties.
final SSLContext sslcontext = SSLContexts.createSystemDefault();
// Create a registry of custom connection socket factories for supported
// protocol schemes.
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)).build();
// Use custom DNS resolver to override the system DNS resolution.
final DnsResolver dnsResolver = new SystemDefaultDnsResolver() {
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
if (host.equalsIgnoreCase("myhost")) {
return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
} else {
return super.resolve(host);
}
}
};
// Create a connection manager with custom configuration.
final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, PoolConcurrencyPolicy.STRICT, PoolReusePolicy.LIFO, TimeValue.ofMinutes(5), null, dnsResolver, null);
// Create socket configuration
final SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
// Configure the connection manager to use socket configuration either
// by default or for a specific host.
connManager.setDefaultSocketConfig(socketConfig);
// Validate connections after 1 sec of inactivity
connManager.setValidateAfterInactivity(TimeValue.ofSeconds(10));
// Configure total max or per route limits for persistent connections
// that can be kept in the pool or leased by the connection manager.
connManager.setMaxTotal(100);
connManager.setDefaultMaxPerRoute(10);
connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);
// Use custom cookie store if necessary.
final CookieStore cookieStore = new BasicCookieStore();
// Use custom credentials provider if necessary.
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
// Create global request configuration
final RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(StandardCookieSpec.STRICT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(StandardAuthScheme.NTLM, StandardAuthScheme.DIGEST)).setProxyPreferredAuthSchemes(Collections.singletonList(StandardAuthScheme.BASIC)).build();
try (final CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider).setProxy(new HttpHost("myproxy", 8080)).setDefaultRequestConfig(defaultRequestConfig).build()) {
final HttpGet httpget = new HttpGet("http://httpbin.org/get");
// Request configuration can be overridden at the request level.
// They will take precedence over the one set at the client level.
final RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setConnectionRequestTimeout(Timeout.ofSeconds(5)).setConnectTimeout(Timeout.ofSeconds(5)).setProxy(new HttpHost("myotherproxy", 8080)).build();
httpget.setConfig(requestConfig);
// Execution context can be customized locally.
final HttpClientContext context = HttpClientContext.create();
// Contextual attributes set the local context level will take
// precedence over those set at the client level.
context.setCookieStore(cookieStore);
context.setCredentialsProvider(credentialsProvider);
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
try (final CloseableHttpResponse response = httpclient.execute(httpget, context)) {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
System.out.println(EntityUtils.toString(response.getEntity()));
// Once the request has been executed the local context can
// be used to examine updated state and various objects affected
// by the request execution.
// Last executed request
context.getRequest();
// Execution route
context.getHttpRoute();
// Auth exchanges
context.getAuthExchanges();
// Cookie origin
context.getCookieOrigin();
// Cookie spec used
context.getCookieSpec();
// User security token
context.getUserToken();
}
}
}
use of org.apache.hc.client5.http.auth.CredentialsProvider in project mercury by yellow013.
the class ClientPreemptiveDigestAuthentication method main.
public static void main(final String[] args) throws Exception {
try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
final HttpHost target = new HttpHost("http", "httpbin.org", 80);
final HttpClientContext localContext = HttpClientContext.create();
final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(target), new UsernamePasswordCredentials("user", "passwd".toCharArray()));
localContext.setCredentialsProvider(credentialsProvider);
final HttpGet httpget = new HttpGet("http://httpbin.org/digest-auth/auth/user/passwd");
System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());
for (int i = 0; i < 3; i++) {
try (final CloseableHttpResponse response = httpclient.execute(target, httpget, localContext)) {
System.out.println("----------------------------------------");
System.out.println(response.getCode() + " " + response.getReasonPhrase());
EntityUtils.consume(response.getEntity());
final AuthExchange authExchange = localContext.getAuthExchange(target);
if (authExchange != null) {
final AuthScheme authScheme = authExchange.getAuthScheme();
if (authScheme instanceof DigestScheme) {
final DigestScheme digestScheme = (DigestScheme) authScheme;
System.out.println("Nonce: " + digestScheme.getNonce() + "; count: " + digestScheme.getNounceCount());
}
}
}
}
}
}
use of org.apache.hc.client5.http.auth.CredentialsProvider in project webdrivermanager by bonigarcia.
the class HttpClient method createBasicCredentialsProvider.
private final Optional<BasicCredentialsProvider> createBasicCredentialsProvider(String proxy, String proxyUser, String proxyPass, HttpHost proxyHost) throws MalformedURLException, UnsupportedEncodingException {
Optional<URL> proxyUrl = determineProxyUrl(proxy);
if (!proxyUrl.isPresent()) {
return empty();
}
String username = null;
String password = null;
// apply env value
String userInfo = proxyUrl.get().getUserInfo();
if (userInfo != null) {
StringTokenizer st = new StringTokenizer(userInfo, ":");
username = st.hasMoreTokens() ? decode(st.nextToken(), UTF_8.name()) : null;
password = st.hasMoreTokens() ? decode(st.nextToken(), UTF_8.name()) : null;
}
String envProxyUser = getenv("HTTPS_PROXY_USER");
String envProxyPass = getenv("HTTPS_PROXY_PASS");
username = (envProxyUser != null) ? envProxyUser : username;
password = (envProxyPass != null) ? envProxyPass : password;
// apply option value
username = isNullOrEmpty(proxyUser) ? username : proxyUser;
password = isNullOrEmpty(proxyPass) ? password : proxyPass;
if (username == null) {
return empty();
}
String ntlmUsername = username;
String ntlmDomain = null;
int index = username.indexOf('\\');
if (index > 0) {
ntlmDomain = username.substring(0, index);
ntlmUsername = username.substring(index + 1);
}
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
AuthScope authScope = new AuthScope(proxyHost, null, NTLM);
char[] passwd = (password == null) ? new char[0] : password.toCharArray();
Credentials creds = new NTCredentials(ntlmUsername, passwd, getWorkstation(), ntlmDomain);
credentialsProvider.setCredentials(authScope, creds);
authScope = new AuthScope(proxyHost.getHostName(), proxyHost.getPort());
creds = new UsernamePasswordCredentials(username, passwd);
credentialsProvider.setCredentials(authScope, creds);
return Optional.of(credentialsProvider);
}
Aggregations