List of usage examples for org.apache.http.auth AuthScope getHost
public String getHost()
From source file:ucar.unidata.util.AccountManager.java
/** * Do the authentication//from w ww .jav a2 s.c o m * @param scope authscope * * @return Null if the user presses cancel. Else return the credentials * */ public Credentials getCredentials(AuthScope scope) { //TODO: What should this do? if (scope == null) { throw new IllegalArgumentException("Authentication scope may not be null"); } if (currentCredentials == null) { String host = scope.getHost(); int port = scope.getPort(); String key = host + ":" + port + ":" + scope.getRealm(); // System.err.println ("got auth call " + key); UserInfo userInfo = getUserNamePassword(key, "The server " + host + ":" + port + " requires a username/password"); if (userInfo == null) { return null; } currentCredentials = new UsernamePasswordCredentials(userInfo.getUserId(), userInfo.getPassword()); } return currentCredentials; }
From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java
@NonNull private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url, @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException { UserCredentials result = null;/* w w w. ja v a 2s. c o m*/ String realm = null; HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs); HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs); // use the simple one final DefaultHttpClient httpClient = new DefaultHttpClient(params); // create local execution context HttpContext localContext = new BasicHttpContext(); final HttpGet httpGet = new HttpGet(url); if (inHeaders != null) { for (Header header : inHeaders) { httpGet.addHeader(header); } } // retrieve local java configured network in case there is the need to // authenticate a proxy ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Set preference order for authentication options. // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in // servers that support both, as it is more secure. However, we don't seem to handle it // very well, so we leave it off the list. // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for // more info. List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); if (DEBUG) { try { URI uri = new URI(url); ProxySelector sel = routePlanner.getProxySelector(); if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$ List<Proxy> list = sel.select(uri); System.out.printf("SdkLib.UrlOpener:\n Connect to: %s\n Proxy List: %s\n", //$NON-NLS-1$ url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$ } } catch (Exception e) { System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$ url, e.toString()); } } boolean trying = true; // loop while the response is being fetched while (trying) { // connect and get status code HttpResponse response = httpClient.execute(httpGet, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (DEBUG) { System.out.printf(" Status: %d\n", statusCode); //$NON-NLS-1$ } // check whether any authentication is required AuthState authenticationState = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) { // in case the status is OK and there is a realm and result, // cache it if (realm != null && result != null) { sRealmCache.put(realm, result); } } // there is the need for authentication if (authenticationState != null) { // get scope and realm AuthScope authScope = authenticationState.getAuthScope(); // If the current realm is different from the last one it means // a pass was performed successfully to the last URL, therefore // cache the last realm if (realm != null && !realm.equals(authScope.getRealm())) { sRealmCache.put(realm, result); } realm = authScope.getRealm(); // in case there is cache for this Realm, use it to authenticate if (sRealmCache.containsKey(realm)) { result = sRealmCache.get(realm); } else { // since there is no cache, request for login and password result = monitor.displayLoginCredentialsPrompt("Site Authentication", "Please login to the following domain: " + realm + "\n\nServer requiring authentication:\n" + authScope.getHost()); if (result == null) { throw new CanceledByUserException("User canceled login dialog."); } } // retrieve authentication data String user = result.getUserName(); String password = result.getPassword(); String workstation = result.getWorkstation(); String domain = result.getDomain(); // proceed in case there is indeed a user if (user != null && user.length() > 0) { Credentials credentials = new NTCredentials(user, password, workstation, domain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); trying = true; } else { trying = false; } } else { trying = false; } HttpEntity entity = response.getEntity(); if (entity != null) { if (trying) { // in case another pass to the Http Client will be performed, close the entity. entity.getContent().close(); } else { // since no pass to the Http Client is needed, retrieve the // entity's content. // Note: don't use something like a BufferedHttpEntity since it would consume // all content and store it in memory, resulting in an OutOfMemory exception // on a large download. InputStream is = new FilterInputStream(entity.getContent()) { @Override public void close() throws IOException { // Since Http Client is no longer needed, close it. // Bug #21167: we need to tell http client to shutdown // first, otherwise the super.close() would continue // downloading and not return till complete. httpClient.getConnectionManager().shutdown(); super.close(); } }; HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine()); outResponse.setHeaders(response.getAllHeaders()); outResponse.setLocale(response.getLocale()); return Pair.of(is, outResponse); } } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) { // It's ok to not have an entity (e.g. nothing to download) for a 304 HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine()); outResponse.setHeaders(response.getAllHeaders()); outResponse.setLocale(response.getLocale()); return Pair.of(null, outResponse); } } // We get here if we did not succeed. Callers do not expect a null result. httpClient.getConnectionManager().shutdown(); throw new FileNotFoundException(url); }
From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java
@Override public Credentials getCredentials(AuthScope authscope) { if (proxy != null && proxy instanceof HttpProxy) { HttpProxy httpProxy = (HttpProxy) proxy; if (httpProxy.getIp().equals(authscope.getHost()) && httpProxy.getPort() == authscope.getPort() && httpProxy.getUsername() != null && httpProxy.getPassword() != null) { return new UsernamePasswordCredentials(httpProxy.getUsername(), httpProxy.getPassword()); }//from ww w . ja v a 2 s . co m } return credentialProvider.getCredentials(authscope); }
From source file:org.seasar.robot.client.http.HcHttpClient.java
public synchronized void init() { if (httpClient != null) { return;//from w ww. j av a 2 s . co m } if (logger.isDebugEnabled()) { logger.debug("Initializing " + HcHttpClient.class.getName()); } // access timeout final Integer accessTimeoutParam = getInitParameter(ACCESS_TIMEOUT_PROPERTY, accessTimeout); if (accessTimeoutParam != null) { accessTimeout = accessTimeoutParam; } // robots.txt parser final Boolean robotsTxtEnabled = getInitParameter(ROBOTS_TXT_ENABLED_PROPERTY, Boolean.TRUE); if (robotsTxtHelper != null) { robotsTxtHelper.setEnabled(robotsTxtEnabled.booleanValue()); } // httpclient final org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); final Integer connectionTimeoutParam = getInitParameter(CONNECTION_TIMEOUT_PROPERTY, connectionTimeout); if (connectionTimeoutParam != null) { requestConfigBuilder.setConnectTimeout(connectionTimeoutParam); } final Boolean staleCheckingEnabledParam = getInitParameter(STALE_CHECKING_ENABLED_PROPERTY, staleCheckingEnabled); if (staleCheckingEnabledParam != null) { requestConfigBuilder.setStaleConnectionCheckEnabled(staleCheckingEnabledParam); } final Integer soTimeoutParam = getInitParameter(SO_TIMEOUT_PROPERTY, soTimeout); if (soTimeoutParam != null) { requestConfigBuilder.setSocketTimeout(soTimeoutParam); } // AuthSchemeFactory final RegistryBuilder<AuthSchemeProvider> authSchemeProviderBuilder = RegistryBuilder.create(); final Map<String, AuthSchemeProvider> factoryMap = getInitParameter(AUTH_SCHEME_PROVIDERS_PROPERTY, authSchemeProviderMap); if (factoryMap != null) { for (final Map.Entry<String, AuthSchemeProvider> entry : factoryMap.entrySet()) { authSchemeProviderBuilder.register(entry.getKey(), entry.getValue()); } } // user agent userAgent = getInitParameter(USER_AGENT_PROPERTY, userAgent); if (StringUtil.isNotBlank(userAgent)) { httpClientBuilder.setUserAgent(userAgent); } CredentialsProvider credsProvider = null; AuthCache authCache = null; // proxy final String proxyHost = getInitParameter(PROXY_HOST_PROPERTY, this.proxyHost); final Integer proxyPort = getInitParameter(PROXY_PORT_PROPERTY, this.proxyPort); if (proxyHost != null && proxyPort != null) { final HttpHost proxy = new HttpHost(proxyHost, proxyPort); final DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); httpClientBuilder.setRoutePlanner(routePlanner); final Credentials credentials = getInitParameter(PROXY_CREDENTIALS_PROPERTY, proxyCredentials); if (credentials != null) { authCache = new BasicAuthCache(); credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials); final AuthScheme authScheme = getInitParameter(PROXY_AUTH_SCHEME_PROPERTY, proxyAuthScheme); if (authScheme != null) { authCache.put(proxy, authScheme); } } } // Authentication final Authentication[] siteCredentialList = getInitParameter(BASIC_AUTHENTICATIONS_PROPERTY, new Authentication[0]); if (siteCredentialList != null && siteCredentialList.length > 0 && authCache == null) { authCache = new BasicAuthCache(); credsProvider = new BasicCredentialsProvider(); } for (final Authentication authentication : siteCredentialList) { final AuthScope authScope = authentication.getAuthScope(); credsProvider.setCredentials(authScope, authentication.getCredentials()); final AuthScheme authScheme = authentication.getAuthScheme(); if (authScope.getHost() != null && authScheme != null) { final HttpHost targetHost = new HttpHost(authScope.getHost(), authScope.getPort()); authCache.put(targetHost, authScheme); } } if (authCache != null) { httpClientContext.setAuthCache(authCache); httpClientContext.setCredentialsProvider(credsProvider); } // Request Header final RequestHeader[] requestHeaders = getInitParameter(REQUERT_HEADERS_PROPERTY, new RequestHeader[0]); for (final RequestHeader requestHeader : requestHeaders) { if (requestHeader.isValid()) { requestHeaderList.add(new BasicHeader(requestHeader.getName(), requestHeader.getValue())); } } // do not redirect requestConfigBuilder.setRedirectsEnabled(false); // cookie if (cookieSpec != null) { requestConfigBuilder.setCookieSpec(cookieSpec); } // cookie store httpClientBuilder.setDefaultCookieStore(cookieStore); if (cookieStore != null) { final Cookie[] cookies = getInitParameter(COOKIES_PROPERTY, new Cookie[0]); for (final Cookie cookie : cookies) { cookieStore.addCookie(cookie); } } connectionMonitorTask = TimeoutManager.getInstance().addTimeoutTarget( new HcConnectionMonitorTarget(clientConnectionManager, idleConnectionTimeout), connectionCheckInterval, true); final CloseableHttpClient closeableHttpClient = httpClientBuilder .setConnectionManager(clientConnectionManager).setDefaultRequestConfig(requestConfigBuilder.build()) .build(); if (!httpClientPropertyMap.isEmpty()) { final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(closeableHttpClient.getClass()); for (final Map.Entry<String, Object> entry : httpClientPropertyMap.entrySet()) { final String propertyName = entry.getKey(); if (beanDesc.hasPropertyDesc(propertyName)) { final PropertyDesc propertyDesc = beanDesc.getPropertyDesc(propertyName); propertyDesc.setValue(closeableHttpClient, entry.getValue()); } else { logger.warn("DefaultHttpClient does not have " + propertyName + "."); } } } httpClient = closeableHttpClient; }
From source file:org.codelibs.fess.crawler.client.http.HcHttpClient.java
public synchronized void init() { if (httpClient != null) { return;// www .java 2s . c om } if (logger.isDebugEnabled()) { logger.debug("Initializing " + HcHttpClient.class.getName()); } super.init(); // robots.txt parser final Boolean robotsTxtEnabled = getInitParameter(ROBOTS_TXT_ENABLED_PROPERTY, Boolean.TRUE, Boolean.class); if (robotsTxtHelper != null) { robotsTxtHelper.setEnabled(robotsTxtEnabled.booleanValue()); } // httpclient final org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); final Integer connectionTimeoutParam = getInitParameter(CONNECTION_TIMEOUT_PROPERTY, connectionTimeout, Integer.class); if (connectionTimeoutParam != null) { requestConfigBuilder.setConnectTimeout(connectionTimeoutParam); } final Integer soTimeoutParam = getInitParameter(SO_TIMEOUT_PROPERTY, soTimeout, Integer.class); if (soTimeoutParam != null) { requestConfigBuilder.setSocketTimeout(soTimeoutParam); } // AuthSchemeFactory final RegistryBuilder<AuthSchemeProvider> authSchemeProviderBuilder = RegistryBuilder.create(); @SuppressWarnings("unchecked") final Map<String, AuthSchemeProvider> factoryMap = getInitParameter(AUTH_SCHEME_PROVIDERS_PROPERTY, authSchemeProviderMap, Map.class); if (factoryMap != null) { for (final Map.Entry<String, AuthSchemeProvider> entry : factoryMap.entrySet()) { authSchemeProviderBuilder.register(entry.getKey(), entry.getValue()); } } // user agent userAgent = getInitParameter(USER_AGENT_PROPERTY, userAgent, String.class); if (StringUtil.isNotBlank(userAgent)) { httpClientBuilder.setUserAgent(userAgent); } final HttpRoutePlanner planner = buildRoutePlanner(); if (planner != null) { httpClientBuilder.setRoutePlanner(planner); } // Authentication final Authentication[] siteCredentialList = getInitParameter(BASIC_AUTHENTICATIONS_PROPERTY, new Authentication[0], Authentication[].class); for (final Authentication authentication : siteCredentialList) { final AuthScope authScope = authentication.getAuthScope(); credentialsProvider.setCredentials(authScope, authentication.getCredentials()); final AuthScheme authScheme = authentication.getAuthScheme(); if (authScope.getHost() != null && authScheme != null) { final HttpHost targetHost = new HttpHost(authScope.getHost(), authScope.getPort()); authCache.put(targetHost, authScheme); } } httpClientContext.setAuthCache(authCache); httpClientContext.setCredentialsProvider(credentialsProvider); // Request Header final RequestHeader[] requestHeaders = getInitParameter(REQUERT_HEADERS_PROPERTY, new RequestHeader[0], RequestHeader[].class); for (final RequestHeader requestHeader : requestHeaders) { if (requestHeader.isValid()) { requestHeaderList.add(new BasicHeader(requestHeader.getName(), requestHeader.getValue())); } } // do not redirect requestConfigBuilder .setRedirectsEnabled(getInitParameter(REDIRECTS_ENABLED, redirectsEnabled, Boolean.class)); // cookie if (cookieSpec != null) { requestConfigBuilder.setCookieSpec(cookieSpec); } // cookie store httpClientBuilder.setDefaultCookieStore(cookieStore); if (cookieStore != null) { final Cookie[] cookies = getInitParameter(COOKIES_PROPERTY, new Cookie[0], Cookie[].class); for (final Cookie cookie : cookies) { cookieStore.addCookie(cookie); } } connectionMonitorTask = TimeoutManager.getInstance().addTimeoutTarget( new HcConnectionMonitorTarget(clientConnectionManager, idleConnectionTimeout), connectionCheckInterval, true); final CloseableHttpClient closeableHttpClient = httpClientBuilder .setConnectionManager(clientConnectionManager).setDefaultRequestConfig(requestConfigBuilder.build()) .build(); if (!httpClientPropertyMap.isEmpty()) { final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(closeableHttpClient.getClass()); for (final Map.Entry<String, Object> entry : httpClientPropertyMap.entrySet()) { final String propertyName = entry.getKey(); if (beanDesc.hasPropertyDesc(propertyName)) { final PropertyDesc propertyDesc = beanDesc.getPropertyDesc(propertyName); propertyDesc.setValue(closeableHttpClient, entry.getValue()); } else { logger.warn("DefaultHttpClient does not have " + propertyName + "."); } } } httpClient = closeableHttpClient; }
From source file:org.switchyard.component.resteasy.util.ClientInvoker.java
/** * Create a RESTEasy invoker client.//from ww w . j ava 2s.c o m * * @param basePath The base path for the class * @param resourceClass The JAX-RS Resource Class * @param method The JAX-RS Resource Class's method * @param model Configuration model */ public ClientInvoker(String basePath, Class<?> resourceClass, Method method, RESTEasyBindingModel model) { Set<String> httpMethods = IsHttpMethod.getHttpMethods(method); _baseUri = createUri(basePath); if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class) && method.getReturnType().isInterface()) { _subResourcePath = createSubResourcePath(basePath, method); } else if (httpMethods == null || httpMethods.size() != 1) { throw RestEasyMessages.MESSAGES .youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(method.toString()); } _httpMethod = httpMethods.iterator().next(); _resourceClass = resourceClass; _method = method; try { _uri = (UriBuilder) URIBUILDER_CLASS.newInstance(); } catch (InstantiationException ie) { throw new RuntimeException(ie); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } _uri.uri(_baseUri); if (_resourceClass.isAnnotationPresent(Path.class)) { _uri.path(_resourceClass); } if (_method.isAnnotationPresent(Path.class)) { _uri.path(_method); } _providerFactory = new ResteasyProviderFactory(); boolean useBuiltins = true; // use builtin @Provider classes by default if (model.getContextParamsConfig() != null) { Map<String, String> contextParams = model.getContextParamsConfig().toMap(); // Set use builtin @Provider classes String registerBuiltins = contextParams.get(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS); if (registerBuiltins != null) { useBuiltins = Boolean.parseBoolean(registerBuiltins); } // Register @Provider classes List<Class<?>> providerClasses = RESTEasyUtil.getProviderClasses(contextParams); if (providerClasses != null) { for (Class<?> pc : providerClasses) { _providerFactory.registerProvider(pc); } } List<ClientErrorInterceptor> interceptors = RESTEasyUtil.getClientErrorInterceptors(contextParams); if (interceptors != null) { for (ClientErrorInterceptor interceptor : interceptors) { _providerFactory.addClientErrorInterceptor(interceptor); } } } if (useBuiltins) { _providerFactory.setRegisterBuiltins(true); RegisterBuiltin.register(_providerFactory); } _extractorFactory = new DefaultEntityExtractorFactory(); _extractor = _extractorFactory.createExtractor(_method); _marshallers = ClientMarshallerFactory.createMarshallers(_resourceClass, _method, _providerFactory, null); _accepts = MediaTypeHelper.getProduces(_resourceClass, method, null); ClientInvokerInterceptorFactory.applyDefaultInterceptors(this, _providerFactory, _resourceClass, _method); // Client executor SchemeRegistry schemeRegistry = new SchemeRegistry(); int port = _baseUri.getPort(); if (_baseUri.getScheme().startsWith("https")) { if (port == -1) { port = 443; } SSLSocketFactory sslFactory = getSSLSocketFactory(model.getSSLContextConfig()); if (sslFactory == null) { sslFactory = SSLSocketFactory.getSocketFactory(); } schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, sslFactory)); } else { if (port == -1) { port = 80; } schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, PlainSocketFactory.getSocketFactory())); } PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry); cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); HttpClient httpClient = new DefaultHttpClient(cm); _executor = new ApacheHttpClient4Executor(httpClient); // register ApacheHttpClient4ExceptionMapper manually for local instance of ResteasyProviderFactory Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class, ClientExceptionMapper.class)[0]; _providerFactory.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType); // Authentication settings if (model.hasAuthentication()) { // Set authentication AuthScope authScope = null; Credentials credentials = null; if (model.isBasicAuth()) { authScope = createAuthScope(model.getBasicAuthConfig().getHost(), model.getBasicAuthConfig().getPort(), model.getBasicAuthConfig().getRealm()); credentials = new UsernamePasswordCredentials(model.getBasicAuthConfig().getUser(), model.getBasicAuthConfig().getPassword()); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(authScope.getHost(), authScope.getPort()), new BasicScheme(ChallengeState.TARGET)); BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); ((ApacheHttpClient4Executor) _executor).setHttpContext(context); } else { authScope = createAuthScope(model.getNtlmAuthConfig().getHost(), model.getNtlmAuthConfig().getPort(), model.getNtlmAuthConfig().getRealm()); credentials = new NTCredentials(model.getNtlmAuthConfig().getUser(), model.getNtlmAuthConfig().getPassword(), "", model.getNtlmAuthConfig().getDomain()); } ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials); } else { ProxyModel proxy = model.getProxyConfig(); if (proxy != null) { HttpHost proxyHost = null; if (proxy.getPort() != null) { proxyHost = new HttpHost(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue()); } else { proxyHost = new HttpHost(proxy.getHost(), -1); } if (proxy.getUser() != null) { AuthScope authScope = new AuthScope(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue(), AuthScope.ANY_REALM); Credentials credentials = new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword()); AuthCache authCache = new BasicAuthCache(); authCache.put(proxyHost, new BasicScheme(ChallengeState.PROXY)); ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials); BasicHttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTH_CACHE, authCache); ((ApacheHttpClient4Executor) _executor).setHttpContext(context); } httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost); } } Integer timeout = model.getTimeout(); if (timeout != null) { HttpParams httpParams = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); HttpConnectionParams.setSoTimeout(httpParams, timeout); } }
From source file:com.mnxfst.testing.activities.http.AbstractHTTPRequestActivity.java
/** * @see com.mnxfst.testing.activities.TSPlanActivity#initialize(com.mnxfst.testing.plan.config.TSPlanConfigOption) *//*from ww w .j a va2 s. co m*/ public void initialize(TSPlanConfigOption cfg) throws TSPlanActivityExecutionException { if (cfg == null) throw new TSPlanActivityExecutionException("Failed to initialize activity '" + this.getClass().getName() + "' due to missing configuration options"); ///////////////////////////////////////////////////////////////////////////////////////// // fetch scheme, host, port and path this.scheme = (String) cfg.getOption(CFG_OPT_SCHEME); if (this.scheme == null || this.scheme.isEmpty()) throw new TSPlanActivityExecutionException( "Required config option '" + CFG_OPT_SCHEME + "' missing for activity '" + getName() + "'"); this.host = (String) cfg.getOption(CFG_OPT_HOST); if (this.host == null || this.host.isEmpty()) throw new TSPlanActivityExecutionException( "Requied config option '" + CFG_OPT_HOST + "' missing for activity '" + getName() + "'"); String portStr = (String) cfg.getOption(CFG_OPT_PORT); if (portStr != null && !portStr.isEmpty()) { try { this.port = Integer.parseInt(portStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_PORT + "' for activity '" + getName() + "'"); } } // fetch username and password this.basicAuthUsername = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_USERNAME); this.basicAuthPassword = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PASSWORD); this.basicAuthHostScope = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_HOST_SCOPE); String authPortScopeStr = (String) cfg.getOption(CFG_OPT_BASIC_AUTH_PORT_SCOPE); if (authPortScopeStr != null && !authPortScopeStr.trim().isEmpty()) { try { this.basicAuthPortScope = Integer.parseInt(authPortScopeStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_BASIC_AUTH_PORT_SCOPE + "' for activity '" + getName() + "'"); } } if (this.port <= 0) this.port = 80; this.path = (String) cfg.getOption(CFG_OPT_PATH); if (this.path == null || this.path.isEmpty()) this.path = "/"; String maxConnStr = (String) cfg.getOption(CFG_OPT_MAX_CONNECTIONS); if (maxConnStr != null && !maxConnStr.isEmpty()) { try { this.maxConnections = Integer.parseInt(maxConnStr); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_MAX_CONNECTIONS + "' for activity '" + getName() + "'"); } } // initialize http host and context this.httpHost = new HttpHost(this.host, this.port); // URI builder try { // query parameters List<NameValuePair> qParams = new ArrayList<NameValuePair>(); for (String key : cfg.getOptions().keySet()) { if (key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) { String value = (String) cfg.getOption(key); String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length()); qParams.add(new BasicNameValuePair(requestParameterName, value)); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", requestParameter=" + requestParameterName + ", value=" + value + "]"); } } this.destinationURI = URIUtils.createURI(this.scheme, this.host, this.port, this.path, URLEncodedUtils.format(qParams, this.contentChartset), null); // TODO handle post values } catch (URISyntaxException e) { throw new TSPlanActivityExecutionException("Failed to initialize uri for [scheme=" + this.scheme + ", host=" + this.host + ", port=" + this.port + ", path=" + this.path + "]"); } httpRequestContext.setAttribute(ExecutionContext.HTTP_CONNECTION, clientConnection); httpRequestContext.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", maxConnections=" + maxConnections + ", scheme=" + scheme + ", host=" + host + ", port=" + port + ", path=" + path + "]"); ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // protocol settings this.userAgent = (String) cfg.getOption(CFG_OPT_USER_AGENT); if (this.userAgent == null || this.userAgent.isEmpty()) this.userAgent = "ptest-server"; String protocolVersion = (String) cfg.getOption(CFG_OPT_HTTP_PROTOCOL_VERSION); if (protocolVersion != null && !protocolVersion.isEmpty()) { if (protocolVersion.equalsIgnoreCase("0.9")) this.httpVersion = HttpVersion.HTTP_0_9; else if (protocolVersion.equalsIgnoreCase("1.0")) this.httpVersion = HttpVersion.HTTP_1_0; else if (protocolVersion.equalsIgnoreCase("1.1")) this.httpVersion = HttpVersion.HTTP_1_1; else throw new TSPlanActivityExecutionException("Failed to parse http protocol version '" + protocolVersion + "'. Valid value: 0.9, 1.0 and 1.1"); } this.contentChartset = (String) cfg.getOption(CFG_OPT_CONTENT_CHARSET); if (this.contentChartset == null || this.contentChartset.isEmpty()) this.contentChartset = "UTF-8"; String expectContStr = (String) cfg.getOption(CFG_OPT_EXPECT_CONTINUE); if (expectContStr != null && !expectContStr.isEmpty()) { this.expectContinue = Boolean.parseBoolean(expectContStr.trim()); } HttpProtocolParams.setUserAgent(httpParameters, userAgent); HttpProtocolParams.setVersion(httpParameters, httpVersion); HttpProtocolParams.setContentCharset(httpParameters, contentChartset); HttpProtocolParams.setUseExpectContinue(httpParameters, expectContinue); String httpProcStr = (String) cfg.getOption(CFG_OPT_HTTP_REQUEST_PROCESSORS); if (httpProcStr != null && !httpProcStr.isEmpty()) { List<HttpRequestInterceptor> interceptors = new ArrayList<HttpRequestInterceptor>(); String[] procClasses = httpProcStr.split(","); if (procClasses != null && procClasses.length > 0) { for (int i = 0; i < procClasses.length; i++) { try { Class<?> clazz = Class.forName(procClasses[i]); interceptors.add((HttpRequestInterceptor) clazz.newInstance()); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", httpRequestInterceptor=" + procClasses[i] + "]"); } catch (Exception e) { throw new TSPlanActivityExecutionException("Failed to instantiate http interceptor '" + procClasses[i] + "' for activity '" + getName() + "'. Error: " + e.getMessage()); } } } this.httpRequestResponseProcessor = new ImmutableHttpProcessor( (HttpRequestInterceptor[]) interceptors.toArray(EMPTY_HTTP_REQUEST_INTERCEPTOR_ARRAY)); this.hasRequestResponseProcessors = true; } this.method = (String) cfg.getOption(CFG_OPT_METHOD); if (method == null || method.isEmpty()) this.method = "GET"; if (!method.equalsIgnoreCase("get") && !method.equalsIgnoreCase("post")) throw new TSPlanActivityExecutionException( "Invalid method '" + method + "' found for activity '" + getName() + "'"); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", method=" + method + ", user-agent=" + userAgent + ", httpVersion=" + httpVersion + ", contentCharset=" + contentChartset + ", expectContinue=" + expectContinue + "]"); ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // fetch proxy settings this.proxyUrl = (String) cfg.getOption(CFG_OPT_PROXY_URL); String proxyPortStr = (String) cfg.getOption(CFG_OPT_PROXY_PORT); if (proxyPortStr != null && !proxyPortStr.isEmpty()) { try { this.proxyPort = Integer.parseInt(proxyPortStr.trim()); } catch (NumberFormatException e) { throw new TSPlanActivityExecutionException( "Failed to parse expected numerical value for config option '" + CFG_OPT_PROXY_PORT + "' for activity '" + getName() + "'"); } } this.proxyUser = (String) cfg.getOption(CFG_OPT_PROXY_USER); this.proxyPassword = (String) cfg.getOption(CFG_OPT_PROXY_PASSWORD); if (proxyUrl != null && !proxyUrl.isEmpty()) { if (proxyPort > 0) this.proxyHost = new HttpHost(proxyUrl, proxyPort); else this.proxyHost = new HttpHost(proxyUrl); } if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", proxyUrl=" + proxyUrl + ", proxyPort=" + proxyPort + ", proxyUser=" + proxyUser + "]"); ///////////////////////////////////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////////////////////// // // fetch request parameters // // // unfortunately we must step through the whole set of keys ... // for(String key : cfg.getOptions().keySet()) { // if(key.startsWith(REQUEST_PARAM_OPTION_PREFIX)) { // String value = (String)cfg.getOption(key); // String requestParameterName = key.substring(REQUEST_PARAM_OPTION_PREFIX.length(), key.length()); // httpParameters.setParameter(requestParameterName, value); // if(logger.isDebugEnabled()) // logger.debug("activity[name="+getName()+", id="+getId()+", requestParameter="+requestParameterName+", value="+value+"]"); // } // } // // ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // configure scheme registry and initialize http client SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", registeredSchemes={http, https}]"); ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager( schemeRegistry); threadSafeClientConnectionManager.setMaxTotal(maxConnections); threadSafeClientConnectionManager.setDefaultMaxPerRoute(maxConnections); this.httpClient = new DefaultHttpClient(threadSafeClientConnectionManager); if (this.basicAuthUsername != null && !this.basicAuthUsername.trim().isEmpty() && this.basicAuthPassword != null && !this.basicAuthPassword.trim().isEmpty()) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(this.basicAuthUsername, this.basicAuthPassword); AuthScope authScope = null; if (basicAuthHostScope != null && !basicAuthHostScope.isEmpty() && basicAuthPortScope > 0) { authScope = new AuthScope(basicAuthHostScope, basicAuthPortScope); } else { authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT); } this.httpClient.getCredentialsProvider().setCredentials(authScope, creds); if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", credentials=(" + creds.getUserName() + ", " + creds.getPassword() + "), authScope=(" + authScope.getHost() + ":" + authScope.getPort() + ")]"); } if (logger.isDebugEnabled()) logger.debug("activity[name=" + getName() + ", id=" + getId() + ", threadSafeClientConnectionManager=initialized]"); }