Example usage for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER

Introduction

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

Prototype

String RETRY_HANDLER

To view the source code for org.apache.commons.httpclient.params HttpMethodParams RETRY_HANDLER.

Click Source Link

Usage

From source file:ac.elements.io.Signature.java

/**
 * Configure HttpClient with set of defaults as well as configuration from
 * AmazonEC2Config instance.//w  w w .j a  va 2s  .  c  o  m
 * 
 * @return the http client
 */
private static HttpClient configureHttpClient() {

    /* Set http client parameters */
    HttpClientParams httpClientParams = new HttpClientParams();
    httpClientParams.setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
    httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() {

        public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {
            if (executionCount > MAX_RETRY_ERROR) {
                log.warn("Maximum Number of Retry attempts " + "reached, will not retry");
                return false;
            }
            log.warn("Retrying request. Attempt " + executionCount);
            if (exception instanceof NoHttpResponseException) {
                log.warn("Retrying on NoHttpResponseException");
                return true;
            }
            if (exception instanceof InterruptedIOException) {
                log.warn("Will not retry on InterruptedIOException", exception);
                return false;
            }
            if (exception instanceof UnknownHostException) {
                log.warn("Will not retry on UnknownHostException", exception);
                return false;
            }
            if (!method.isRequestSent()) {
                log.warn("Retrying on failed sent request");
                return true;
            }
            return false;
        }
    });

    /* Set host configuration */
    HostConfiguration hostConfiguration = new HostConfiguration();

    /* Set connection manager parameters */
    HttpConnectionManagerParams connectionManagerParams = new HttpConnectionManagerParams();
    connectionManagerParams.setConnectionTimeout(50000);
    connectionManagerParams.setSoTimeout(50000);
    connectionManagerParams.setStaleCheckingEnabled(true);
    connectionManagerParams.setTcpNoDelay(true);
    connectionManagerParams.setMaxTotalConnections(MAX_CONNECTIONS);
    connectionManagerParams.setMaxConnectionsPerHost(hostConfiguration, MAX_CONNECTIONS);

    /* Set connection manager */
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.setParams(connectionManagerParams);

    /* Set http client */
    httpClient = new HttpClient(httpClientParams, connectionManager);

    /* Set proxy if configured */
    // if (config.isSetProxyHost() && config.isSetProxyPort()) {
    // log.info("Configuring Proxy. Proxy Host: " + config.getProxyHost() +
    // "Proxy Port: " + config.getProxyPort() );
    // hostConfiguration.setProxy(config.getProxyHost(),
    // config.getProxyPort());
    // if (config.isSetProxyUsername() && config.isSetProxyPassword()) {
    // httpClient.getState().setProxyCredentials (new AuthScope(
    // config.getProxyHost(),
    // config.getProxyPort()),
    // new UsernamePasswordCredentials(
    // config.getProxyUsername(),
    // config.getProxyPassword()));
    //        
    // }
    // }
    httpClient.setHostConfiguration(hostConfiguration);
    return httpClient;
}

From source file:com.celamanzi.liferay.portlets.rails286.OnlineClient.java

/** 
 * POST/*from   w w w  . j a v a  2  s  . co m*/
 * 
 * Posts the parametersBody
 * @throws RailsAppException 
 */
