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.wise.vle.web.RApacheController.java

/**
 * Handle requests to the RApache server
 * @param request//  w ww .j  a  v a2s  .c  o m
 * @param response
 * @throws IOException 
 * @throws ServletException 
 * @throws JSONException 
 */
private void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    HttpClient client = new HttpClient();

    String targetURL = null;
    String rtype = null;

    try {
        vleProperties = new Properties();
        vleProperties.load(getClass().getClassLoader().getResourceAsStream("vle.properties"));
        targetURL = vleProperties.getProperty("rApache_url");
        rtype = request.getParameter("type");
    } catch (Exception e) {
        System.err
                .println("RApacheController could not locate the rApache URL and/or identify the request type");
        e.printStackTrace();
    }

    if (targetURL != null && rtype != null) {
        // Create a method instance.
        if (rtype.equals("rstat")) {
            PostMethod method = new PostMethod(targetURL);

            String rdata = request.getParameter("rdata");

            // Map input = request.getParameterMap();

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

            method.addParameter(new NameValuePair("rtype", rtype));
            method.addParameter(new NameValuePair("rdata", rdata));

            byte[] responseBody = null;
            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.
                responseBody = method.getResponseBody();

                // Deal with the response.
                // Use caution: ensure correct character encoding and is not binary data
            } 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();
            }

            String responseString = "";

            if (responseBody != null) {
                responseString = new String(responseBody);
            }

            try {
                response.getWriter().print(responseString);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            PostMethod method = new PostMethod(targetURL);

            String rdata = request.getParameter("rdata");
            rdata = URLDecoder.decode(rdata, "UTF-8");
            // Map input = request.getParameterMap();

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

            method.addParameter(new NameValuePair("rtype", rtype));
            method.addParameter(new NameValuePair("rdata", rdata));

            byte[] responseBody = null;
            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.
                responseBody = method.getResponseBody();

                // Deal with the response.
                // Use caution: ensure correct character encoding and is not binary data
            } 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();
            }

            try {

                ServletOutputStream out = response.getOutputStream();
                response.setContentType("image/jpeg");
                response.setContentLength(responseBody.length);
                out.write(responseBody, 0, responseBody.length);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:org.wso2.appcloud.pingdom.service.util.Utils.java

public static boolean isApplicationHealthy(String launchURL) throws HeartbeatServiceException {
    boolean isApplicationHealthy = true;
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(launchURL);

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

    try {//from   w  w  w  . j av a  2 s .  co  m
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            isApplicationHealthy = false;
            byte[] responseBody = method.getResponseBody();
            log.error("Failed to get 200 ok response from url:" + launchURL + " due to "
                    + new String(responseBody));
        }

    } catch (IOException e) {
        isApplicationHealthy = false;
        log.error("Failed to invoke url:" + launchURL + " and get proper response.", e);
    } finally {
        method.releaseConnection();
    }
    return isApplicationHealthy;
}

From source file:org.wso2.carbon.esb.proxyservice.test.proxyservices.UrlEncordedFormPostViaProxyTestCase.java

@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = {//from   w  ww.j  a  v  a 2s  . c om
        "wso2.esb" }, description = "Patch : ESBJAVA-1696 : Encoded Special characters in the URL is decoded at the Gateway and not re-encoded", enabled = true)
public void testEncodingSpecialCharacterViaHttpProxy() throws IOException {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));
    client.getParams().setSoTimeout(5000);
    client.getParams().setConnectionManagerTimeout(5000);

    // Create POST method
    String url = getProxyServiceURLHttp("MyProxy");
    PostMethod method = new PostMethod(url);
    // Set parameters on POST
    String value1 = "Hello World";
    String value2 = "This is a Form Submission containing %";
    String value3 = URLEncoder.encode("This is an encoded value containing %");
    method.setParameter("test1", value1);
    method.addParameter("test2", value2);
    method.addParameter("test3", value3);

    // Execute and print response
    try {
        client.executeMethod(method);
    } catch (Exception e) {

    } finally {
        method.releaseConnection();
    }
    String response = wireMonitorServer.getCapturedMessage();
    String[] responseArray = response.split("test");

    if (responseArray.length < 3) {
        Assert.fail("All attributes are not sent");
    }
    for (String res : responseArray) {
        if (res.startsWith("1")) {
            Assert.assertTrue(res.startsWith("1=" + URLEncoder.encode(value1).replace("+", "%20")));
        } else if (res.startsWith("2")) {
            Assert.assertTrue(res.startsWith("2=" + URLEncoder.encode(value2).replace("+", "%20")));
        } else if (res.startsWith("3")) {
            Assert.assertTrue(res.startsWith("3=" + URLEncoder.encode(value3)));
        }
    }

}

