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:org.cancergrid.ws.util.HttpContentReader.java

public static String getHttpContent(String httpUrl, String query, Method method) {
    LOG.debug("getHttpContent(httpUrl): " + httpUrl);
    LOG.debug("getHttpContent(query): " + query);
    LOG.debug("getHttpContent(method): " + method);

    HttpMethod httpMethod = null;/*w w w.  j av  a2  s  . c  o m*/
    if (httpUrl.contains("&")) {
        httpUrl = httpUrl.replace("&", "&");
    }

    if (query != null && query.length() > 0 && query.startsWith("?") && query.contains("&")) {
        query = query.replace("&", "&");
    }

    try {
        //LOG.debug("Querying: " + httpUrl);
        if (method == Method.GET) {
            httpMethod = new GetMethod(httpUrl);
            if (query != null && query.length() > 0) {
                httpMethod.setQueryString(query);
            }
        } else if (method == Method.POST) {
            httpMethod = new PostMethod(httpUrl);
            if (query != null && query.length() > 0) {
                RequestEntity entity = new StringRequestEntity(query, "text/xml", "UTF-8");
                ((PostMethod) httpMethod).setRequestEntity(entity);
            }
        }

        httpMethod.setFollowRedirects(true);

        httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        Protocol.registerProtocol("https", new Protocol("https",
                new org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory(), 443));
        HttpClient client = new HttpClient();
        int statusCode = client.executeMethod(httpMethod);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + httpMethod.getStatusLine());
            LOG.error("Error querying: " + httpMethod.getURI().toString());
            throw new Exception("Method failed: " + httpMethod.getStatusLine());
        }

        byte[] responseBody = httpMethod.getResponseBody();
        return new String(responseBody, "UTF-8");
    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
    } catch (Exception e) {
        LOG.error(e.getMessage());
    } finally {
        httpMethod.releaseConnection();
    }
    return null;
}

From source file:org.codelabor.system.remoting.http.services.HttpAdapterServiceImpl.java

public String requestByGetMethod(Map<String, String> parameterMap) throws Exception {
    String responseBody = null;//  ww  w  .  j a  v a 2s .  c  om
    GetMethod method = null;

    try {
        StringBuilder sb = new StringBuilder();
        sb.append(url);
        if (url.indexOf("?") == -1) {
            sb.append("?");
        }
        Set<String> keySet = parameterMap.keySet();
        Iterator<String> iter = keySet.iterator();
        String parameterKey = null;
        while (iter.hasNext()) {
            parameterKey = iter.next();
            sb.append(parameterKey);
            sb.append("=");
            sb.append(parameterMap.get(parameterKey));
            if (iter.hasNext()) {
                sb.append("&");
            }
        }

        String encodedURI = URIUtil.encodeQuery(sb.toString());
        logger.debug("encodedURI: {}", encodedURI);

        method = new GetMethod(encodedURI);
        HttpParams httpParams = new DefaultHttpParams();
        DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retry, false);
        httpParams.setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
        HttpClient httpClient = new HttpClient(new HttpClientParams(httpParams));

        int statusCode = httpClient.executeMethod(method);
        logger.debug("statusCode: {}", statusCode);
        switch (statusCode) {
        case HttpStatus.SC_OK:
            responseBody = method.getResponseBodyAsString();
            logger.debug("responseBody: {}", responseBody);
            break;
        }
    } catch (Exception e) {
        if (logger.isErrorEnabled()) {
            String messageKey = "error.http.request";
            String userMessage = messageSource.getMessage(messageKey, new String[] {}, "default message",
                    Locale.getDefault());
            logger.error(userMessage, e);
        }
        e.printStackTrace();
        throw e;
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return responseBody;
}

From source file:org.codelabor.system.services.HttpAdapterServiceImpl.java

