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.xwiki.test.integration.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;//from  w  ww.  j  a v a 2s. c o  m
    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("Result of pinging [" + url + "] = [" + response.responseCode
                        + "], Message = [" + 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;
}

From source file:org.xwiki.xwoot.manager.internal.DefaultXWootManager.java

/**
 * Initializes the HTTP client utility. Called by the component manager when this component is instantiated.
 * //from w ww .j  av a  2 s  .  co  m
 * @see Initializable#initialize()
 */
public void initialize() throws InitializationException {
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    client = new HttpClient(connectionManager);
    client.getParams().setSoTimeout(2000);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, true));

    try {
        documentBridge = (DocumentAccessBridge) componentManager.lookup(DocumentAccessBridge.class.getName());
    } catch (ComponentLookupException e) {
        throw new InitializationException(e.getMessage());
    }
}

From source file:phex.download.PushRequestSleeper.java

private boolean requestViaPushProxies() {
    assert pushProxyAddresses != null && pushProxyAddresses.length > 0;

    // format: /gnet/push-proxy?guid=<ServentIdAsABase16UrlEncodedString>
    String requestPart = "/gnet/push-proxy?guid=" + clientGUID.toHexString();

    ((SimpleStatisticProvider) statsService
            .getStatisticProvider(StatisticsManager.PUSH_DLDPUSHPROXY_ATTEMPTS_PROVIDER)).increment(1);

    for (int i = 0; i < pushProxyAddresses.length; i++) {
        String urlStr = "http://" + pushProxyAddresses[i].getFullHostName() + requestPart;
        NLogger.debug(PushRequestSleeper.class, "PUSH via push proxy: " + urlStr);

        HttpClient httpClient = HttpClientFactory.createHttpClient();
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));

        httpClient.getParams().setSoTimeout(10000);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        HeadMethod method = null;//ww w.  j  a v a  2 s .c om
        try {
            method = new HeadMethod(urlStr);
            method.addRequestHeader(GnutellaHeaderNames.X_NODE, serventAddress.getFullHostName());
            method.addRequestHeader("Cache-Control", "no-cache");
            method.addRequestHeader(HTTPHeaderNames.CONNECTION, "close");

            int responseCode = httpClient.executeMethod(method);

            NLogger.debug(PushRequestSleeper.class,
                    "PUSH via push proxy response code: " + responseCode + " (" + urlStr + ')');

            // if 202
            if (responseCode == HttpURLConnection.HTTP_ACCEPTED) {
                ((SimpleStatisticProvider) statsService
                        .getStatisticProvider(StatisticsManager.PUSH_DLDPUSHPROXY_SUCESS_PROVIDER))
                                .increment(1);
                return true;
            }
        } catch (IOException exp) {
            NLogger.warn(PushRequestSleeper.class, exp);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
    }
    return false;
}

From source file:phex.gwebcache.GWebCacheConnection.java

/**
 * Opens a connection to the request url and checks the response code.
 * 3xx are automaticly redirected./*from w  w  w.  ja  v a  2s . c  o m*/
 * 400 - 599 response codes will throw a ConnectException.
 */
private void openConnection(URL requestURL) throws IOException {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));
    if (ProxyPrefs.UseHttp.get().booleanValue() && !StringUtils.isEmpty(ProxyPrefs.HttpHost.get())) {
        client.getHostConfiguration().setProxy(ProxyPrefs.HttpHost.get(), ProxyPrefs.HttpPort.get().intValue());
    }

    method = new GetMethod(requestURL.toExternalForm());
    method.setFollowRedirects(false);
    method.addRequestHeader("Cache-Control", "no-cache");
    // be HTTP/1.1 complient
    method.addRequestHeader(HTTPHeaderNames.USER_AGENT, Environment.getPhexVendor());
    method.addRequestHeader(HTTPHeaderNames.CONNECTION, "close");

    NLogger.debug(GWebCacheConnection.class, "Open GWebCache connection to " + requestURL + ".");
    int responseCode = client.executeMethod(method);
    NLogger.debug(GWebCacheConnection.class,
            "GWebCache " + requestURL + " returned response code: " + responseCode);

    // we only accept the status codes 2xx all others fail...
    if (responseCode < 200 || responseCode > 299) {
        throw new ConnectException("GWebCache service not available, response code: " + responseCode);
    }

    InputStream bodyStream = method.getResponseBodyAsStream();
    if (bodyStream != null) {
        reader = new BufferedReader(new InputStreamReader(bodyStream));
    } else {
        throw new ConnectException("Empty response.");
    }
}

