Example usage for org.apache.commons.httpclient.params HttpClientParams setConnectionManagerTimeout

List of usage examples for org.apache.commons.httpclient.params HttpClientParams setConnectionManagerTimeout

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpClientParams setConnectionManagerTimeout.

Prototype

public void setConnectionManagerTimeout(long paramLong) 

Source Link

Usage

From source file:com.netsteadfast.greenstep.util.ApplicationSiteUtils.java

private static boolean checkTestConnection(String host, String contextPath, HttpServletRequest request) {
    boolean test = false;
    String basePath = request.getScheme() + "://" + host + "/" + contextPath;
    String urlStr = basePath + "/pages/system/testJsonResult.action";
    try {//from   w w w  .  j  ava  2s  .c o m
        logger.info("checkTestConnection , url=" + urlStr);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(urlStr);
        HttpClientParams params = new HttpClientParams();
        params.setConnectionManagerTimeout(TEST_JSON_HTTP_TIMEOUT);
        client.setParams(params);
        client.executeMethod(method);
        byte[] responseBody = method.getResponseBody();
        if (null == responseBody) {
            test = false;
            return test;
        }
        String content = new String(responseBody, Constants.BASE_ENCODING);
        ObjectMapper mapper = new ObjectMapper();
        @SuppressWarnings("unchecked")
        Map<String, Object> dataMap = (Map<String, Object>) mapper.readValue(content, HashMap.class);
        if (YesNo.YES.equals(dataMap.get("success"))) {
            test = true;
        }
    } catch (JsonParseException e) {
        logger.error(e.getMessage().toString());
    } catch (JsonMappingException e) {
        logger.error(e.getMessage().toString());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (!test) {
            logger.warn("checkTestConnection : " + String.valueOf(test));
        } else {
            logger.info("checkTestConnection : " + String.valueOf(test));
        }
    }
    return test;
}

From source file:com.calclab.emite.xtesting.services.HttpConnector.java

private Runnable createSendAction(final String httpBase, final String xml, final ConnectorCallback callback) {
    return new Runnable() {
        public void run() {
            final String id = HttpConnectorID.getNext();
            debug("Connector [{0}] send: {1}", id, xml);
            final HttpClientParams params = new HttpClientParams();
            params.setConnectionManagerTimeout(10000);
            final HttpClient client = new HttpClient(params);
            int status = 0;
            String response = null;
            final PostMethod post = new PostMethod(httpBase);

            try {
                post.setRequestEntity(new StringRequestEntity(xml, "text/xml", "utf-8"));
                System.out.println("SENDING: " + xml);
                status = client.executeMethod(post);
                response = post.getResponseBodyAsString();
            } catch (final Exception e) {
                callback.onError(xml, e);
                e.printStackTrace();/*from   ww w. j a  v a  2  s  . c  o m*/
            } finally {
                post.releaseConnection();
            }

            receiveService.execute(createResponseAction(xml, callback, id, status, response));
        }
    };
}

From source file:com.liferay.portlet.rss.util.RSSWebCacheItem.java

public Object convert(String key) throws WebCacheException {
    SyndFeed feed = null;//from  ww w.  j  ava2s .c  om

    try {

        // com.liferay.portal.kernel.util.HttpUtil will break the connection
        // if it spends more than 5 seconds looking up a location. However,
        // German umlauts do not get encoded correctly. This may be a bug
        // with commons-httpclient or with how FeedParser uses
        // java.io.Reader.

        // Use http://xml.newsisfree.com/feeds/29/629.xml and
        // http://test.domosoft.com/up/RSS to test if German umlauts show
        // up correctly.

        /*Reader reader = new StringReader(
           new String(HttpUtil.URLtoByteArray(_url)));
                
        channel = FeedParser.parse(builder, reader);*/

        HttpImpl httpImpl = (HttpImpl) HttpUtil.getHttp();

        HostConfiguration hostConfiguration = httpImpl.getHostConfiguration(_url);

        HttpClient httpClient = httpImpl.getClient(hostConfiguration);

        httpImpl.proxifyState(httpClient.getState(), hostConfiguration);

        HttpClientParams httpClientParams = httpClient.getParams();

        httpClientParams.setConnectionManagerTimeout(PropsValues.RSS_CONNECTION_TIMEOUT);
        httpClientParams.setSoTimeout(PropsValues.RSS_CONNECTION_TIMEOUT);

        GetMethod getMethod = new GetMethod(_url);

        httpClient.executeMethod(hostConfiguration, getMethod);

        SyndFeedInput input = new SyndFeedInput();

        feed = input.build(new XmlReader(getMethod.getResponseBodyAsStream()));
    } catch (Exception e) {
        throw new WebCacheException(_url + " " + e.toString());
    }

    return feed;
}

