Example usage for org.apache.commons.httpclient DefaultHttpMethodRetryHandler DefaultHttpMethodRetryHandler

List of usage examples for org.apache.commons.httpclient DefaultHttpMethodRetryHandler DefaultHttpMethodRetryHandler

Introduction

In this page you can find the example usage for org.apache.commons.httpclient DefaultHttpMethodRetryHandler DefaultHttpMethodRetryHandler.

Prototype

public DefaultHttpMethodRetryHandler(int paramInt, boolean paramBoolean) 

Source Link

Usage

From source file:org.jahia.test.bin.FindPrincipalTest.java

@Before
public void setUp() throws Exception {

    // Create an instance of HttpClient.
    client = new HttpClient();

    // todo we should really insert content to test the find.

    PostMethod loginMethod = new PostMethod(getLoginServletURL());
    try {/*from  w  ww. j a  v  a 2  s  .c o  m*/
        loginMethod.addParameter("username", "root");
        loginMethod.addParameter("password", "root1234");
        loginMethod.addParameter("redirectActive", "false");
        // the next parameter is required to properly activate the valve check.
        loginMethod.addParameter(LoginEngineAuthValveImpl.LOGIN_TAG_PARAMETER, "1");
        // Provide custom retry handler is necessary
        loginMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        int statusCode = client.executeMethod(loginMethod);
        assertEquals("Method failed: " + loginMethod.getStatusLine(), HttpStatus.SC_OK, statusCode);
    } finally {
        loginMethod.releaseConnection();
    }
}

From source file:org.jahia.test.bin.FindPrincipalTest.java

@After
public void tearDown() throws Exception {

    PostMethod logoutMethod = new PostMethod(getLogoutServletURL());
    try {/*from w w w  .j  ava2s. c om*/
        logoutMethod.addParameter("redirectActive", "false");
        // Provide custom retry handler is necessary
        logoutMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        int statusCode = client.executeMethod(logoutMethod);
        assertEquals("Method failed: " + logoutMethod.getStatusLine(), HttpStatus.SC_OK, statusCode);
    } finally {
        logoutMethod.releaseConnection();
    }
}

From source file:org.jahia.test.bin.FindPrincipalTest.java

@Test
public void testFindUsers() throws IOException, JSONException, JahiaException {

    PostMethod method = new PostMethod(getFindPrincipalServletURL());
    try {//from  www. j  a  v a2s  .c o  m
        method.addParameter("principalType", "users");
        method.addParameter("wildcardTerm", "*root*");

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

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

        assertEquals("Method failed: " + method.getStatusLine(), HttpStatus.SC_OK, statusCode);

        // Read the response body.
        StringBuilder responseBodyBuilder = new StringBuilder();
        responseBodyBuilder.append("[").append(method.getResponseBodyAsString()).append("]");
        String responseBody = responseBodyBuilder.toString();

        JSONArray jsonResults = new JSONArray(responseBody);

        assertNotNull("A proper JSONObject instance was expected, got null instead", jsonResults);
    } finally {
        method.releaseConnection();
    }

    // @todo we need to add more tests to validate results.

}

From source file:org.jahia.test.bin.FindPrincipalTest.java

@Test
public void testFindGroups() throws IOException, JSONException {

    PostMethod method = new PostMethod(getFindPrincipalServletURL());
    try {/*from  w w w  . ja v a2 s . c  o  m*/
        method.addParameter("principalType", "groups");
        method.addParameter("siteKey", TESTSITE_NAME);
        method.addParameter("wildcardTerm", "*administrators*");

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

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

        assertEquals("Method failed: " + method.getStatusLine(), HttpStatus.SC_OK, statusCode);

        // Read the response body.
        StringBuilder responseBodyBuilder = new StringBuilder();
        responseBodyBuilder.append("[").append(method.getResponseBodyAsString()).append("]");
        String responseBody = responseBodyBuilder.toString();

        JSONArray jsonResults = new JSONArray(responseBody);

        assertNotNull("A proper JSONObject instance was expected, got null instead", jsonResults);
    } finally {
        method.releaseConnection();
    }

    // @todo we need to add more tests to validate results.

}