From source file:voldemort.client.HttpStoreClientFactory.java

public HttpStoreClientFactory(ClientConfig config) {
    super(config);
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    this.httpClient = new HttpClient(connectionManager);
    this.httpClient.setHostConfiguration(hostConfig);
    HttpClientParams clientParams = this.httpClient.getParams();
    clientParams.setConnectionManagerTimeout(config.getConnectionTimeout(TimeUnit.MILLISECONDS));
    clientParams.setSoTimeout(config.getSocketTimeout(TimeUnit.MILLISECONDS));
    clientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    clientParams.setParameter("http.useragent", VOLDEMORT_USER_AGENT);
    HttpConnectionManagerParams managerParams = this.httpClient.getHttpConnectionManager().getParams();
    managerParams.setConnectionTimeout(config.getConnectionTimeout(TimeUnit.MILLISECONDS));
    managerParams.setMaxTotalConnections(config.getMaxTotalConnections());
    managerParams.setStaleCheckingEnabled(false);
    managerParams.setMaxConnectionsPerHost(httpClient.getHostConfiguration(),
            config.getMaxConnectionsPerNode());
    this.reroute = config.getRoutingTier().equals(RoutingTier.SERVER);
    this.requestFormatFactory = new RequestFormatFactory();
}

From source file:voldemort.performance.HttpClientBench.java

private static HttpClient createClient() {
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpClient httpClient = new HttpClient(connectionManager);
    HttpClientParams clientParams = httpClient.getParams();
    clientParams.setConnectionManagerTimeout(DEFAULT_CONNECTION_MANAGER_TIMEOUT);
    clientParams.setSoTimeout(500);//from   ww w  .  j av a2  s .  c  o m
    clientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    clientParams.setBooleanParameter("http.tcp.nodelay", false);
    clientParams.setIntParameter("http.socket.receivebuffer", 60000);
    clientParams.setParameter("http.useragent", VOLDEMORT_USER_AGENT);
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost("localhost");
    hostConfig.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    httpClient.setHostConfiguration(hostConfig);
    HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
    managerParams.setConnectionTimeout(DEFAULT_CONNECTION_MANAGER_TIMEOUT);
    managerParams.setMaxTotalConnections(DEFAULT_MAX_CONNECTIONS);
    managerParams.setMaxConnectionsPerHost(httpClient.getHostConfiguration(), DEFAULT_MAX_HOST_CONNECTIONS);
    managerParams.setStaleCheckingEnabled(false);

    return httpClient;
}

From source file:voldemort.performance.RemoteStoreComparisonTest.java