From source file:com.calclab.emite.j2se.services.HttpConnector.java

private Runnable createSendAction(final String httpBase, final String xml, final ConnectorCallback callback) {
    return new Runnable() {
        public void run() {
            final String id = HttpConnectorID.getNext();
            Logger.debug("Connector [{0}] send: {1}", id, xml);
            final HttpClientParams params = new HttpClientParams();
            params.setConnectionManagerTimeout(10000);
            final HttpClient client = new HttpClient(params);
            int status = 0;
            String response = null;
            final PostMethod post = new PostMethod(httpBase);

            try {
                post.setRequestEntity(new StringRequestEntity(xml, "text/xml", "utf-8"));
                System.out.println("SENDING: " + xml);
                status = client.executeMethod(post);
                response = post.getResponseBodyAsString();
            } catch (final Exception e) {
                callback.onError(xml, e);
                e.printStackTrace();/*from www.  j  av a2s  .c o m*/
            } finally {
                post.releaseConnection();
            }

            receiveService.execute(createResponseAction(xml, callback, id, status, response));
        }
    };
}

From source file:com.gisgraphy.rest.RestClient.java

/**
        /*from   ww  w. ja v  a 2  s.co m*/
        
/**
 * @param multiThreadedHttpConnectionManager
 *                The
 * @link {@link MultiThreadedHttpConnectionManager} that the fulltext search
 *       engine will use
 * @throws RestClientException
 *                 If an error occured
 */
public RestClient(MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager)
        throws RestClientException {
    if (multiThreadedHttpConnectionManager == null) {
        throw new RestClientException("multiThreadedHttpConnectionManager can not be null");
    }
    this.httpClient = new HttpClient(multiThreadedHttpConnectionManager);
    HttpClientParams httpClientParams = new HttpClientParams();
    httpClientParams.setHttpElementCharset("utf8");
    httpClientParams.setConnectionManagerTimeout(15000);
    httpClientParams.setParameter(HttpMethodParams.USER_AGENT, ClientConfig.CLIENT_USER_AGENT);
    httpClient.setParams(httpClientParams);

    if (this.httpClient == null) {
        throw new RestClientException(
                "Can not instanciate http client with multiThreadedHttpConnectionManager : "
                        + multiThreadedHttpConnectionManager);
    }
}

From source file:com.isencia.passerelle.model.util.RESTFacade.java

public RESTFacade(int connectionTimeout, int socketTimeout) {
    httpClient = new HttpClient();
    HttpClientParams params = new HttpClientParams();
    params.setSoTimeout(socketTimeout);/*from   w  w  w .j  av a  2  s  . c o m*/
    params.setConnectionManagerTimeout(connectionTimeout);
    httpClient.setParams(params);
}

From source file:edu.utah.further.core.ws.HttpClientTemplate.java

/**
 * Private {@link HttpClient} initialization.
 *///from   w  ww  .  j  a va 2  s.  c om