From source file:org.jahia.test.JahiaTestCase.java

protected PostResult post(String url, String[]... params) throws IOException {
    PostMethod method = new PostMethod(url);
    for (String[] param : params) {
        method.addParameter(param[0], param[1]);
    }/*www  .  ja va  2  s .  co m*/

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

    int statusCode = 0;
    String statusLine = null;
    String responseBody = null;
    try {
        // Execute the method.
        statusCode = getHttpClient().executeMethod(method);

        statusLine = method.getStatusLine().toString();
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: {}", statusLine);
        }

        // Read the response body.
        responseBody = method.getResponseBodyAsString();
    } finally {
        method.releaseConnection();
    }

    return new PostResult(statusCode, statusLine, responseBody);
}

From source file:org.jasig.portal.services.MultiThreadedHttpConnectionManagerFactoryBean.java

@Override
protected MultiThreadedHttpConnectionManager createInstance() throws Exception {
    final MultiThreadedHttpConnectionManager multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();

    final HttpConnectionManagerParams pars = multiThreadedHttpConnectionManager.getParams();
    pars.setConnectionTimeout(this.connectionTimeout);
    pars.setSoTimeout(this.soTimeout);
    pars.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    pars.setMaxTotalConnections(this.maxTotalConnections);
    pars.setDefaultMaxConnectionsPerHost(this.defaultMaxConnectionsPerHost);

    return multiThreadedHttpConnectionManager;
}

From source file:org.kalypso.commons.net.ProxyUtilities.java

/**
 * Creates a configured http client. The configuration includes setting of proxy settings.
 * <p>/*from  w  w w . ja  va2s  .  co m*/
 * IMPORTANT: To use proxy-authentication, you must use the setDoAuthentication Method of the HttpMethod you are going
 * to use.
 * </p>
 * <strong>Example:</strong>
 * 
 * <pre>
 * HttpMethod method = new GetMethod( m_url.toString() );
 * method.setDoAuthentication( true );
 * </pre>
 * 
 * @param timeout
 *          The socket timeout in milliseconds.
 * @param retries
 *          The number of retries, the http client is going to make. Set to a value lower then 0 to leave it at the
 *          default value.
 * @return The configured http client. If no proxy is set, it will be a normal http client with the given timeout and
 *         retries.
 * @deprecated This method should not be used any more, because its functionality is covered completely by the method
 *             {@link #getConfiguredHttpClient(int, URL, int)}. If you have no appropriate URL, leave it null.
 */
@Deprecated
public static HttpClient getConfiguredHttpClient(final int timeout, final int retries) {
    /* Create the new http client. */
    final HttpClient client = new HttpClient();

    /* Client should always authenticate before making a connection. */
    client.getParams().setAuthenticationPreemptive(true);
    client.getParams().setSoTimeout(timeout);

    /* If a retry count is given, set the number of retries. */
    if (retries >= 0)
        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(retries, true));

    /* Get the proxy object. */
    final Proxy proxy = getProxy();

    /* If the proxy should be used, configure the client with it. */
    if (proxy.useProxy()) {
        /* Get the proxy data. */
        final String proxyHost = proxy.getProxyHost();
        final int proxyPort = proxy.getProxyPort();

        /* Set the proxy information. */
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);

        /* Get the credentials. */
        final String user = proxy.getUser();
        final String password = proxy.getPassword();

        /* Set them, if the credentials are complete. */
        if (user != null && password != null) {
            final Credentials credentials = new UsernamePasswordCredentials(user, password);
            client.getState().setProxyCredentials(AuthScope.ANY, credentials);
        }
    }

    return client;
}

From source file:org.kalypso.commons.net.ProxyUtilities.java

