use of org.apache.http.impl.auth.BasicScheme in project elasticsearch by elastic.
the class RestClient method setHosts.
/**
* Replaces the hosts that the client communicates with.
* @see HttpHost
*/
public synchronized void setHosts(HttpHost... hosts) {
if (hosts == null || hosts.length == 0) {
throw new IllegalArgumentException("hosts must not be null nor empty");
}
Set<HttpHost> httpHosts = new HashSet<>();
AuthCache authCache = new BasicAuthCache();
for (HttpHost host : hosts) {
Objects.requireNonNull(host, "host cannot be null");
httpHosts.add(host);
authCache.put(host, new BasicScheme());
}
this.hostTuple = new HostTuple<>(Collections.unmodifiableSet(httpHosts), authCache);
this.blacklist.clear();
}
use of org.apache.http.impl.auth.BasicScheme in project opennms by OpenNMS.
the class RestSessionIT method queryUri.
private Header[] queryUri(final String uri, final String header) throws IOException {
final HttpGet httpGet = new HttpGet(getBaseUrl() + uri);
final HttpHost targetHost = new HttpHost(httpGet.getURI().getHost(), httpGet.getURI().getPort(), httpGet.getURI().getScheme());
final CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("admin", "admin"));
final AuthCache authCache = new BasicAuthCache();
final BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
final CloseableHttpResponse closeableHttpResponse = HttpClients.createDefault().execute(targetHost, httpGet, context);
closeableHttpResponse.close();
return closeableHttpResponse.getHeaders(header);
}
use of org.apache.http.impl.auth.BasicScheme in project jmeter by apache.
the class HTTPHC4Impl method executeRequest.
/**
* Execute request either as is or under PrivilegedAction
* if a Subject is available for url
* @param httpClient the {@link CloseableHttpClient} to be used to execute the httpRequest
* @param httpRequest the {@link HttpRequest} to be executed
* @param localContext th {@link HttpContext} to be used for execution
* @param url the target url (will be used to look up a possible subject for the execution)
* @return the result of the execution of the httpRequest
* @throws IOException
* @throws ClientProtocolException
*/
private CloseableHttpResponse executeRequest(final CloseableHttpClient httpClient, final HttpRequestBase httpRequest, final HttpContext localContext, final URL url) throws IOException, ClientProtocolException {
AuthManager authManager = getAuthManager();
if (authManager != null) {
Subject subject = authManager.getSubjectForUrl(url);
if (subject != null) {
try {
return Subject.doAs(subject, (PrivilegedExceptionAction<CloseableHttpResponse>) () -> httpClient.execute(httpRequest, localContext));
} catch (PrivilegedActionException e) {
log.error("Can't execute httpRequest with subject: {}", subject, e);
throw new RuntimeException("Can't execute httpRequest with subject:" + subject, e);
}
}
if (BASIC_AUTH_PREEMPTIVE) {
Authorization authorization = authManager.getAuthForURL(url);
if (authorization != null && Mechanism.BASIC_DIGEST.equals(authorization.getMechanism())) {
HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
// 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(target, basicAuth);
// Add AuthCache to the execution context
localContext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
}
}
}
return httpClient.execute(httpRequest, localContext);
}
use of org.apache.http.impl.auth.BasicScheme in project fess by codelibs.
the class DataConfig method initializeClientFactory.
@Override
public Map<String, Object> initializeClientFactory(final CrawlerClientFactory crawlerClientFactory) {
final Map<String, String> paramMap = getHandlerParameterMap();
final Map<String, Object> factoryParamMap = new HashMap<>();
crawlerClientFactory.setInitParameterMap(factoryParamMap);
// parameters
for (final Map.Entry<String, String> entry : paramMap.entrySet()) {
final String key = entry.getKey();
if (key.startsWith(CRAWLER_PARAM_PREFIX)) {
factoryParamMap.put(key.substring(CRAWLER_PARAM_PREFIX.length()), entry.getValue());
}
}
// user agent
final String userAgent = paramMap.get(CRAWLER_USERAGENT);
if (StringUtil.isNotBlank(userAgent)) {
factoryParamMap.put(HcHttpClient.USER_AGENT_PROPERTY, userAgent);
}
// web auth
final String webAuthStr = paramMap.get(CRAWLER_WEB_AUTH);
if (StringUtil.isNotBlank(webAuthStr)) {
final String[] webAuthNames = webAuthStr.split(",");
final List<Authentication> basicAuthList = new ArrayList<>();
for (final String webAuthName : webAuthNames) {
final String scheme = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".scheme");
final String hostname = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".host");
final String port = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".port");
final String realm = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".realm");
final String username = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".username");
final String password = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".password");
if (StringUtil.isEmpty(username)) {
logger.warn("username is empty. webAuth:" + webAuthName);
continue;
}
AuthScheme authScheme = null;
if (Constants.BASIC.equals(scheme)) {
authScheme = new BasicScheme();
} else if (Constants.DIGEST.equals(scheme)) {
authScheme = new DigestScheme();
} else if (Constants.NTLM.equals(scheme)) {
authScheme = new NTLMScheme(new JcifsEngine());
}
// TODO FORM
AuthScope authScope;
if (StringUtil.isBlank(hostname)) {
authScope = AuthScope.ANY;
} else {
int p = AuthScope.ANY_PORT;
if (StringUtil.isNotBlank(port)) {
try {
p = Integer.parseInt(port);
} catch (final NumberFormatException e) {
logger.warn("Failed to parse " + port, e);
}
}
String r = realm;
if (StringUtil.isBlank(realm)) {
r = AuthScope.ANY_REALM;
}
String s = scheme;
if (StringUtil.isBlank(scheme) || Constants.NTLM.equals(scheme)) {
s = AuthScope.ANY_SCHEME;
}
authScope = new AuthScope(hostname, p, r, s);
}
Credentials credentials;
if (Constants.NTLM.equals(scheme)) {
final String workstation = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".workstation");
final String domain = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".domain");
credentials = new NTCredentials(username, password == null ? StringUtil.EMPTY : password, workstation == null ? StringUtil.EMPTY : workstation, domain == null ? StringUtil.EMPTY : domain);
} else {
credentials = new UsernamePasswordCredentials(username, password == null ? StringUtil.EMPTY : password);
}
basicAuthList.add(new AuthenticationImpl(authScope, credentials, authScheme));
}
factoryParamMap.put(HcHttpClient.BASIC_AUTHENTICATIONS_PROPERTY, basicAuthList.toArray(new Authentication[basicAuthList.size()]));
}
// request header
final List<org.codelibs.fess.crawler.client.http.RequestHeader> rhList = new ArrayList<>();
int count = 1;
String headerName = paramMap.get(CRAWLER_WEB_HEADER_PREFIX + count + ".name");
while (StringUtil.isNotBlank(headerName)) {
final String headerValue = paramMap.get(CRAWLER_WEB_HEADER_PREFIX + count + ".value");
rhList.add(new org.codelibs.fess.crawler.client.http.RequestHeader(headerName, headerValue));
count++;
headerName = paramMap.get(CRAWLER_WEB_HEADER_PREFIX + count + ".name");
}
if (!rhList.isEmpty()) {
factoryParamMap.put(HcHttpClient.REQUERT_HEADERS_PROPERTY, rhList.toArray(new org.codelibs.fess.crawler.client.http.RequestHeader[rhList.size()]));
}
// file auth
final String fileAuthStr = paramMap.get(CRAWLER_FILE_AUTH);
if (StringUtil.isNotBlank(fileAuthStr)) {
final String[] fileAuthNames = fileAuthStr.split(",");
final List<SmbAuthentication> smbAuthList = new ArrayList<>();
final List<FtpAuthentication> ftpAuthList = new ArrayList<>();
for (final String fileAuthName : fileAuthNames) {
final String scheme = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".scheme");
if (Constants.SAMBA.equals(scheme)) {
final String domain = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".domain");
final String hostname = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".host");
final String port = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".port");
final String username = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".username");
final String password = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".password");
if (StringUtil.isEmpty(username)) {
logger.warn("username is empty. fileAuth:" + fileAuthName);
continue;
}
final SmbAuthentication smbAuth = new SmbAuthentication();
smbAuth.setDomain(domain == null ? StringUtil.EMPTY : domain);
smbAuth.setServer(hostname);
if (StringUtil.isNotBlank(port)) {
try {
smbAuth.setPort(Integer.parseInt(port));
} catch (final NumberFormatException e) {
logger.warn("Failed to parse " + port, e);
}
}
smbAuth.setUsername(username);
smbAuth.setPassword(password == null ? StringUtil.EMPTY : password);
smbAuthList.add(smbAuth);
} else if (Constants.FTP.equals(scheme)) {
final String hostname = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".host");
final String port = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".port");
final String username = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".username");
final String password = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".password");
if (StringUtil.isEmpty(username)) {
logger.warn("username is empty. fileAuth:" + fileAuthName);
continue;
}
final FtpAuthentication ftpAuth = new FtpAuthentication();
ftpAuth.setServer(hostname);
if (StringUtil.isNotBlank(port)) {
try {
ftpAuth.setPort(Integer.parseInt(port));
} catch (final NumberFormatException e) {
logger.warn("Failed to parse " + port, e);
}
}
ftpAuth.setUsername(username);
ftpAuth.setPassword(password == null ? StringUtil.EMPTY : password);
ftpAuthList.add(ftpAuth);
}
}
if (!smbAuthList.isEmpty()) {
factoryParamMap.put(SmbClient.SMB_AUTHENTICATIONS_PROPERTY, smbAuthList.toArray(new SmbAuthentication[smbAuthList.size()]));
}
if (!ftpAuthList.isEmpty()) {
factoryParamMap.put(FtpClient.FTP_AUTHENTICATIONS_PROPERTY, ftpAuthList.toArray(new FtpAuthentication[ftpAuthList.size()]));
}
}
return factoryParamMap;
}
use of org.apache.http.impl.auth.BasicScheme in project iaf by ibissource.
the class HttpSenderBase method sendMessageWithTimeoutGuarded.
@Override
public String sendMessageWithTimeoutGuarded(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException {
ParameterValueList pvl = null;
try {
if (prc != null && paramList != null) {
pvl = prc.getValues(paramList);
}
} catch (ParameterException e) {
throw new SenderException(getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e);
}
URIBuilder uri;
HttpRequestBase httpRequestBase;
try {
if (urlParameter != null) {
String url = (String) pvl.getParameterValue(getUrlParam()).getValue();
uri = getURI(url);
} else {
uri = staticUri;
}
httpTarget = new HttpHost(uri.getHost(), getPort(uri), uri.getScheme());
Map<String, String> headersParamsMap = new HashMap<String, String>();
if (headersParams != null) {
StringTokenizer st = new StringTokenizer(headersParams, ",");
while (st.hasMoreElements()) {
headersParamsMap.put(st.nextToken(), null);
}
}
if (isEncodeMessages()) {
message = URLEncoder.encode(message, getCharSet());
}
httpRequestBase = getMethod(uri, message, pvl, headersParamsMap, prc.getSession());
if (httpRequestBase == null)
throw new MethodNotSupportedException("could not find implementation for method [" + getMethodType() + "]");
if (!"POST".equals(getMethodType()) && !"PUT".equals(getMethodType()) && !"REPORT".equals(getMethodType())) {
httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
protected boolean isRedirectable(String method) {
return true;
}
});
}
if (StringUtils.isNotEmpty(getContentType())) {
httpRequestBase.setHeader("Content-Type", getContentType());
}
if (credentials != null && !StringUtils.isEmpty(credentials.getUsername())) {
AuthCache authCache = httpClientContext.getAuthCache();
if (authCache == null)
authCache = new BasicAuthCache();
authCache.put(httpTarget, new BasicScheme());
httpClientContext.setAuthCache(authCache);
}
log.info(getLogPrefix() + "configured httpclient for host [" + uri.getHost() + "]");
} catch (Exception e) {
throw new SenderException(e);
}
CloseableHttpClient httpClient = httpClientBuilder.build();
String result = null;
int statusCode = -1;
int count = getMaxExecuteRetries();
String msg = null;
while (count-- >= 0 && statusCode == -1) {
try {
log.debug(getLogPrefix() + "executing method [" + httpRequestBase.getRequestLine() + "]");
HttpResponse httpResponse = httpClient.execute(httpTarget, httpRequestBase, httpClientContext);
log.debug(getLogPrefix() + "executed method");
HttpResponseHandler responseHandler = new HttpResponseHandler(httpResponse);
StatusLine statusline = httpResponse.getStatusLine();
statusCode = statusline.getStatusCode();
if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey()) && prc != null) {
prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode));
}
if (statusCode != HttpServletResponse.SC_OK) {
log.warn(getLogPrefix() + "status [" + statusline.toString() + "]");
} else {
log.debug(getLogPrefix() + "status [" + statusCode + "]");
}
result = extractResult(responseHandler, prc);
log.debug(getLogPrefix() + "retrieved result [" + result + "]");
} catch (ClientProtocolException e) {
httpRequestBase.abort();
Throwable throwable = e.getCause();
String cause = null;
if (throwable != null) {
cause = throwable.toString();
}
msg = e.getMessage();
log.warn(getLogPrefix() + "httpException with message [" + msg + "] and cause [" + cause + "], executeRetries left [" + count + "]");
} catch (IOException e) {
httpRequestBase.abort();
if (e instanceof SocketTimeoutException) {
throw new TimeOutException(e);
}
throw new SenderException(e);
} finally {
// By forcing the use of the HttpResponseHandler the resultStream
// will automatically be closed when it has been read.
// See HttpResponseHandler and ReleaseConnectionAfterReadInputStream.
// We cannot close the connection as the response might be kept
// in a sessionKey for later use in the pipeline.
//
// IMPORTANT: It is possible that poorly written implementations
// wont read or close the response.
// This will cause the connection to become stale..
}
}
if (statusCode == -1) {
if (StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) {
// java.net.SocketTimeoutException: Read timed out
throw new TimeOutException("Failed to recover from timeout exception");
}
throw new SenderException("Failed to recover from exception");
}
if (isXhtml() && StringUtils.isNotEmpty(result)) {
result = XmlUtils.skipDocTypeDeclaration(result.trim());
if (result.startsWith("<html>") || result.startsWith("<html ")) {
CleanerProperties props = new CleanerProperties();
HtmlCleaner cleaner = new HtmlCleaner(props);
TagNode tagNode = cleaner.clean(result);
result = new SimpleXmlSerializer(props).getXmlAsString(tagNode);
if (transformerPool != null) {
log.debug(getLogPrefix() + " transforming result [" + result + "]");
ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true, true);
try {
result = transformerPool.transform(prc_xslt.getInputSource(), null);
} catch (Exception e) {
throw new SenderException("Exception on transforming input", e);
}
}
}
}
return result;
}
Aggregations