@PostConstruct
private final void afterPropertiesSet() {
    // Client is higher in the hierarchy than manager so set the parameters here
    final HttpClientParams clientParams = new HttpClientParams();
    clientParams.setConnectionManagerClass(connectionManager.getClass());
    clientParams.setConnectionManagerTimeout(connectionTimeout);
    clientParams.setSoTimeout(readTimeout);
    clientParams.setParameter("http.connection.timeout", new Integer(connectionTimeout));
    // A retry handler for when a connection fails
    clientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() {
        @Override
        public boolean retryMethod(final HttpMethod method, final IOException exception,
                final int executionCount) {
            if (executionCount >= retryCount) {
                // Do not retry if over max retry count
                return false;
            }
            if (instanceOf(exception, NoHttpResponseException.class)) {
                // Retry if the server dropped connection on us
                return true;
            }
            if (instanceOf(exception, SocketException.class)) {
                // Retry if the server reset connection on us
                return true;
            }
            if (instanceOf(exception, SocketTimeoutException.class)) {
                // Retry if the read timed out
                return true;
            }
            if (!method.isRequestSent()) {
                // Retry if the request has not been sent fully or
                // if it's OK to retry methods that have been sent
                return true;
            }
            // otherwise do not retry
            return false;
        }
    });
    httpClient.setParams(clientParams);

    final HttpConnectionManagerParams connectionManagerParams = connectionManager.getParams();
    connectionManagerParams.setDefaultMaxConnectionsPerHost(maxConnectionsPerHost);
    connectionManager.setParams(connectionManagerParams);
}

From source file:de.ingrid.mdek.quartz.jobs.URLValidatorJob.java

@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {

    ExecutorService executorService = Executors.newFixedThreadPool(NUM_THREADS);
    JobDataMap mergedJobDataMap = jobExecutionContext.getMergedJobDataMap();
    Map<String, URLState> urlMap = (Map<String, URLState>) mergedJobDataMap.get(URL_MAP);
    List<URLValidator> validatorTasks = new ArrayList<URLValidator>(urlMap.size());

    Map<String, URLState> capabilitiesMap = (Map<String, URLState>) mergedJobDataMap.get(CAP_URL_MAP);
    List<CapabilitiesValidator> capabilitiesValidatorTasks = new ArrayList<CapabilitiesValidator>(
            capabilitiesMap.size());/*  ww  w .ja  v a  2 s .  co  m*/

    HttpClientParams httpClientParams = new HttpClientParams();
    httpClientParams.setConnectionManagerTimeout(0);
    httpClientParams.setSoTimeout(SOCKET_TIMEOUT);
    HttpConnectionParams httpParams = new HttpConnectionParams();
    httpParams.setConnectionTimeout(CONNECTION_TIMEOUT);
    httpClientParams.setDefaults(httpParams);
    HttpClient httpClient = new HttpClient(httpClientParams, new MultiThreadedHttpConnectionManager());
    if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) {
        httpClient.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"),
                Integer.parseInt(System.getProperty("http.proxyPort")));
    }
    for (URLState urlState : urlMap.values()) {
        validatorTasks.add(new URLValidator(httpClient, urlState));
    }
    for (URLState urlState : capabilitiesMap.values()) {
        capabilitiesValidatorTasks.add(new CapabilitiesValidator(httpClient, urlState));
    }

    log.debug("Starting url validation...");
    long startTime = System.currentTimeMillis();
    List<Future<URLState>> resultFutureList = new ArrayList<Future<URLState>>();
    for (URLValidator validator : validatorTasks) {
        resultFutureList.add(executorService.submit(validator));
    }
    for (CapabilitiesValidator validator : capabilitiesValidatorTasks) {
        resultFutureList.add(executorService.submit(validator));
    }

    for (Future<URLState> future : resultFutureList) {
        try {
            if (!cancelJob) {
                future.get();

            } else {
                log.debug("forcing shutdown of executor service...");
                executorService.shutdownNow();
                break;
            }

        } catch (Exception ex) {
            log.debug("Exception while fetching result from future.", ex);
        }
    }
    long endTime = System.currentTimeMillis();
    log.debug("URL Validation took " + (endTime - startTime) + " ms.");

    executorService.shutdown();

    // Only store if job was not cancelled
    if (!cancelJob) {
        Map<String, List<URLObjectReference>> map = new HashMap<String, List<URLObjectReference>>();
        map.put(MdekKeys.URL_RESULT, (List<URLObjectReference>) mergedJobDataMap.get(URL_OBJECT_REFERENCES));
        map.put(MdekKeys.CAP_RESULT, (List<URLObjectReference>) mergedJobDataMap.get(CAPABILITIES_REFERENCES));
        jobExecutionContext.setResult(map);
    }
}