protected byte[] post(NameValuePair[] parametersBody, Map<String, Object[]> files)
        throws HttpException, IOException, RailsAppException {
    // Response body from the web server
    byte[] responseBody = null;
    statusCode = -1;

    List<File> tempFiles = null;

    HttpClient client = preparedClient();

    // Create a method instance.
    PostMethod method = new PostMethod(requestURL.toString());
    HttpMethod _method = (HttpMethod) method;

    String action = "POST action request URL: " + requestURL.toString();
    if (ajax) {
        log.debug("Ajax " + action);
        _method.setRequestHeader("X_REQUESTED_WITH", "XMLHttpRequest");
        _method.setRequestHeader("ACCEPT", "text/javascript, text/html, application/xml, text/xml, */*");
        _method.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    } else
        log.debug(action);

    // finalize method
    method = (PostMethod) prepareMethodHeaders(_method);

    if (files != null && files.size() > 0) {

        tempFiles = new ArrayList<File>();
        createMultipartRequest(parametersBody, files, method, tempFiles);

    } else {
        // Array of parameters may not be null, so init empty NameValuePair[]
        if (parametersBody == null) {
            parametersBody = new NameValuePair[0];
        }
        method.setRequestBody(parametersBody);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
    }

    try {
        // Execute the method.
        statusCode = client.executeMethod(method);

        if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
                || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

            // get Location
            String location = ((Header) method.getResponseHeader("Location")).getValue();
            requestURL = new URL(location);
            log.debug("POST status code: " + method.getStatusLine());
            log.debug("Redirect to location: " + location);

            // server may add another cookie before redirect..
            cookies = client.getState().getCookies();

            // Note that this GET overwrites the previous POST method,
            // so it should set statusCode and cookies correctly.
            responseBody = get();

        } else {
            // the original POST method was OK, pass
            // No more redirects! Response should be 200 OK
            if (statusCode != HttpStatus.SC_OK) {
                String errorMessage = "Method failed: " + method.getStatusLine();
                log.error(errorMessage);
                throw new RailsAppException(errorMessage, new String(method.getResponseBody()));

            } else {
                log.debug("POST status code: " + method.getStatusLine());
            }

            // Read the response body.
            responseBody = method.getResponseBody();

            // Keep the headers for future usage (render or resource phase)
            configureHeader(method.getResponseHeaders());

            // Get session cookies
            cookies = client.getState().getCookies();
        }

    } finally {
        // Release the connection
        method.releaseConnection();

        // Delete temp files
        deleteFiles(tempFiles);
    }

    return responseBody;
}

From source file:com.ning.http.client.providers.apache.ApacheAsyncHttpProvider.java

public ApacheAsyncHttpProvider(AsyncHttpClientConfig config) {
    this.config = config;
    connectionManager = new MultiThreadedHttpConnectionManager();

    params = new HttpClientParams();
    params.setParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, Boolean.TRUE);
    params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

    AsyncHttpProviderConfig<?, ?> providerConfig = config.getAsyncHttpProviderConfig();
    if (providerConfig != null && ApacheAsyncHttpProvider.class.isAssignableFrom(providerConfig.getClass())) {
        configure(ApacheAsyncHttpProviderConfig.class.cast(providerConfig));
    }/*from w  w w .  java2s  .c o m*/
}

From source file:com.netflix.dynomitemanager.sidecore.utils.WarmBootstrapTask.java

private boolean sendCommand(String cmd) {
    DynamicStringProperty adminUrl = DynamicPropertyFactory.getInstance()
            .getStringProperty("florida.metrics.url", "http://localhost:22222");

    String url = adminUrl.get() + cmd;
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

    GetMethod get = new GetMethod(url);
    try {/*from w ww .ja  va2 s  .  c  om*/
        int statusCode = client.executeMethod(get);
        if (!(statusCode == 200)) {
            logger.error("Got non 200 status code from " + url);
            return false;
        }

        String response = get.getResponseBodyAsString();
        //logger.info("Received response from " + url + "\n" + response);

        if (!response.isEmpty()) {
            logger.info("Received response from " + url + "\n" + response);
        } else {
            logger.error("Cannot parse empty response from " + url);
            return false;
        }

    } catch (Exception e) {
        logger.error("Failed to sendCommand and invoke url: " + url, e);
        return false;
    }

    return true;
}

From source file:de.scoopgmbh.copper.monitoring.client.context.ApplicationContext.java