From source file:org.wso2.iot.integration.common.IOTHttpClient.java

public IOTResponse get(String endpoint) {
    HttpClient client = new HttpClient();
    try {/*w ww.j  a v a  2 s  .co m*/
        ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory();

        Protocol https = new Protocol(Constants.HTTPS, socketFactory, Constants.HTTPS_GATEWAY_PORT);
        Protocol.registerProtocol(Constants.HTTPS, https);
        String url = backEndUrl + endpoint;
        GetMethod method = new GetMethod(url);
        method.setRequestHeader(AUTHORIZATION, authorizationString);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        IOTResponse iotResponse = new IOTResponse();
        iotResponse.setStatus(client.executeMethod(method));
        iotResponse.setBody(new String(method.getResponseBody()));
        return iotResponse;

    } catch (GeneralSecurityException e) {
        log.error("Failure occurred at IOTResponse get for GeneralSecurityException", e);
    } catch (IOException e) {
        log.error("Failure occurred at IOTResponse get for IOException", e);
    }

    return null;
}

From source file:org.wso2.iot.integration.common.IOTHttpClient.java

public IOTResponse delete(String endpoint) {

    HttpClient client = new HttpClient();

    try {//  w w  w . j  ava  2  s.c om
        ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory();

        Protocol https = new Protocol(Constants.HTTPS, socketFactory, Constants.HTTPS_GATEWAY_PORT);
        Protocol.registerProtocol(Constants.HTTPS, https);

        String url = backEndUrl + endpoint;

        DeleteMethod method = new DeleteMethod(url);
        method.setRequestHeader(AUTHORIZATION, authorizationString);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        IOTResponse iotResponse = new IOTResponse();
        iotResponse.setStatus(client.executeMethod(method));
        iotResponse.setBody(method.getResponseBodyAsString());
        return iotResponse;

    } catch (GeneralSecurityException e) {
        log.error("Failure occurred at IOTResponse delete for GeneralSecurityException", e);
    } catch (IOException e) {
        log.error("Failure occurred at IOTResponse delete for IOException", e);
    }
    return null;
}

From source file:org.wso2.mdm.integration.common.MDMHttpClient.java

public MDMResponse get(String endpoint) {
    HttpClient client = new HttpClient();
    try {/*from w  w w .  ja v a2  s  . c om*/
        ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory();

        Protocol https = new Protocol("https", socketFactory, 9443);
        Protocol.registerProtocol("https", https);
        String url = backEndUrl + endpoint;
        GetMethod method = new GetMethod(url);
        method.setRequestHeader(AUTHORIZATION, authrizationString);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        MDMResponse mdmResponse = new MDMResponse();
        mdmResponse.setStatus(client.executeMethod(method));
        mdmResponse.setBody(new String(method.getResponseBody()));
        return mdmResponse;

    } catch (GeneralSecurityException e) {
        log.error("Failure occurred at MDMResponse get for GeneralSecurityException", e);
    } catch (IOException e) {
        log.error("Failure occurred at MDMResponse get for IOException", e);
    }

    return null;
}

From source file:org.wso2.mdm.integration.common.MDMHttpClient.java

public MDMResponse delete(String endpoint) {

    HttpClient client = new HttpClient();

    try {/* w  w  w .  jav  a  2s  .c  om*/
        ProtocolSocketFactory socketFactory = new EasySSLProtocolSocketFactory();

        Protocol https = new Protocol("https", socketFactory, 9443);
        Protocol.registerProtocol("https", https);

        String url = backEndUrl + endpoint;

        DeleteMethod method = new DeleteMethod(url);
        method.setRequestHeader(AUTHORIZATION, authrizationString);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        MDMResponse mdmResponse = new MDMResponse();
        mdmResponse.setStatus(client.executeMethod(method));
        mdmResponse.setBody(method.getResponseBodyAsString());
        return mdmResponse;

    } catch (GeneralSecurityException e) {
        log.error("Failure occurred at MDMResponse delete for GeneralSecurityException", e);
    } catch (IOException e) {
        log.error("Failure occurred at MDMResponse delete for IOException", e);
    }
    return null;
}