From source file:com.dtolabs.rundeck.core.common.impl.URLFileUpdater.java

private void updateHTTPUrl(final File destinationFile) throws FileUpdaterException {
    if (null == interaction) {
        interaction = new normalInteraction();
    }/* w w  w.  ja v  a 2  s  . c o  m*/
    final Properties cacheProperties;
    if (useCaching) {
        cacheProperties = loadCacheData(cacheMetadata);
        contentTypeFromCache(cacheProperties);
    } else {
        cacheProperties = null;
    }

    final HttpClientParams params = new HttpClientParams();
    if (timeout > 0) {
        params.setConnectionManagerTimeout(timeout * 1000);
        params.setSoTimeout(timeout * 1000);
    }

    final HttpClient client = new HttpClient(params);
    AuthScope authscope = null;
    UsernamePasswordCredentials cred = null;
    boolean doauth = false;
    String cleanUrl = url.toExternalForm().replaceAll("^(https?://)([^:@/]+):[^@/]*@", "$1$2:****@");
    String urlToUse = url.toExternalForm();
    try {
        if (null != url.getUserInfo()) {
            doauth = true;
            authscope = new AuthScope(url.getHost(), url.getPort() > 0 ? url.getPort() : url.getDefaultPort(),
                    AuthScope.ANY_REALM, "BASIC");
            cred = new UsernamePasswordCredentials(url.getUserInfo());
            urlToUse = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()).toExternalForm();
        } else if (null != username && null != password) {
            doauth = true;
            authscope = new AuthScope(url.getHost(), url.getPort() > 0 ? url.getPort() : url.getDefaultPort(),
                    AuthScope.ANY_REALM, "BASIC");
            cred = new UsernamePasswordCredentials(username + ":" + password);
            urlToUse = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()).toExternalForm();
        }
    } catch (MalformedURLException e) {
        throw new FileUpdaterException("Failed to configure base URL for authentication: " + e.getMessage(), e);
    }
    if (doauth) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(authscope, cred);
    }
    interaction.setClient(client);
    interaction.setMethod(new GetMethod(urlToUse));
    interaction.setFollowRedirects(true);
    if (null != acceptHeader) {
        interaction.setRequestHeader("Accept", acceptHeader);
    } else {
        interaction.setRequestHeader("Accept", "*/*");
    }

    if (useCaching) {
        applyCacheHeaders(cacheProperties, interaction);
    }

    logger.debug("Making remote request: " + cleanUrl);
    try {
        resultCode = interaction.executeMethod();
        reasonCode = interaction.getStatusText();
        if (useCaching && HttpStatus.SC_NOT_MODIFIED == resultCode) {
            logger.debug("Content NOT MODIFIED: file up to date");
        } else if (HttpStatus.SC_OK == resultCode) {
            determineContentType(interaction);

            //write to file
            FileOutputStream output = new FileOutputStream(destinationFile);
            try {
                Streams.copyStream(interaction.getResponseBodyAsStream(), output);
            } finally {
                output.close();
            }
            if (destinationFile.length() < 1) {
                //file was empty!
                if (!destinationFile.delete()) {
                    logger.warn("Failed to remove empty file: " + destinationFile.getAbsolutePath());
                }
            }
            if (useCaching) {
                cacheResponseInfo(interaction, cacheMetadata);
            }
        } else {
            throw new FileUpdaterException(
                    "Unable to retrieve content: result code: " + resultCode + " " + reasonCode);
        }
    } catch (HttpException e) {
        throw new FileUpdaterException(e);
    } catch (IOException e) {
        throw new FileUpdaterException(e);
    } finally {
        interaction.releaseConnection();
    }
}

From source file:com.zimbra.common.util.ZimbraHttpConnectionManager.java

private HttpClientParams createHttpClientParams() {
    HttpClientParams clientParams = new HttpClientParams();

    ///*from  w ww .  j  a va2s .c o m*/
    // Sets the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager. 
    //
    // HttpClientParams.CONNECTION_MANAGER_TIMEOUT
    //
    clientParams.setConnectionManagerTimeout(getParams().getHttpClientConnectionTimeout());

    return clientParams;
}