Example usage for org.apache.http.impl.client DefaultHttpClient setHttpRequestRetryHandler

List of usage examples for org.apache.http.impl.client DefaultHttpClient setHttpRequestRetryHandler

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient setHttpRequestRetryHandler.

Prototype

public synchronized void setHttpRequestRetryHandler(final HttpRequestRetryHandler handler) 

Source Link

Usage

From source file:jetbrains.buildServer.commitPublisher.github.api.impl.HttpClientWrapperImpl.java

public HttpClientWrapperImpl()
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion();

    final HttpParams ps = new BasicHttpParams();

    DefaultHttpClient.setDefaultHttpParams(ps);
    final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000);
    HttpConnectionParams.setConnectionTimeout(ps, timeout);
    HttpConnectionParams.setSoTimeout(ps, timeout);
    HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion);

    final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault();
    final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate");
        }/* w  ww.  j a  v a  2s.  c  o m*/
    }) {
        @Override
        public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host,
                InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context)
                throws IOException {
            if (socket instanceof SSLSocket) {
                try {
                    PropertyUtils.setProperty(socket, "host", host.getHostName());
                } catch (Exception ex) {
                    LOG.warn(String.format(
                            "A host name is not passed to SSL connection for the purpose of supporting SNI due to the following exception: %s",
                            ex.toString()));
                }
            }
            return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        }
    };
    schemaRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry),
            ps);

    setupProxy(httpclient);

    httpclient.setRoutePlanner(new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    httpclient.addRequestInterceptor(new RequestAcceptEncoding());
    httpclient.addResponseInterceptor(new ResponseContentEncoding());
    httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    myClient = httpclient;
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * test is the returned status code matches the one of the HandlerException
 * thrown, with a HandlerException thrown before a body is set
 * /* ww  w . j a v a  2s.c  o m*/
 * @throws Exception
 *             on failure
 */
@Test
public void testExceptionStatusCodeBeforeBody() throws Exception {
    final int statusCode = 302;
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testStatusCode");
            response.setHeader(HeaderName.SERVER, "Ad-Hoc testing server");
            throw new HandlerException(ResponseStatus.getInstanceByCode(statusCode));
        }
    }, serverBinding);

    try {
        URI serverURL = new URI("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        HttpHead method = new HttpHead(serverURL);
        DefaultHttpClient client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(null);
        client.setRedirectHandler(nullRedirectHandler);
        HttpResponse response = client.execute(method);
        // for the handler to be invoked, something of the response has to
        // be asked
        assertEquals(statusCode, response.getStatusLine().getStatusCode());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * @throws Exception//from   w  ww.  j  ava  2s .  co m
 */
@Test
public void testStatusCode() throws Exception {
    final int statusCode = 302;
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testStatusCode");
            response.setResponseStatus(ResponseStatus.getInstanceByCode(statusCode));
            response.setHeader(HeaderName.SERVER, "Ad-Hoc testing server");
            response.setHeader(HeaderName.LOCATION, "http://example.org/");
        }
    }, serverBinding);

    try {
        URI serverURL = new URI("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        HttpHead method = new HttpHead(serverURL);
        DefaultHttpClient client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(null);
        client.setRedirectHandler(nullRedirectHandler);
        HttpResponse response = client.execute(method);
        // for the handler to be invoked, something of the response has to
        // be asked
        log.info(response);
        log.info(response.getStatusLine());
        assertEquals(statusCode, response.getStatusLine().getStatusCode());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

@Test
public void testStatusCodeResetInMessageBody() throws Exception {
    final int newStatusCode = 302;
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, final Response response) throws HandlerException {
            log.info("handling testStatusCode");
            response.setResponseStatus(ResponseStatus.CREATED);
            response.setHeader(HeaderName.SERVER, "Ad-Hoc testing server");
            response.setHeader(HeaderName.LOCATION, "http://example.org");
            response.setBody(new MessageBody2Write() {

                public void writeTo(WritableByteChannel out) throws IOException {
                    try {
                        response.setResponseStatus(ResponseStatus.getInstanceByCode(newStatusCode));
                    } catch (HandlerException ex) {
                        throw new RuntimeException(ex);
                    }/*from ww w .j  a  va  2  s. co m*/
                    ByteBuffer bb = ByteBuffer.wrap("this is the body".getBytes());
                    out.write(bb);
                }
            });
        }
    }, serverBinding);

    try {
        URI serverURL = new URI("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        HttpHead method = new HttpHead(serverURL);
        DefaultHttpClient client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(null);
        client.setRedirectHandler(nullRedirectHandler);
        HttpResponse response = client.execute(method);
        // for the handler to be invoked, something of the response has to
        // be asked
        assertEquals(newStatusCode, response.getStatusLine().getStatusCode());
    } finally {
        webServer.stop();
    }
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * @deprecated uses getBody;/*from w ww . j  ava2  s.  co  m*/
 * @throws Exception
 */
@Deprecated
public void testPut() throws Exception {
    final byte[] body = Util.createRandomBytes(3); // 10*1000000);
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testPut");

            if (!request.getMethod().equals(Method.PUT)) {
                response.setResponseStatus(ResponseStatus.METHOD_NOT_ALLOWED);

                return;
            }

            log.info(request.getBody());
        }
    }, serverBinding);

    try {
        URI serverURL = new URI("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");

        DefaultHttpClient client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(null);
        HttpPut method = new HttpPut(serverURL);
        method.setEntity(new ByteArrayEntity(body));
        HttpResponse response = client.execute(method);
        // for the handler to be invoked, something of the response has to
        // be asked
        log.info("" + response.getStatusLine().getStatusCode());

        // assertEquals(statusCode, method.getStatusCode());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:net.paissad.minus.utils.HttpClientUtils.java

/**
 * Convenience method for sending HTTP requests.
 * <b><span style="color:red">Note</span></b>: This method is intended to be
 * used internally, not by end-users.// w  ww  . ja v a 2 s.  c o m
 * 
 * @param baseURL - <b>Example</b>: http://minus.com/api
 * @param parametersBody - The parameters (name => value pairs) to pass to
 *            the request.
 * @param sessionId - If <tt>null</tt> or empty, then create and use a new
 *            session, otherwise, use the specified session_id (which is
 *            stored in a cookie).
 * @param requestType
 * @param additionalRequestHeaders -
 * @param expectedResponseType
 * @return The response retrieved from Minus API.
 * @throws MinusException
 */
private static MinusHttpResponse sendRequest(final String baseURL, final Map<String, String> parametersBody,
        final String sessionId, final RequestType requestType, final Header[] additionalRequestHeaders,
        final ExpectedResponseType expectedResponseType) throws MinusException {

    DefaultHttpClient client = null;
    HttpRequestBase request = null;
    InputStream responseContent = null;
    boolean errorOccured = false;

    try {
        if (requestType == RequestType.GET) {
            request = new HttpGet(baseURL);
            if (parametersBody != null && !parametersBody.isEmpty()) {
                request = appendParametersToRequest(request, parametersBody);
            }

        } else if (requestType == RequestType.POST) {
            UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(getHttpParamsFromMap(parametersBody),
                    HTTP.UTF_8);
            request = new HttpPost(baseURL);
            ((HttpPost) request).setEntity(encodedEntity);

        } else {
            throw new MinusException("The method (" + requestType + ") is unknown, weird ...");
        }

        request.addHeader(new BasicHeader("User-Agent", APP_USER_AGENT));
        if (additionalRequestHeaders != null && additionalRequestHeaders.length > 0) {
            for (Header aHeader : additionalRequestHeaders) {
                request.addHeader(aHeader);
            }
        }

        client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler());

        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        CookieStore cookieStore = new BasicCookieStore();

        Cookie sessionCookie = null;
        if (sessionId != null && !sessionId.trim().isEmpty()) {
            sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId);
            ((BasicClientCookie2) sessionCookie).setPath("/");
            ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME);
            ((BasicClientCookie2) sessionCookie).setVersion(0);
            cookieStore.addCookie(sessionCookie);
        }

        client.setCookieStore(cookieStore);

        HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        // Execute the request ... pass local context as a parameter
        HttpResponse resp = client.execute(request, localContext);

        // Let's update the cookie have the name 'sessionid'
        for (Cookie aCookie : client.getCookieStore().getCookies()) {
            if (aCookie.getName().equals(MINUS_COOKIE_NAME)) {
                sessionCookie = aCookie;
                break;
            }
        }

        Object result = null;
        int statusCode = resp.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = resp.getEntity();
            if (entity != null) {
                if (expectedResponseType == ExpectedResponseType.STRING) {
                    result = EntityUtils.toString(entity);
                    EntityUtils.consume(entity);
                } else if (expectedResponseType == ExpectedResponseType.HTTP_ENTITY) {
                    result = entity;
                }
            }
        } else {
            // The response code is not OK.
            StringBuilder errMsg = new StringBuilder();
            errMsg.append("HTTP ").append(requestType).append(" failed => ").append(resp.getStatusLine());
            if (request != null) {
                errMsg.append(" : ").append(request.getURI());
            }
            throw new MinusException(errMsg.toString());
        }

        return new MinusHttpResponse(result, sessionCookie);

    } catch (Exception e) {
        errorOccured = true;
        if (request != null) {
            request.abort();
        }
        String errMsg = "Error while executing the HTTP " + requestType + " request : " + e.getMessage();
        throw new MinusException(errMsg, e);

    } finally {
        if (client != null) {
            // We must not close the client is the expected response is an
            // InputStream. Indeed, if ever we close the client, we won't be
            // able to read the response because of SocketException.
            if (errorOccured) {
                client.getConnectionManager().shutdown();
            } else if (expectedResponseType != ExpectedResponseType.HTTP_ENTITY) {
                client.getConnectionManager().shutdown();
            }
        }
        CommonUtils.closeAllStreamsQuietly(responseContent);
    }
}

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

