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:com.discogs.api.webservice.impl.HttpClientWebService.java

@Override
public Resp doGet(String url) throws WebServiceException {
    HttpMethod method = new GZipCapableGetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setDoAuthentication(true);//from w w w . j  a  v  a 2 s .  co  m

    try {
        // execute the method
        int statusCode = this.httpClient.executeMethod(method);

        if (logger.isDebugEnabled()) {
            logger.debug(method.getResponseBodyAsString());
        }

        switch (statusCode) {
        case HttpStatus.SC_OK:
            return createResp(method.getResponseBodyAsStream());

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceNotFoundException("Resource not found.", method.getResponseBodyAsString());

        case HttpStatus.SC_BAD_REQUEST:
            throw new RequestException(method.getResponseBodyAsString());

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException(method.getResponseBodyAsString());

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException(method.getResponseBodyAsString());

        default:
            String em = "web service returned unknown status '" + statusCode + "', response was: "
                    + method.getResponseBodyAsString();
            logger.error(em);
            throw new WebServiceException(em);
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Fatal transport error: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.npower.dm.msm.tools.PackageCheckerImpl.java

public PackageMetaInfo getPackageMetaInfo(String url) throws DMException {
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    PackageMetaInfo metaInfo = new PackageMetaInfo();
    metaInfo.setUrl(url);//  w ww . j  a va 2s  .  c  o m
    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);
        metaInfo.setServerStatus(statusCode);
        if (statusCode != HttpStatus.SC_OK) {
            // System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody));

        Header mimeType = method.getResponseHeader("Content-Type");
        if (mimeType != null) {
            metaInfo.setMimeType(mimeType.getValue());
        }

        Header contentLength = method.getResponseHeader("Content-Length");
        if (contentLength != null && StringUtils.isNotEmpty(contentLength.getValue())) {
            metaInfo.setSize(Integer.parseInt(contentLength.getValue()));
        }

    } catch (HttpException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } catch (IOException e) {
        metaInfo.setErrorMessage(e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return metaInfo;
}

From source file:de.softwareforge.pgpsigner.util.HKPSender.java

public boolean uploadKey(final byte[] armoredKey) {

    PostMethod post = new PostMethod(UPLOAD_URL);

    try {/*w  w  w  .ja v a  2  s  .  c om*/

        NameValuePair keyText = new NameValuePair("keytext", new String(armoredKey, "ISO-8859-1"));
        post.setRequestBody(new NameValuePair[] { keyText });
        post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        int statusCode = httpClient.executeMethod(post);

        if (statusCode != HttpStatus.SC_OK) {
            return false;
        }

        InputStream responseStream = post.getResponseBodyAsStream();
        InputStreamReader isr = null;
        BufferedReader br = null;
        StringBuffer response = new StringBuffer();

        try {
            isr = new InputStreamReader(responseStream);
            br = new BufferedReader(isr);
            String line = null;

            while ((line = br.readLine()) != null) {
                response.append(line);
            }
        } finally {
            IOUtils.closeQuietly(br);
            IOUtils.closeQuietly(isr);
            IOUtils.closeQuietly(responseStream);

        }
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        return false;
    } finally {
        post.releaseConnection();
    }
    return true;
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public SaxonDocument search(HashMap<String, String> request)
        throws UnsupportedEncodingException, IOException, SaxonApiException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;/*w w  w .  ja v a2 s  .  c om*/
    String urlStr = prepareUrl(request);
    Log.debug("The following search is goint to be executed:" + urlStr);
    // Create a method instance.
    method = new GetMethod(urlStr);

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

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString());
    //Log.debug(solrResponse.getXMLDocumentString());

    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()",
                XPathConstants.STRING);
        throw new Exception(errorMessage);
    }

    return solrResponse;
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.HttpClientIT.java

@Test
public void test() throws Exception {
    HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(CONNECTION_TIMEOUT);
    client.getParams().setSoTimeout(SO_TIMEOUT);

    GetMethod method = new GetMethod(webServer.getCallHttpUrl());

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setQueryString(new NameValuePair[] { new NameValuePair("key2", "value2") });

    try {// w  w  w . j  a v  a2  s  .  c o m
        // Execute the method.
        client.executeMethod(method);
    } catch (Exception ignored) {
    } finally {
        method.releaseConnection();
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
}

From source file:com.panoramagl.downloaders.PLHTTPFileDownloader.java

/**download methods*/

@Override/*from  ww w . j  a  v  a 2s.  com*/
protected byte[] downloadFile() {
    this.setRunning(true);
    byte[] result = null;
    InputStream is = null;
    ByteArrayOutputStream bas = null;
    String url = this.getURL();
    PLFileDownloaderListener listener = this.getListener();
    boolean hasListener = (listener != null);
    int responseCode = -1;
    long startTime = System.currentTimeMillis();
    // HttpClient instance
    HttpClient client = new HttpClient();
    // Method instance
    HttpMethod method = new GetMethod(url);
    // Method parameters
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.USER_AGENT, "PanoramaGL Android");
    methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(this.getMaxAttempts(), false));
    try {
        // Execute the method
        responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK)
            throw new IOException(method.getStatusText());
        // Get content length
        Header header = method.getRequestHeader("Content-Length");
        long contentLength = (header != null ? Long.parseLong(header.getValue()) : 1);
        if (this.isRunning()) {
            if (hasListener)
                listener.didBeginDownload(url, startTime);
        } else
            throw new PLRequestInvalidatedException(url);
        // Get response body as stream
        is = method.getResponseBodyAsStream();
        bas = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int length = 0, total = 0;
        // Read stream
        while ((length = is.read(buffer)) != -1) {
            if (this.isRunning()) {
                bas.write(buffer, 0, length);
                total += length;
                if (hasListener)
                    listener.didProgressDownload(url, (int) (((float) total / (float) contentLength) * 100.0f));
            } else
                throw new PLRequestInvalidatedException(url);
        }
        if (total == 0)
            throw new IOException("Request data has invalid size (0)");
        // Get data
        if (this.isRunning()) {
            result = bas.toByteArray();
            if (hasListener)
                listener.didEndDownload(url, result, System.currentTimeMillis() - startTime);
        } else
            throw new PLRequestInvalidatedException(url);
    } catch (Throwable e) {
        if (this.isRunning()) {
            PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            if (hasListener)
                listener.didErrorDownload(url, e.toString(), responseCode, result);
        }
    } finally {
        if (bas != null) {
            try {
                bas.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        // Release the connection
        method.releaseConnection();
    }
    this.setRunning(false);
    return result;
}

From source file:edu.internet2.middleware.grouper.changeLog.esb2.consumer.EsbHttpPublisher.java

@Override
public boolean dispatchEvent(String eventJsonString, String consumerName) {
    // TODO Auto-generated method stub

    String urlString = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.url");
    String username = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.username", "");
    String password = GrouperLoaderConfig
            .getPropertyString("changeLog.consumer." + consumerName + ".publisher.password", "");
    if (LOG.isDebugEnabled()) {
        LOG.debug("Consumer name: " + consumerName + " sending " + GrouperUtil.indent(eventJsonString, false)
                + " to " + urlString);
    }//from   w w w.  ja  v  a2 s .c om
    int retries = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.retries", 0);
    int timeout = GrouperLoaderConfig
            .getPropertyInt("changeLog.consumer." + consumerName + ".publisher.timeout", 60000);
    PostMethod post = new PostMethod(urlString);
    post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(retries, false));
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(timeout));
    post.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    RequestEntity requestEntity;
    try {
        requestEntity = new StringRequestEntity(eventJsonString, "application/json", "utf-8");

        post.setRequestEntity(requestEntity);
        HttpClient httpClient = new HttpClient();
        if (!(username.equals(""))) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Authenticating using basic auth");
            }
            URL url = new URL(urlString);
            httpClient.getState().setCredentials(new AuthScope(null, url.getPort(), null),
                    new UsernamePasswordCredentials(username, password));
            httpClient.getParams().setAuthenticationPreemptive(true);
            post.setDoAuthentication(true);
        }
        int statusCode = httpClient.executeMethod(post);
        if (statusCode == 200) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code 200 recieved, event sent OK");
            }
            return true;
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Status code " + statusCode + " recieved, event send failed");
            }
            return false;
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