public static void main(String[] args) throws Exception {
    if (args.length != 2)
        Utils.croak("USAGE: java " + RemoteStoreComparisonTest.class.getName()
                + " numRequests numThreads [useNio]");

    int numRequests = Integer.parseInt(args[0]);
    int numThreads = Integer.parseInt(args[1]);
    boolean useNio = args.length > 2 ? args[2].equals("true") : false;

    /** * In memory test ** */
    final Store<byte[], byte[], byte[]> memStore = new InMemoryStorageEngine<byte[], byte[], byte[]>("test");
    PerformanceTest memWriteTest = new PerformanceTest() {

        @Override//  w w  w  .  ja  va 2  s .  com
        public void doOperation(int i) {
            byte[] key = String.valueOf(i).getBytes();
            memStore.put(key, new Versioned<byte[]>(key), null);
        }
    };
    System.out.println("###########################################");
    System.out.println("Performing memory write test.");
    memWriteTest.run(numRequests, numThreads);
    memWriteTest.printStats();
    System.out.println();

    PerformanceTest memReadTest = new PerformanceTest() {

        @Override
        public void doOperation(int i) {
            try {
                memStore.get(String.valueOf(i).getBytes(), null);
            } catch (Exception e) {
                System.out.println("Failure on i = " + i);
                e.printStackTrace();
            }
        }
    };
    System.out.println("Performing memory read test.");
    memReadTest.run(numRequests, numThreads);
    memReadTest.printStats();
    System.out.println();
    System.out.println();

    /** * Do Socket tests ** */
    String storeName = "test";
    StoreRepository repository = new StoreRepository();
    repository.addLocalStore(new InMemoryStorageEngine<ByteArray, byte[], byte[]>(storeName));
    SocketStoreFactory storeFactory = new ClientRequestExecutorPool(10, 1000, 1000, 32 * 1024);
    final Store<ByteArray, byte[], byte[]> socketStore = storeFactory.create(storeName, "localhost", 6666,
            RequestFormatType.VOLDEMORT_V1, RequestRoutingType.NORMAL);
    RequestHandlerFactory factory = ServerTestUtils.getSocketRequestHandlerFactory(repository);
    AbstractSocketService socketService = ServerTestUtils.getSocketService(useNio, factory, 6666, 50, 50, 1000);
    socketService.start();

    PerformanceTest socketWriteTest = new PerformanceTest() {

        @Override
        public void doOperation(int i) {
            byte[] bytes = String.valueOf(i).getBytes();
            ByteArray key = new ByteArray(bytes);
            socketStore.put(key, new Versioned<byte[]>(bytes), null);
        }
    };
    System.out.println("###########################################");
    System.out.println("Performing socket write test.");
    socketWriteTest.run(numRequests, numThreads);
    socketWriteTest.printStats();
    System.out.println();

    PerformanceTest socketReadTest = new PerformanceTest() {

        @Override
        public void doOperation(int i) {
            try {
                socketStore.get(TestUtils.toByteArray(String.valueOf(i)), null);
            } catch (Exception e) {
                System.out.println("Failure on i = " + i);
                e.printStackTrace();
            }
        }
    };
    System.out.println("Performing socket read test.");
    socketReadTest.run(numRequests, 1);
    socketReadTest.printStats();
    System.out.println();
    System.out.println();

    socketStore.close();
    storeFactory.close();
    socketService.stop();

    /** * Do HTTP tests ** */
    repository.addLocalStore(new InMemoryStorageEngine<ByteArray, byte[], byte[]>(storeName));
    HttpService httpService = new HttpService(null, null, repository, RequestFormatType.VOLDEMORT_V0,
            numThreads, 8080);
    httpService.start();
    HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    HttpClientParams clientParams = httpClient.getParams();
    clientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    clientParams.setParameter("http.useragent", "test-agent");
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
    httpClient.setHostConfiguration(hostConfig);
    HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
    managerParams.setConnectionTimeout(10000);
    managerParams.setMaxTotalConnections(numThreads);
    managerParams.setStaleCheckingEnabled(false);
    managerParams.setMaxConnectionsPerHost(httpClient.getHostConfiguration(), numThreads);
    final HttpStore httpStore = new HttpStore("test", "localhost", 8080, httpClient,
            new RequestFormatFactory().getRequestFormat(RequestFormatType.VOLDEMORT_V0), false);
    Thread.sleep(400);

    PerformanceTest httpWriteTest = new PerformanceTest() {

        @Override
        public void doOperation(int i) {
            byte[] key = String.valueOf(i).getBytes();
            httpStore.put(new ByteArray(key), new Versioned<byte[]>(key), null);
        }
    };
    System.out.println("###########################################");
    System.out.println("Performing HTTP write test.");
    httpWriteTest.run(numRequests, numThreads);
    httpWriteTest.printStats();
    System.out.println();

    PerformanceTest httpReadTest = new PerformanceTest() {

        @Override
        public void doOperation(int i) {
            httpStore.get(new ByteArray(String.valueOf(i).getBytes()), null);
        }
    };
    System.out.println("Performing HTTP read test.");
    httpReadTest.run(numRequests, numThreads);
    httpReadTest.printStats();

    httpService.stop();
}