public String request(Map<String, String> parameterMap) {
    StringBuilder stringBuilder = new StringBuilder();
    String responseBody = null;/*from w ww  .  j a va2s  . co m*/
    GetMethod method = null;

    try {
        stringBuilder.append(url);
        if (url.indexOf("?") == -1) {
            stringBuilder.append("?");
        }
        Set<String> keySet = parameterMap.keySet();
        Iterator<String> iter = keySet.iterator();
        String parameterKey = null;
        while (iter.hasNext()) {
            parameterKey = iter.next();
            stringBuilder.append(parameterKey);
            stringBuilder.append("=");
            stringBuilder.append(parameterMap.get(parameterKey));
            if (iter.hasNext()) {
                stringBuilder.append("&");
            }
        }

        String encodedURI = URIUtil.encodeQuery(stringBuilder.toString());

        if (log.isDebugEnabled()) {
            log.debug(encodedURI);
        }

        method = new GetMethod(encodedURI);
        HttpParams httpParams = new DefaultHttpParams();
        DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retry, false);
        httpParams.setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
        HttpClient httpClient = new HttpClient(new HttpClientParams(httpParams));

        int statusCode = httpClient.executeMethod(method);
        if (log.isDebugEnabled()) {
            stringBuilder = new StringBuilder();
            stringBuilder.append("statusCode: ").append(statusCode);
            log.debug(stringBuilder.toString());
        }
        switch (statusCode) {
        case HttpStatus.SC_OK:
            responseBody = method.getResponseBodyAsString();
            break;
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            String messageKey = "error.http.request";
            String userMessage = messageSource.getMessage(messageKey, new String[] {}, "default message",
                    Locale.getDefault());
            log.error(userMessage, e);
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
    return responseBody;
}

From source file:org.colombbus.tangara.net.TConnection.java

/**
 * Create a new connection//from   www. j a  v a  2s. c  o  m
 *
 * @param userAgent
 *            the user-agent of the HTTP header
 * @param charset
 *            the character set encoding of the HTTP communication
 * @param serverURL
 *            the address of the server as an URL
 * @param retryCount
 * @param timeout
 */
public TConnection(String userAgent, String charset, String serverURL, int retryCount, int timeout) {
    super();
    this.serverURL = serverURL;
    this.encodingCharset = charset;
    this.retryHandler = new HttpConnRetryHandler(retryCount);
    params.setParameter(HttpMethodParams.USER_AGENT, userAgent);
    params.setContentCharset(charset);
    params.setConnectionManagerTimeout(timeout);
    params.setSoTimeout(timeout);
    params.setParameter(HttpMethodParams.RETRY_HANDLER, this.retryHandler);
}

From source file:org.copperengine.monitoring.client.context.ApplicationContext.java

protected void connect(final String serverAddressParam, final String user, final String password) {
    boolean secureConnect = StringUtils.hasText(user) && StringUtils.hasText(password);
    String serverAddress = serverAddressParam;
    if (!serverAddress.endsWith("/")) {
        serverAddress = serverAddress + "/";
    }//from ww  w  . ja va2s.  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(serverAddress + "copperMonitoringService");
        httpInvokerProxyFactoryBean.setServiceInterface(LoginService.class);
        httpInvokerProxyFactoryBean.setServiceUrl(serverAddress + "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(serverAddress + "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 serverAddressFinal = serverAddress;
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                setGuiCopperDataProvider(copperMonitoringService, serverAddressFinal, sessionId);
            }
        });
    }
}

From source file:org.craftercms.cstudio.share.service.impl.TranslationServiceBingImpl.java

/**
 * fire the bing service//from  w  w  w .j av  a 2  s  .c om
 */