/**
 * Creates a configured http client. The configuration includes setting of proxy settings.
 * <p>/*from   w  ww . ja v a 2 s .  c  om*/
 * IMPORTANT: To use proxy-authentication, you must use the setDoAuthentication Method of the HttpMethod you are going
 * to use.
 * </p>
 * <strong>Example:</strong>
 * 
 * <pre>
 * HttpMethod method = new GetMethod( m_url.toString() );
 * method.setDoAuthentication( true );
 * </pre>
 * 
 * @param timeout
 *          The socket timeout in milliseconds.
 * @param url
 *          The url, for which the client is needed. Could be null.
 * @param retries
 *          The number of retries, the http client is going to make. Set to a value lower then 0 to leave it at the
 *          default value.
 * @return The configured http client. If no proxy is set or the host, included in the url is a non proxy host, it
 *         will be a normal http client with the given timeout and retries. If url is null, the check for non proxy
 *         hosts is omitted.
 */
public static HttpClient getConfiguredHttpClient(final int timeout, final URL url, final int retries) {
    /* Create the new http client. */
    final HttpClient client = new HttpClient();

    /* Client should always authenticate before making a connection. */
    client.getParams().setAuthenticationPreemptive(true);
    client.getParams().setSoTimeout(timeout);

    /* If a retry count is given, set the number of retries. */
    if (retries >= 0)
        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(retries, true));

    /* Get the proxy object. */
    final Proxy proxy = getProxy();

    /* If the proxy should be used, configure the client with it. */
    if (proxy.useProxy() && !isNonProxyHost(url)) {
        /* Get the proxy data. */
        final String proxyHost = proxy.getProxyHost();
        final int proxyPort = proxy.getProxyPort();

        /* Set the proxy information. */
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);

        /* Get the credentials. */
        final String user = proxy.getUser();
        final String password = proxy.getPassword();

        /* Set them, if the credentials are complete. */
        if (user != null && password != null) {
            final Credentials credentials = new UsernamePasswordCredentials(user, password);
            client.getState().setProxyCredentials(AuthScope.ANY, credentials);
        }
    }

    return client;
}

From source file:org.kei.android.phone.cellhistory.towers.request.OpenCellIdRequestEntity.java

@Override
public int decode(final String url, final HttpConnection connection, final int timeout) throws Exception {
    int ret = OK;
    final GetMethod getMethod = new GetMethod(url);
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    // socket timeout (connection timeout already set in HttpClient)
    getMethod.getParams().setSoTimeout(timeout);
    final int resCode = getMethod.execute(new HttpState(), connection);
    final InputStream response = getMethod.getResponseBodyAsStream();
    final DataInputStream dis = new DataInputStream(response);
    if (resCode == HttpStatus.SC_OK) {
        final int av = dis.available();
        final byte[] json = new byte[av];
        dis.readFully(json);//  w w  w.  j  a  v a 2  s.  c o  m
        final String sjson = new String(json);
        final String ljson = sjson.toLowerCase(Locale.US);
        if (ljson.indexOf("err") == -1) {
            final JSONObject object = new JSONObject(sjson);
            String lat, lng;
            lat = object.getString("lat");
            lng = object.getString("lon");
            ti.setCellLatitude(Double.parseDouble(lat));
            ti.setCellLongitude(Double.parseDouble(lng));
        } else if (ljson.indexOf("not found") != -1)
            ret = NOT_FOUND;
        else
            ret = EXCEPTION;
    } else if (resCode == HttpStatus.SC_NOT_FOUND)
        ret = NOT_FOUND;
    else if (resCode == HttpStatus.SC_INTERNAL_SERVER_ERROR)
        ret = BAD_REQUEST;
    else
        ret = EXCEPTION;
    getMethod.releaseConnection();
    return ret;
}

From source file:org.kuali.mobility.athletics.service.AthleticsServiceImpl.java

private InputStream getInputStreamFromGetMethod(GetMethod get) throws Exception {
    get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer(socketTimeout));
    httpClient.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT,
            new Long(connectionManagerTimeout));
    httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
            new Integer(connectionTimeout));
    int status = httpClient.executeMethod(get);
    if (status == HttpStatus.SC_OK) {
        return get.getResponseBodyAsStream();
    }//from   w w  w . ja  v a  2s .c  o m
    return null;
}