/** * Closes idle connections. */ public synchronized void run() { while (!shutdown) { Iterator iter = connectionManagers.iterator(); while (iter.hasNext()) { HttpConnectionManager connectionManager = (HttpConnectionManager) iter.next(); handleCloseIdleConnections(connectionManager); } try { this.wait(timeoutInterval); } catch (InterruptedException e) { } } // clear out the connection managers now that we're shutdown this.connectionManagers.clear(); }
@Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); for (HttpConnectionManager m : connMgr) { // Close expired connections // m.closeExpiredConnections(); // Optionally, close connections // that have been idle longer than 30 sec m.closeIdleConnections(30000); } } } } catch (InterruptedException ex) { // terminate } }
private void initConfigurationContext() throws Exception { HttpConnectionManager multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager(); HttpClient httpClient = new HttpClient(multiThreadedHttpConnectionManager); File configFile = new File(DEFAULT_AXIS2_XML); if (!configFile.exists()) { configurationContext = ConfigurationContextFactory.createDefaultConfigurationContext(); configurationContext.setProperty(HTTPConstants.DEFAULT_MAX_CONNECTIONS_PER_HOST, MAX_CONNECTIONS_PER_HOST); } else { configurationContext = ConfigurationContextFactory. createConfigurationContextFromFileSystem(DEFAULT_CLIENT_REPO, DEFAULT_AXIS2_XML); } configurationContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient); configurationContext.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE); Map<String, TransportOutDescription> transportsOut = configurationContext.getAxisConfiguration().getTransportsOut(); for (TransportOutDescription transportOutDescription : transportsOut.values()) { if (Constants.TRANSPORT_HTTP.equals(transportOutDescription.getName()) || Constants.TRANSPORT_HTTPS.equals(transportOutDescription.getName())) { transportOutDescription.getSender().init(configurationContext, transportOutDescription); } } }
/** * A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs * * @param user * can be NULL * @param password * can be NULL * @return HttpClient */ public static HttpClient getHttpClientInstance(String user, String password) { HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionParams params = connectionManager.getParams(); // wait max 10 seconds to establish connection params.setConnectionTimeout(10000); // a read() call on the InputStream associated with this Socket // will block for only this amount params.setSoTimeout(10000); HttpClient c = new HttpClient(connectionManager); // use basic authentication if available if (user != null && user.length() > 0) { AuthScope authScope = new AuthScope(null, -1, null); Credentials credentials = new UsernamePasswordCredentials(user, password); c.getState().setCredentials(authScope, credentials); } return c; }
/** * Closes idle connections. */ public synchronized void run() { while (!shutdown) { Iterator iter = connectionManagers.iterator(); while (iter.hasNext()) { HttpConnectionManager connectionManager = (HttpConnectionManager) iter.next(); connectionManager.closeIdleConnections(connectionTimeout); } try { this.wait(timeoutInterval); } catch (InterruptedException e) { } } // clear out the connection managers now that we're shutdown this.connectionManagers.clear(); }
@Override public void close() { if(httpClient != null) { HttpConnectionManager connectionManager = httpClient.getHttpConnectionManager(); if(connectionManager instanceof MultiThreadedHttpConnectionManager) { ((MultiThreadedHttpConnectionManager)connectionManager).shutdown(); } } }
private IdleConnectionCloser(HttpConnectionManager httpConnectionManager) { super("FastServletProxyFactory.IdleConnectionCloser"); this.httpConnectionManager = httpConnectionManager; this.setName("IdleConnectionCloser"); this.setDaemon(true); this.setPriority(Thread.MIN_PRIORITY); }
public static void logCurrentHttpConnection(HttpClient httpClient, HostConfiguration hostConfiguration, HttpPool poolMode) { if (Engine.logEngine.isInfoEnabled() && httpClient != null) { if (poolMode == HttpPool.no) { Engine.logEngine.info("(HttpUtils) Use a not pooled HTTP connection for " + hostConfiguration.getHost()); } else { HttpConnectionManager httpConnectionManager = httpClient.getHttpConnectionManager(); if (httpConnectionManager != null && httpConnectionManager instanceof MultiThreadedHttpConnectionManager) { MultiThreadedHttpConnectionManager mtHttpConnectionManager = (MultiThreadedHttpConnectionManager) httpConnectionManager; int connections = mtHttpConnectionManager.getConnectionsInPool(); int connectionsForHost = mtHttpConnectionManager.getConnectionsInPool(hostConfiguration); Engine.logEngine.info("(HttpUtils) Use a " + poolMode.name() + " pool with " + connections + " HTTP connections, " + connectionsForHost + " for " + hostConfiguration.getHost() + "; Getting one ... [for instance " + httpClient.hashCode() + "]"); } } } }
/** * Removes the connection manager from this class. The idle connections from the connection * manager will no longer be automatically closed by this class. * * @param connectionManager The connection manager to remove */ public synchronized void removeConnectionManager(HttpConnectionManager connectionManager) { if (shutdown) { throw new IllegalStateException("IdleConnectionTimeoutThread has been shutdown"); } this.connectionManagers.remove(connectionManager); }
/** * 使用独立的连接管理器。 * @param connectionManager 链接管理器 * @return */ public HttpReq httpConnectionManager(HttpConnectionManager connectionManager) { httpConnectionManager = connectionManager; externalConnectionManager = true; return this; }
public void RequestConnectionHttp(String url, String user, String pass, int timeout) throws Exception { HttpClient client = new HttpClient(); HttpConnectionManager hcm = client.getHttpConnectionManager(); HttpConnectionManagerParams hcmParam = hcm.getParams(); hcmParam.setConnectionTimeout(timeout + 1000); hcm.setParams(hcmParam); client.setHttpConnectionManager(hcm); if (user != null && pass != null) { client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass)); } GetMethod get = new GetMethod(url); get.setDoAuthentication(true); try { int status = client.executeMethod(get); if (status != 200) { System.out.println(status + "\n" + get.getResponseBodyAsString()); throw new Exception("Failed: status=" + status); } setLastcrres("OK"); } catch (Exception e) { setLastcrres(e.getMessage()); System.out.println("HTTP CR OOPS: " + e.getMessage() + "\n"); throw e; } finally { get.releaseConnection(); } }
/** {@inheritDoc} */ @Override public boolean interrupt() { HttpClient client = savedClient; if (client != null) { savedClient = null; // TODO - not sure this is the best method final HttpConnectionManager httpConnectionManager = client.getHttpConnectionManager(); if (httpConnectionManager instanceof SimpleHttpConnectionManager) {// Should be true ((SimpleHttpConnectionManager)httpConnectionManager).shutdown(); } } return client != null; }
@Test public void testHttpGetWithoutConversion() throws Exception { // This is needed as by default there are 2 parallel // connections to some host and there is nothing that // closes the http connection here. // Need to set the httpConnectionManager HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); httpConnectionManager.getParams().setDefaultMaxConnectionsPerHost(5); context.getComponent("http", HttpComponent.class).setHttpConnectionManager(httpConnectionManager); String endpointName = "seda:withoutConversion?concurrentConsumers=5"; sendMessagesTo(endpointName, 5); }
public HttpEndpoint(String endPointURI, HttpComponent component, URI httpURI, HttpClientParams clientParams, HttpConnectionManager httpConnectionManager, HttpClientConfigurer clientConfigurer) throws URISyntaxException { super(endPointURI, component, httpURI); this.clientParams = clientParams; this.httpClientConfigurer = clientConfigurer; this.httpConnectionManager = httpConnectionManager; }
public OAuthTokenValidationStubFactory(String url, String adminUsername, String adminPassword, Properties properties) { this.validateUrl(url); this.url = url; this.validateCredentials(adminUsername, adminPassword); this.basicAuthHeader = new String(Base64.encodeBase64((adminUsername + ":" + adminPassword).getBytes())); HttpConnectionManager connectionManager = this.createConnectionManager(properties); this.httpClient = new HttpClient(connectionManager); }
/** * Creates an instance of MultiThreadedHttpConnectionManager using HttpClient 3.x APIs * * @param properties Properties to configure MultiThreadedHttpConnectionManager * @return An instance of properly configured MultiThreadedHttpConnectionManager */ private HttpConnectionManager createConnectionManager(Properties properties) { HttpConnectionManagerParams params = new HttpConnectionManagerParams(); if (properties == null || properties.isEmpty()) { throw new IllegalArgumentException("Parameters required to initialize HttpClient instances " + "associated with OAuth token validation service stub are not provided"); } String maxConnectionsPerHostParam = properties.getProperty("MaxConnectionsPerHost"); if (maxConnectionsPerHostParam == null || maxConnectionsPerHostParam.isEmpty()) { if (log.isDebugEnabled()) { log.debug("MaxConnectionsPerHost parameter is not explicitly defined. Therefore, the default, " + "which is 2, will be used"); } } else { params.setDefaultMaxConnectionsPerHost(Integer.parseInt(maxConnectionsPerHostParam)); } String maxTotalConnectionsParam = properties.getProperty("MaxTotalConnections"); if (maxTotalConnectionsParam == null || maxTotalConnectionsParam.isEmpty()) { if (log.isDebugEnabled()) { log.debug("MaxTotalConnections parameter is not explicitly defined. Therefore, the default, " + "which is 10, will be used"); } } else { params.setMaxTotalConnections(Integer.parseInt(maxTotalConnectionsParam)); } HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.setParams(params); return connectionManager; }
public HttpClient getUploadDownloadClient(boolean forProxy) { int index = forProxy ? 1 : 0; if (myUploadDownloadClients[index] == null) { HttpConnectionManager connManager = new MultiThreadedHttpConnectionManager(); myUploadDownloadClients[index] = new HttpClient(connManager); HttpClientParams clientParams = new HttpClientParams(); // Set the default timeout in case we have a connection pool starvation to 30sec clientParams.setConnectionManagerTimeout(30000); myUploadDownloadClients[index].setParams(clientParams); } return myUploadDownloadClients[index]; }
/** * Constructor */ public OwnCloudClient(Uri baseUri, HttpConnectionManager connectionMgr) { super(connectionMgr); if (baseUri == null) { throw new IllegalArgumentException("Parameter 'baseUri' cannot be NULL"); } mBaseUri = baseUri; mInstanceNumber = sIntanceCounter++; Log_OC.d(TAG + " #" + mInstanceNumber, "Creating OwnCloudClient"); String userAgent = OwnCloudClientManagerFactory.getUserAgent(); getParams().setParameter(HttpMethodParams.USER_AGENT, userAgent); getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); getParams().setCookiePolicy( CookiePolicy.IGNORE_COOKIES); getParams().setParameter( PARAM_SINGLE_COOKIE_HEADER, // to avoid problems with some web servers PARAM_SINGLE_COOKIE_HEADER_VALUE); applyProxySettings(); clearCredentials(); }
/** * Shutdown hook that closes the underlying {@link HttpConnectionManager}'s connection pool, if any. */ public void destroy() { HttpConnectionManager connectionManager = getHttpClient().getHttpConnectionManager(); if (connectionManager instanceof MultiThreadedHttpConnectionManager) { ((MultiThreadedHttpConnectionManager) connectionManager).shutdown(); } }
public void cancel(HttpMethod method) { HttpClient client = null; HttpConnectionManager cmanager = client.getHttpConnectionManager(); for (IProgressMonitor m : cmap.keySet()) { if (m.isCanceled()) { method.abort(); cmap.remove(m); } } }
/** @since 2.0 */ @Override public void closeCommunicationLink() { if (getClient() != null) { HttpConnectionManager mgr = getClient().getHttpConnectionManager(); if (mgr instanceof MultiThreadedHttpConnectionManager) { ((MultiThreadedHttpConnectionManager) mgr).shutdown(); } } }
public PartnerService(Definition wsdlDefinition, QName serviceName, String portName, ConfigurationContext clientConfigCtx, ProcessConf pconf, HttpConnectionManager connManager) throws AxisFault { this.wsdlDefinition = wsdlDefinition; this.serviceName = serviceName; this.portName = portName; this.clientConfigCtx = clientConfigCtx; this.processConfiguration = pconf; inferBindingInformation(); this.clientConfigCtx.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, connManager); this.clientConfigCtx.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "false"); Element eprEle = BPELProcessProxy.genEPRfromWSDL(this.wsdlDefinition, this.serviceName, this.portName); if (eprEle == null) { throw new IllegalArgumentException("Service Port definition not found for service:" + this.serviceName + " and port:" + this.portName); } this.endpointReference = EndpointFactory.convertToWSA( BPELProcessProxy.createServiceRef(eprEle)); endpointUrl = endpointReference.getUrl(); initUEP(); if (log.isDebugEnabled()) { String msg = "Process ID => " + this.processConfiguration.getProcessId() + " Deployer => " + this.processConfiguration.getDeployer(); log.debug(msg); } }
/** * @param args * @throws IOException * @throws HttpException */ public static void main(String[] args) throws HttpException, IOException { // HttpConnectionManager connectionManager = new SimpleHttpConnectionManager(); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); // hcmp = new HttpConnectionManagerParams(); // hcmp.setStaleCheckingEnabled(true); // int totConn = args.getNumberOfThreadsPrStep()*args.getNumberOfSteps(); // hcmp.setMaxTotalConnections(totConn); HttpClient client = new HttpClient(connectionManager); // client.getParams().setParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, new Boolean(false)); client.getParams().setParameter(HttpClientParams.USE_EXPECT_CONTINUE, new Boolean(true)); client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 2000); // String url = "http://localhost:8082/xapsws/services/xAPSWS"; String url = "http://pingcom.xaps-hosting.net/xapsws/services/xAPSWS"; String xml = retrieveXmlFromFile("perl-client-test-modified.xml"); // String xml = retrieveXmlFromFile("owera-java-client-test.xml"); PostMethod pm = new PostMethod(url); if (xml != null) { RequestEntity requestEntity = new StringRequestEntity(xml, "text/xml", "ISO-8859-1"); pm.setRequestEntity(requestEntity); pm.setRequestHeader(new Header("SOAPAction", "http://http://xapsws.owera.com/xapsws/soap")); } int statusCode = client.executeMethod(pm); Reader reader = new InputStreamReader(pm.getResponseBodyAsStream(), pm.getResponseCharSet()); BufferedReader br = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); while (true) { String line = br.readLine(); if (line == null) break; sb.append(line); } String response = sb.toString(); System.out.println("Status-code: " + statusCode); System.out.println("Response: " + prettyFormat(response)); }
/** * Shutdown hook that closes the underlying {@link HttpConnectionManager}'s * connection pool, if any. */ public void destroy() { HttpConnectionManager connectionManager = getHttpClient().getHttpConnectionManager(); if (connectionManager instanceof MultiThreadedHttpConnectionManager) { ((MultiThreadedHttpConnectionManager) connectionManager).shutdown(); } }
public void connectWebDAVServer(String strUri, int intMaxConnections, String strUserId, String strPassword) { HostConfiguration hostConfig = new HostConfiguration(); hostConfig.setHost(strUri); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setMaxConnectionsPerHost(hostConfig, intMaxConnections); connectionManager.setParams(params); this.client = new HttpClient(connectionManager); client.setHostConfiguration(hostConfig); Credentials creds = new UsernamePasswordCredentials(strUserId, strPassword); client.getState().setCredentials(AuthScope.ANY, creds); }
/** * This created httpclient pool that can be used to connect to external entity. This connection can be configured * via broker.xml by setting up the required http connection parameters. * @return an instance of HttpClient that is configured with MultiThreadedHttpConnectionManager */ private HttpClient createHttpClient() { HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setDefaultMaxConnectionsPerHost(config.getMaximumHttpConnectionPerHost()); params.setMaxTotalConnections(config.getMaximumTotalHttpConnection()); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); connectionManager.setParams(params); return new HttpClient(connectionManager); }
/** * @param executor executor service to use for making parallel requests * @param connectionManager http connection manager to use. */ public MultiGetRequest(@Nonnull Executor executor, @Nonnull HttpConnectionManager connectionManager) { Preconditions.checkNotNull(executor); Preconditions.checkNotNull(connectionManager); this.executor = executor; this.connectionManager = connectionManager; }
public void closeCommunicationLink() { if (getClient() != null) { HttpConnectionManager mgr = getClient().getHttpConnectionManager(); if (mgr instanceof ThreadLocalHttpConnectionManager) { ((ThreadLocalHttpConnectionManager) mgr).releaseLocalConnection(); } if (mgr instanceof MultiThreadedHttpConnectionManager) { ((MultiThreadedHttpConnectionManager) mgr).shutdown(); } } }
private static boolean isGovCloud() /* */ { /* 486 */ if (ec2MetaDataAz != null) { /* 487 */ return ec2MetaDataAz.startsWith("us-gov-west-1"); /* */ } /* */ /* 492 */ String hostname = getHostName(); /* 493 */ int timeout = hostname.startsWith("ip-") ? 30000 : 5000; /* 494 */ GetMethod getMethod = new GetMethod("http://169.254.169.254/latest/meta-data/placement/availability-zone"); /* */ try { /* 496 */ HttpConnectionManager manager = new SimpleHttpConnectionManager(); /* 497 */ HttpConnectionManagerParams params = manager.getParams(); /* */ /* 499 */ params.setConnectionTimeout(timeout); /* */ /* 501 */ params.setSoTimeout(timeout); /* 502 */ HttpClient httpClient = new HttpClient(manager); /* 503 */ int status = httpClient.executeMethod(getMethod); /* 504 */ if ((status < 200) || (status > 299)) { /* 505 */ LOG.info("error status code" + status + " GET " + "http://169.254.169.254/latest/meta-data/placement/availability-zone"); /* */ } else { /* 507 */ ec2MetaDataAz = getMethod.getResponseBodyAsString().trim(); /* 508 */ LOG.info("GET http://169.254.169.254/latest/meta-data/placement/availability-zone result: " + ec2MetaDataAz); /* 509 */ return ec2MetaDataAz.startsWith("us-gov-west-1"); /* */ } /* */ } catch (Exception e) { /* 512 */ LOG.info("GET http://169.254.169.254/latest/meta-data/placement/availability-zone exception ", e); /* */ } finally { /* 514 */ getMethod.releaseConnection(); /* */ } /* 516 */ return false; /* */ }
/** * 通过http的post方式请求数据 connectionTimeOut:建立连接的超时时间,soTimeOut:等待返回结果的超时时间 * @param urlString * @param params * @param encode * @param connectionTimeOut * @param soTimeOut * @return * @throws IOException * @throws HttpException * @throws Exception * @Author YHJ create at 2014年5月14日 下午4:36:02 */ public static String doPost(String urlString, Map<String, String> params) throws HttpException, IOException { PostMethod method = new PostMethod(urlString); HttpClient client = null; try { Set<String> keys = params.keySet(); NameValuePair[] values = new NameValuePair[keys.size()]; int i = 0; for (String key : keys) { NameValuePair v = new NameValuePair(); v.setName(key); v.setValue(params.get(key)); values[i] = v; i++; } client = new HttpClient(); client.getHostConfiguration().setHost(urlString, 80, "http"); client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);// 建立连接的超时时间 client.getHttpConnectionManager().getParams().setSoTimeout(30000);// 等待请求结果的超时时间 if (StringUtils.isNotBlank(encode)) client.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, encode); method.setRequestBody(values); // 使用 POST 方式提交数据 int state = client.executeMethod(method); //返回的状态 if(state != HttpStatus.SC_OK){ throw new RuntimeException("HttpStatus is "+state); } return inputStreamToString(method.getResponseBodyAsStream(), encode); } finally { //releaseConnection方法不能关闭socket连接 //使用SimpleHttpConnectionManager的shutdown方法强制关闭 method.releaseConnection(); if (client != null ) { HttpConnectionManager manager = client.getHttpConnectionManager(); if (manager instanceof SimpleHttpConnectionManager) { SimpleHttpConnectionManager tmp = (SimpleHttpConnectionManager)manager; tmp.shutdown(); } } } }
public HttpClientCAS(HttpClientParams params, HttpConnectionManager httpConnectionManager) { super(params, httpConnectionManager); init(); }
public HttpClientCAS(HttpConnectionManager httpConnectionManager) { super(httpConnectionManager); init(); }
public HttpConnectionManager getHttpConnectionManager() { return httpConnectionManager; }
/** * To use a custom HttpConnectionManager to manage connections */ public void setHttpConnectionManager(HttpConnectionManager httpConnectionManager) { this.httpConnectionManager = httpConnectionManager; }
public HttpEndpoint(String endPointURI, HttpComponent component, URI httpURI, HttpConnectionManager httpConnectionManager) throws URISyntaxException { this(endPointURI, component, httpURI, new HttpClientParams(), httpConnectionManager, null); }