protected void connect(final String serverAdressParam, final String user, final String password) {
    boolean secureConnect = StringUtils.hasText(user) && StringUtils.hasText(password);
    String serverAdress = serverAdressParam;
    if (!serverAdress.endsWith("/")) {
        serverAdress = serverAdress + "/";
    }/*  www.java 2 s. c  o  m*/

    final LoginService loginService;
    final CommonsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new CommonsHttpInvokerRequestExecutor();
    DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(10, false);
    httpInvokerRequestExecutor.getHttpClient().getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            retryHandler);
    httpInvokerRequestExecutor.getHttpClient().getParams().setSoTimeout(1000 * 60 * 5);
    {
        HttpInvokerProxyFactoryBean httpInvokerProxyFactoryBean = new HttpInvokerProxyFactoryBean();
        httpInvokerProxyFactoryBean.setServiceUrl(serverAdress + "copperMonitoringService");
        httpInvokerProxyFactoryBean.setServiceInterface(LoginService.class);
        httpInvokerProxyFactoryBean.setServiceUrl(serverAdress + "loginService");
        httpInvokerProxyFactoryBean.afterPropertiesSet();
        httpInvokerProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor);
        loginService = (LoginService) httpInvokerProxyFactoryBean.getObject();
    }

    final String sessionId;
    if (secureConnect) {
        try {
            sessionId = loginService.doLogin(user, password);
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }
    } else {
        sessionId = "";
    }

    if (sessionId == null) {
        getIssueReporterSingleton().reportWarning("Invalid user/password", null, new Runnable() {
            @Override
            public void run() {
                createLoginForm().show();
            }
        });
    } else {
        HttpInvokerProxyFactoryBean httpInvokerProxyFactoryBean = new HttpInvokerProxyFactoryBean();
        httpInvokerProxyFactoryBean.setServiceUrl(serverAdress + "copperMonitoringService");
        httpInvokerProxyFactoryBean.setServiceInterface(CopperMonitoringService.class);
        RemoteInvocationFactory remoteInvocationFactory = secureConnect
                ? new SecureRemoteInvocationFactory(sessionId)
                : new DefaultRemoteInvocationFactory();
        httpInvokerProxyFactoryBean.setRemoteInvocationFactory(remoteInvocationFactory);
        httpInvokerProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor);
        httpInvokerProxyFactoryBean.afterPropertiesSet();
        final CopperMonitoringService copperMonitoringService = (CopperMonitoringService) httpInvokerProxyFactoryBean
                .getObject();

        final String serverAdressFinal = serverAdress;
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                setGuiCopperDataProvider(copperMonitoringService, serverAdressFinal, sessionId);
            }
        });
    }
}

From source file:fr.openwide.talendalfresco.rest.client.RestAuthenticationTest.java

public void testRestLogout() {
    // first login
    testRestLogin();//from w w  w  . j av  a  2s .  c  om

    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    GetMethod method = new GetMethod(restCommandUrlPrefix + "logout");
    method.setFollowRedirects(true); // ?
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("ticket", ticket) }; // TODO always provide ticket
    method.setQueryString(params);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:com.taobao.ad.easyschedule.commons.utils.JobUtil.java

/**
 * //from ww w .  j a va  2s.  c o m
 * @param jobId
 * @param jobDetail
 * @param target
 * @return
 */