From source file:zz.pseas.ghost.utils.HttpClinetUtil.java

/**
 * @author GS/*from   www.j  a va  2  s.  co  m*/
 * @param url
 * @param para
 *            get??
 * @return
 * @throws IOException
 */
public static String get(String url, Map<String, String> para) throws IOException {
    String responseBody = null;
    GetMethod getMethod = new GetMethod(url);
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // ????
    NameValuePair[] data = new NameValuePair[para.size()];
    int index = 0;
    for (String s : para.keySet()) {
        data[index++] = new NameValuePair(s, para.get(s)); // ??
    }
    getMethod.setQueryString(data); // ?
    try {
        int statusCode = hc.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + getMethod.getStatusLine());
        }
        responseBody = getMethod.getResponseBodyAsString();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        LOG.error("??" + e.getMessage());
    } catch (UnknownHostException e) {
        e.printStackTrace();
        LOG.error("?,UnknownHostException,?" + e.getMessage());
    } catch (HttpException e) { // ?
        e.printStackTrace();
        LOG.error("?" + e.getMessage());
    } catch (IOException e) { // ?
        e.printStackTrace();
        LOG.error("?" + e.getMessage());
    } finally {
        getMethod.releaseConnection(); // 
    }
    return responseBody;
}

From source file:zz.pseas.ghost.utils.HttpClinetUtil.java

/**
 * @author GS//from ww w.  j  av  a 2  s . c om
 * @param url
 * @return
 * @throws IOException
 */
public static String get(String url) throws IOException {
    String responseBody = null;
    GetMethod getMethod = new GetMethod(url);
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // ????
    try {
        int statusCode = hc.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + getMethod.getStatusLine());
        }
        responseBody = getMethod.getResponseBodyAsString();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        LOG.error("??" + e.getMessage());
    } catch (UnknownHostException e) {
        e.printStackTrace();
        LOG.error("??" + e.getMessage());
    } catch (HttpException e) { // ?
        e.printStackTrace();
        LOG.error("?" + e.getMessage());
    } catch (IOException e) { // ?
        e.printStackTrace();
        LOG.error("?" + e.getMessage());
    } finally {
        getMethod.releaseConnection(); // 
    }
    return responseBody;
}

From source file:zz.pseas.ghost.utils.HttpClinetUtil.java

/**
 * @author GS//from  w ww  . j  ava2  s.c om
 * @param url
 * @param para
 * @param cookie
 * @return
 * @throws IOException
 */
public static String get(String url, Map<String, String> para, String cookie) throws IOException {
    String responseBody = null;
    GetMethod getMethod = new GetMethod(url);
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // ????
    NameValuePair[] data = new NameValuePair[para.size()];
    int index = 0;
    for (String s : para.keySet()) {
        data[index++] = new NameValuePair(s, para.get(s)); // ??
    }
    getMethod.setQueryString(data); // ?
    if (!cookie.equals("")) {
        getMethod.setRequestHeader("cookie", cookie);
    }
    try {
        int statusCode = hc.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + getMethod.getStatusLine());
        }
        responseBody = getMethod.getResponseBodyAsString();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        LOG.error("??" + e.getMessage());
    } catch (HttpException e) { // ?
        e.printStackTrace();
        LOG.error("?" + e.getMessage());
    } catch (IOException e) { // ?
        e.printStackTrace();
        LOG.error("?" + e.getMessage());
    } finally {
        getMethod.releaseConnection(); // 
    }
    return responseBody;
}