From source file:org.xsocket.connection.ServerSideCloseTest.java

@Test
public void testApacheClientPooledWebServer() throws Exception {

    System.out.println("testApacheClientPooledWebServer");

    final IServer server = new Server(new WebHandler());
    server.start();/*from   w w w  .  j  a  v a 2 s. c  o  m*/

    for (int i = 0; i < 5; i++) {
        new Thread() {
            @Override
            public void run() {

                running.incrementAndGet();
                try {
                    org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
                    httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                            new DefaultHttpMethodRetryHandler(0, false));

                    for (int j = 0; j < 1000; j++) {

                        GetMethod getMeth = new GetMethod("http://localhost:" + server.getLocalPort() + "/");
                        httpClient.executeMethod(getMeth);

                        Assert.assertEquals(200, getMeth.getStatusCode());
                        Assert.assertEquals("OK", getMeth.getResponseBodyAsString());

                        getMeth.releaseConnection();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    errors.add(e.toString());

                } finally {
                    running.decrementAndGet();
                }

            }
        }.start();
    }

    do {
        QAUtil.sleep(200);
    } while (running.get() > 0);

    for (String error : errors) {
        System.out.println(error);
    }

    Assert.assertTrue(errors.isEmpty());

    server.close();

}

From source file:org.xsocket.connection.ServerSideCloseTest.java

@Test
public void testApacheClientPooledWebServer2() throws Exception {

    System.out.println("testApacheClientPooledWebServer");

    final IServer server = new Server(new WebHandler2());
    server.start();/*w ww.java  2  s  .c  o  m*/

    for (int i = 0; i < 2; i++) {
        new Thread() {
            @Override
            public void run() {

                running.incrementAndGet();
                try {
                    org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
                    httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                            new DefaultHttpMethodRetryHandler(0, false));

                    for (int j = 0; j < 3; j++) {

                        GetMethod getMeth = new GetMethod("http://localhost:" + server.getLocalPort() + "/");
                        httpClient.executeMethod(getMeth);

                        Assert.assertEquals(200, getMeth.getStatusCode());
                        Assert.assertEquals(50000, getMeth.getResponseBodyAsString().getBytes().length);

                        getMeth.releaseConnection();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    errors.add(e.toString());

                } finally {
                    running.decrementAndGet();
                }

            }
        }.start();
    }

    do {
        QAUtil.sleep(200);
    } while (running.get() > 0);

    for (String error : errors) {
        System.out.println(error);
    }

    Assert.assertTrue(errors.isEmpty());

    server.close();

}

From source file:org.xwiki.test.integration.utils.XWikiExecutor.java

public Response isXWikiStarted(String url, int timeout) throws Exception {
    HttpClient client = new HttpClient();

    boolean connected = false;
    long startTime = System.currentTimeMillis();
    Response response = new Response();
    response.timedOut = false;//  w  w w  .j a  va 2  s  .c  om
    response.responseCode = -1;
    response.responseBody = new byte[0];
    while (!connected && !response.timedOut) {
        GetMethod method = new GetMethod(url);

        // Don't retry automatically since we're doing that in the algorithm below
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(0, false));
        // Set a socket timeout to ensure the server has no chance of not answering to our request...
        method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(10000));

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

            // We must always read the response body.
            response.responseBody = method.getResponseBody();

            if (DEBUG) {
                System.out.println(String.format("Result of pinging [%s] = [%s], Message = [%s]", url,
                        response.responseCode, new String(response.responseBody)));
            }

            // check the http response code is either not an error, either "unauthorized"
            // (which is the case for products that deny view for guest, for example).
            connected = (response.responseCode < 400 || response.responseCode == 401);
        } catch (Exception e) {
            // Do nothing as it simply means the server is not ready yet...
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        Thread.sleep(500L);
        response.timedOut = (System.currentTimeMillis() - startTime > timeout * 1000L);
    }
    return response;
}