public static JobResult executeRemoteJob(Long jobId, JobDetail jobDetail, String[] target) {
    JobResult result = JobResult.errorResult(JobResult.RESULTCODE_OTHER_ERR, " ");
    try {
        JobDataMap data = jobDetail.getJobDataMap();
        HttpClient client = new HttpClient();
        int retries = JobUtil.getJobRetries(data.getString(Constants.JOBDATA_RETRIES));
        client.getHttpConnectionManager().getParams().setConnectionTimeout(Constants.JOB_MIN_CONN_TIMEOUT);
        client.getHttpConnectionManager().getParams().setSoTimeout(Constants.JOB_MAX_SO_TIMEOUT);
        GetMethod getMethod = null;
        for (int i = 1; i <= retries + 1; i++) {
            try {
                getMethod = new GetMethod(JobUtil.getJobTargetUrl(jobId, jobDetail, target));
                getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler());
            } catch (UnsupportedEncodingException e) {
                logger.error("ShellJob.execute,jobCommand:URL", e);
                result = JobResult.errorResult(JobResult.RESULTCODE_PARAMETER_ILLEGAL,
                        "URL" + e.getMessage());
                return result;
            }
            try {
                int statusCode = client.executeMethod(getMethod);
                if (statusCode != HttpStatus.SC_OK) {
                    ignoreLogger.warn(jobDetail.getFullName() + "" + i
                            + "statuscode:" + statusCode);
                    /*logger.warn(jobDetail.getFullName() + "" + i + "statuscode:" + statusCode);*/
                    result = JobResult.errorResult(JobResult.RESULTCODE_JOB_REQUEST_FAILURE,
                            "? " + statusCode);
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    if (i > 1) {
                        result.getData().put(JobResult.JOBRESULT_DATA_RETRYCOUNT, String.valueOf(i));
                    }
                    continue;
                }
                if (Constants.JOBDATA_CHECKRESULT_VAL_FALSE
                        .equals(data.getString(Constants.JOBDATA_CHECKRESULT))) {
                    result = new JobResult(true, JobResult.RESULTCODE_JOBRESULT_IGNORE,
                            "" + i + "??");
                    break;
                }
                try {
                    result = JSONObject.parseObject(getMethod.getResponseBodyAsString(), JobResult.class);
                    if (i > 1) {
                        result.getData().put(JobResult.JOBRESULT_DATA_RETRYCOUNT, String.valueOf(i));
                    }
                } catch (Exception e) {
                    ignoreLogger.error(jobDetail.getFullName() + "?:" + e.getMessage());
                    /*logger.error(jobDetail.getFullName() + "?:" + e.getMessage());*/
                    result = JobResult.errorResult(JobResult.RESULTCODE_JOBRESULT_ILLEGAL,
                            "?" + StringUtil.html(e.getMessage()));
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                    continue;
                }
                break;
            } catch (Exception e) {
                ignoreLogger.error(jobDetail.getFullName() + "" + i + "" + e);
                /*logger.error(jobDetail.getFullName() + "" + i + "" + e);*/
                result = JobResult.errorResult(JobResult.RESULTCODE_JOB_REQUEST_FAILURE,
                        "" + i + "" + e.getMessage());
                try {
                    Thread.sleep(Constants.JOB_RETRY_WAITTIME);
                } catch (InterruptedException e1) {
                }
                continue;
            }
        }
    } catch (Exception e) {
        logger.error("Job", e);
        result.setResultMsg(result.getResultMsg() + e.getMessage());
    }
    return result;
}

From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java

private String getMethod(String url, String userId, String groupId, Boolean exception) {
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    GetMethod method = new GetMethod(url);
    setHeaders(method, groupId, userId);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    String response = "";

    try {/*from   ww w  .  ja va  2 s  . co  m*/
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... 
            logger.warn("Get host information of testbeds: " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

public static InputStream executeQuery(String str, OutputFormat fmt) throws Exception {
    final String url = "http://localhost:19002/query";

    // Create a method instance.
    GetMethod method = new GetMethod(url);
    method.setQueryString(new NameValuePair[] { new NameValuePair("query", str) });
    method.setRequestHeader("Accept", fmt.mimeType());

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    executeHttpMethod(method);//from  w  w w . ja va2 s. c  om
    return method.getResponseBodyAsStream();
}

From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java

private static void freeCgiAsyncResources(String endpoint, EndpointReference epr) throws MobyException {
    // construct the Httpclient
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
    // create the post method
    PostMethod method = new PostMethod(endpoint + "/destroy");

    // put our data in the request
    RequestEntity entity;//from   w  ww  . j  a  v a 2  s .  c o m
    try {
        entity = new StringRequestEntity("<Destroy xmlns=\"http://docs.oasis-open.org/wsrf/rl-2\"/>",
                "text/xml", null);
    } catch (UnsupportedEncodingException e) {
        throw new MobyException("Problem posting data to webservice", e);
    }
    method.setRequestEntity(entity);

    // set the header
    StringBuffer httpheader = new StringBuffer();
    httpheader.append("<moby-wsrf>");
    httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">"
            + DESTROY_RESOURCE_ACTION + "</wsa:Action>");
    httpheader.append(
            "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">"
                    + endpoint + "</wsa:To>");
    httpheader.append(
            "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">"
                    + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>");
    httpheader.append("</moby-wsrf>");
    method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", ""));
    // retry up to 10 times
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(10, true));

    // call the method
    try {
        int result = client.executeMethod(method);
        if (result != HttpStatus.SC_OK)
            throw new MobyException(
                    "Async HTTP POST service returned code: " + result + "\n" + method.getStatusLine());
    } catch (IOException e) {
        throw new MobyException("Problem reading response from webservice", e);
    } finally {
        // Release current connection to the connection pool once you are
        // done
        method.releaseConnection();
    }
}