protected String fireBingService(String content, String fromLang, String toLang) {
    String translatedContent = content;

    HttpClient client = new HttpClient();
    String url = getTranslateServiceUrl();
    url = url.replace("{appId}", getApiKey());
    url = url.replace("{fl}", fromLang);
    url = url.replace("{tl}", toLang);
    url = url.replace("{text}", content);

    GetMethod method = null;

    try {
        method = new GetMethod(url);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            LOGGER.error("Method failed: " + method.getStatusLine());
        } else {
            byte[] responseBody = method.getResponseBody();
            translatedContent = new String(responseBody);
            translatedContent = translatedContent.replaceAll("\\/", "/");
            translatedContent = translatedContent.substring(1, translatedContent.length() - 1);

        }

    } catch (HttpException e) {
        LOGGER.error("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        LOGGER.error("Fatal transport error: " + e.getMessage(), e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return translatedContent;
}

From source file:org.dbpedia.spotlight.sparql.SparqlQueryExecuter.java

public String request(URL url) throws SparqlExecutionException {
    GetMethod method = new GetMethod(url.toString());
    String response = null;// w  ww.ja  v a 2  s.c  o m

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

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

        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("SparqlQuery failed: " + method.getStatusLine());
            throw new SparqlExecutionException(String.format("%s (%s). %s", method.getStatusLine(),
                    method.getURI(), method.getResponseBodyAsString()));
        }

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

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

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        throw new SparqlExecutionException(e);
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        throw new SparqlExecutionException(e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:org.deegree.portal.owswatch.ServiceInvoker.java

/**
 * @param method//from   w ww .  j  a  va 2s .  c  o m
 * @return The response OGCWebServiceResponseData
 * @throws OGCWebServiceException
 */
protected ValidatorResponse executeHttpMethod(HttpMethodBase method) throws OGCWebServiceException {

    HttpClient client = new HttpClient();
    HttpConnectionManagerParams cmParams = client.getHttpConnectionManager().getParams();
    cmParams.setConnectionTimeout(serviceConfig.getTimeout() * 1000);
    client.getHttpConnectionManager().setParams(cmParams);
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(2, false));
    ValidatorResponse response = null;
    try {
        long startTime = System.currentTimeMillis();
        int statusCode = client.executeMethod(method);
        long lapse = System.currentTimeMillis() - startTime;
        response = serviceConfig.getValidator().validateAnswer(method, statusCode);

        response.setLastLapse(lapse);
        Calendar date = Calendar.getInstance();
        date.setTimeInMillis(startTime);
        response.setLastTest(date.getTime());
    } catch (Exception e) {
        throw new OGCWebServiceException(e.getLocalizedMessage());
    } finally {
        method.releaseConnection();
    }
    return response;
}

From source file:org.deri.pipes.endpoints.SindiceProxy.java

public String readHTTP(String url) {
    HttpClient client = new HttpClient();

    GetMethod method = new GetMethod(url);

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

    //TODO:set Accept : "Accept: application/json"

    try {//from   w  w  w  .  j a  va  2  s.c o  m

        int statusCode = client.executeMethod(method);

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

        // Read the response body.
        return new String(method.getResponseBody());
    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return null;
}

From source file:org.deri.pipes.endpoints.SindiceSearchRenderer.java

public List searchSindice(String term, int page) {
    List jList = new ArrayList();

    HttpClient client = new HttpClient();
    try {/*w w w .java  2 s.  c  o  m*/
        term = URLEncoder.encode(term, "UTF-8");
    } catch (java.io.UnsupportedEncodingException e) {
        logger.info("UTF-8 support is required by the JVM specification", e);
    }
    GetMethod method = new GetMethod(
            "http://api.sindice.com/v2/search?q=" + term + "&qt=term&page=" + page + "&count=100");

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

    //TODO:set Accept : "Accept: application/json"

    try {

        int statusCode = client.executeMethod(method);

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

        // Read the response body.
        JSONObject result = new JSONObject(new String(method.getResponseBody()));
        JSONArray resultList = result.getJSONArray("entries");
        noPages = result.getInt("totalResults") / 100;
        for (int i = 0; i < resultList.length(); i++)
            jList.add(resultList.get(i));
        return jList;

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return jList;
}