public static boolean postToServer(String s, String URI, StringBuffer response) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(URI);
    method.addParameter("OS", StringEscapeUtils
            .escapeHtml(System.getProperty("os.name") + "\t" + System.getProperty("os.version")));
    method.addParameter("JVM", StringEscapeUtils
            .escapeHtml(System.getProperty("java.version") + "\t" + System.getProperty("java.vendor")));
    NameValuePair post = new NameValuePair();
    post.setName("post");
    post.setValue(StringEscapeUtils.escapeHtml(s));
    method.addParameter(post);/*from w  w  w.  jav  a 2s. co  m*/

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

    return executeMethod(client, method, response);
}

From source file:br.org.acessobrasil.silvinha.util.versoes.VerificadorDeVersoes.java

public boolean verificarVersao(Versao versaoCliente) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair param = new NameValuePair("param", "check");
    method.setRequestBody(new NameValuePair[] { param });
    DefaultHttpMethodRetryHandler retryHandler = null;
    retryHandler = new DefaultHttpMethodRetryHandler(0, false);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
    try {//w w  w  .  j  a v a2 s  .c o m
        //System.out.println(Silvinha.VERIFICADOR_VERSOES+client.getState().toString());
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
        }
        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        String rb = new String(responseBody).trim();
        Versao versaoServidor = null;
        try {
            versaoServidor = new Versao(rb);
        } catch (NumberFormatException nfe) {
            return false;
        }
        if (versaoCliente.compareTo(versaoServidor) < 0) {
            AtualizadorDeVersoes av = new AtualizadorDeVersoes(url);
            return av.confirmarAtualizacao();
        } else {
            return false;
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
        return false;
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
        return false;
    } catch (Exception e) {
        return false;
    } finally {
        //Release the connection.
        method.releaseConnection();
    }

}

From source file:com.unicauca.braim.http.HttpBraimClient.java

public Song[] GET_Songs(int page, String access_token, JButton bt_next_list, JButton bt_previous_list)
        throws IOException {
    if (page == 1) {
        bt_previous_list.setEnabled(false);
    } else {//  w  w  w.j ava2 s. c  om
        bt_previous_list.setEnabled(true);
    }
    String token = "braim_token=" + access_token;
    String data = "page=" + page + "&per_page=10";
    GetMethod method = new GetMethod(api_url + "/api/v1/songs?" + token + "&" + data);

    Song[] songList = null;
    Gson gson = new Gson();

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

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

        byte[] responseBody = method.getResponseBody();
        Integer total_pages = Integer.parseInt(method.getResponseHeader("total_pages").getValue());
        System.out.println("TOTAL SONG PAGES= " + method.getResponseHeader("total_pages"));
        String response = new String(responseBody, "UTF-8");
        songList = gson.fromJson(response, Song[].class);
        if (page == total_pages) {
            bt_next_list.setEnabled(false);
        } else {
            bt_next_list.setEnabled(true);
        }

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(HttpBraimClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    return songList;
}