private <T> T executeRequest(final HttpRequestBase httpRequest, final HttpClientRequest<T> httpClientRequest)
        throws IOException {
    final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager,
            setFollowRedirects(params, httpClientRequest));
    httpClient.getCookieSpecs().register(NessCookieSpecFactory.NESS_COOKIE_POLICY, new NessCookieSpecFactory());
    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(retries, false));

    contributeCookies(httpClient, httpClientRequest);

    contributeParameters(httpClient, httpRequest, httpClientRequest);

    contributeHeaders(httpRequest, httpClientRequest);

    contributeVirtualHost(httpRequest, httpClientRequest);

    contributeAuthentication(httpClient, httpClientRequest);

    try {/*from  w  ww  .j  a  v a2s.com*/
        final HttpContext httpContext = new BasicHttpContext();
        final HttpResponse httpResponse = httpClient.execute(httpRequest, httpContext);

        final HttpClientResponseHandler<T> responseHandler = httpClientRequest.getHttpHandler();

        try {
            final HttpClientResponse internalResponse = new InternalResponse(httpRequest, httpResponse);
            HttpClientResponse response = internalResponse;

            if (CollectionUtils.isNotEmpty(httpClientObservers)) {
                LOG.trace("Executing Observers");
                for (HttpClientObserver observer : httpClientObservers) {
                    response = observer.onResponseReceived(response);
                }

                if (response != internalResponse) {
                    LOG.trace("Response was modified by Observers!");
                }
            }

            if (responseHandler != null) {
                LOG.trace("Executing Response Handler");
                return responseHandler.handle(response);
            } else {
                LOG.debug("No response handler found, discarding response.");
                return null;
            }
        } finally {
            // Make sure that the content has definitely been consumed. Otherwise,
            // keep-alive does not work.
            EntityUtils.consume(httpResponse.getEntity());
        }
    } catch (IOException ioe) {
        LOG.debug(ioe, "Aborting Request!");
        httpRequest.abort();
        throw ioe;
    } catch (RuntimeException re) {
        LOG.debug(re, "Aborting Request!");
        httpRequest.abort();
        throw re;
    }
}