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:fr.openwide.talendalfresco.rest.client.RestAuthenticationTest.java

public void testRestLogin() {
    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    GetMethod method = new GetMethod(restCommandUrlPrefix + "login");
    method.setFollowRedirects(true); // ?
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("username", "admin"),
            new NameValuePair("password", "admin") };
    method.setQueryString(params);//from   w w  w.  j a  va2s  . c o m

    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.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody)); // TODO rm

        HashSet<String> defaultElementSet = new HashSet<String>(
                Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE,
                        RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE }));
        HashMap<String, String> elementValueMap = new HashMap<String, String>(6);

        try {
            XMLEventReader xmlReader = XmlHelper.getXMLInputFactory()
                    .createXMLEventReader(new ByteArrayInputStream(responseBody));
            StringBuffer singleLevelTextBuf = null;
            while (xmlReader.hasNext()) {
                XMLEvent event = xmlReader.nextEvent();
                switch (event.getEventType()) {
                case XMLEvent.CHARACTERS:
                case XMLEvent.CDATA:
                    if (singleLevelTextBuf != null) {
                        singleLevelTextBuf.append(event.asCharacters().getData());
                    } // else element not meaningful
                    break;
                case XMLEvent.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String elementName = startElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)
                            // TODO another command specific level
                            || "ticket".equals(elementName)) {
                        // reinit buffer at start of meaningful elements
                        singleLevelTextBuf = new StringBuffer();
                    } else {
                        singleLevelTextBuf = null; // not useful
                    }
                    break;
                case XMLEvent.END_ELEMENT:
                    if (singleLevelTextBuf == null) {
                        break; // element not meaningful
                    }

                    // TODO or merely put it in the map since the element has been tested at start
                    EndElement endElement = event.asEndElement();
                    elementName = endElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)) {
                        String value = singleLevelTextBuf.toString();
                        elementValueMap.put(elementName, value);
                        // TODO test if it is code and it is not OK, break to error handling
                    }
                    // TODO another command specific level
                    else if ("ticket".equals(elementName)) {
                        ticket = singleLevelTextBuf.toString();
                    }
                    // singleLevelTextBuf = new StringBuffer(); // no ! in start
                    break;
                }
            }
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            t.printStackTrace();
            //throw t;
        }

        String code = elementValueMap.get(RestConstants.TAG_CODE);
        assertTrue(RestConstants.CODE_OK.equals(code));
        System.out.println("got ticket " + ticket);

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:eu.eco2clouds.accounting.bonfire.BFClientAccountingImpl.java

private String getMethod(String url, Boolean exception) {
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    GetMethod method = new GetMethod(url);
    setHeaders(method);/*from  w ww. ja v  a2 s .  c  o m*/

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

    String response = "";

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

        if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... 
            logger.warn(
                    "get managed experiments information... : " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:net.sourceforge.jcctray.model.CCNet.java

protected HttpMethod httpMethod(DashBoardProject project) {
    HttpMethod method = new PostMethod(forceBuildURL(project));
    configureMethod(method, project);//from   ww w. j  av a2 s.c  om
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    return method;
}

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

public static boolean sendInfoToServer(NameValuePair[] pairs, String URI, StringBuffer response) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(URI);
    method.setQueryString(pairs);/*from w  ww .  jav  a2 s . c o m*/

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

    return executeMethod(client, method, response);
}

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

public HttpProxy() {
    httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    httpClient.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    httpClient.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
    httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));
}

From source file:br.org.acessobrasil.silvinha.autenticador.AutenticadorConector.java

public boolean autenticarLogin(Login login) {
    boolean autenticado = false;
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair x1 = new NameValuePair("x1", login.getUser());
    NameValuePair x2 = new NameValuePair("x2", login.getPass());
    method.setRequestBody(new NameValuePair[] { x1, x2 });
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    try {//from  www .  j  a v  a2s. co  m
        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();
        // Deal with the response.
        if (rb.startsWith("OK")) {
            autenticado = true;
            String[] rbLines = rb.split("\n");
            Token.setUrl(rbLines[1]);
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
    } finally {
        /*
         *  Release the connection.
        */
        method.releaseConnection();
    }

    return autenticado;
}

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

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

    HostConfiguration config = new HostConfiguration();
    config.setHost("weather.naver.com", 80, "http");
    GetMethod method = new GetMethod("/rgn/cityWetrMain.nhn");

    // 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 {//from ww  w.ja v a 2  s. c o m
        // Execute the method.
        client.executeMethod(config, method);
    } catch (Exception ignored) {
    } finally {
        method.releaseConnection();
    }

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

From source file:com.pureinfo.force.net.impl.HttpUtilImpl.java

/**
 * @see com.pureinfo.force.net.IHttpUtil#getContent(String, NameValuePair[],
 *      String, String)// w ww  .j a v  a2s.c  o m
 */
public String getContent(String _sUrl, NameValuePair[] _args, String _sRequestCharset, String _sResponseCharset)
        throws IOTransferException {
    if (_sRequestCharset == null) {
        _sRequestCharset = "utf-8";
    }

    //1. to create http client and set proxy
    HttpClient client = new HttpClient();
    if (m_proxyHost != null) {
        client.getHostConfiguration().setProxyHost(m_proxyHost);
        if (m_sProxyUser != null & m_sProxyPassword != null) {
            client.getState().setProxyCredentials(//
                    new AuthScope(m_proxyHost.getHostName(), m_proxyHost.getPort()),
                    new UsernamePasswordCredentials(m_sProxyUser, m_sProxyPassword));
        }
    }

    //2. to create post
    PostMethod method = new PostMethod(_sUrl);
    if (m_nRetryCount > 0) {
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, //
                new DefaultHttpMethodRetryHandler(m_nRetryCount, false));
    }
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + _sRequestCharset);
    for (int i = 0; _args != null && i < _args.length; i++) {
        method.addParameter(_args[i]);
    }

    //3. to send request and read response
    String sResponse;
    try {
        client.executeMethod(method);
        sResponse = method.getResponseBodyAsString();
        if (!method.getRequestCharSet().equals(_sRequestCharset)) {
            sResponse = new String(sResponse.getBytes(), _sResponseCharset);
        }
        return sResponse;
    } catch (Exception ex) {
        throw new IOTransferException(_sUrl, ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java

public void testSingleFileImport() {
    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    PostMethod method = new PostMethod(restCommandUrlPrefix + "import");
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("path", "/app:company_home"),
            new NameValuePair("ticket", ticket) };
    method.setQueryString(params);//from   ww  w  .j  av  a2  s. co  m

    try {
        //method.setRequestBody(new NameValuePair[] {
        //      new NameValuePair("path", "/app:company_home") });
        FileInputStream acpXmlIs = new FileInputStream(SAMPLE_SINGLE_FILE_PATH);
        InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs);
        //InputStreamRequestEntity entity = new InputStreamRequestEntity(acpXmlIs, "text/xml; charset=ISO-8859-1");
        method.setRequestEntity(entity);
    } catch (IOException ioex) {
        fail("ACP XML file not found " + ioex.getMessage());
    }

    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.
        byte[] responseBody = method.getResponseBody();
        System.out.println(new String(responseBody)); // TODO rm

        HashSet<String> defaultElementSet = new HashSet<String>(
                Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE,
                        RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE }));
        HashMap<String, String> elementValueMap = new HashMap<String, String>(6);

        try {
            XMLEventReader xmlReader = XmlHelper.getXMLInputFactory()
                    .createXMLEventReader(new ByteArrayInputStream(responseBody));
            StringBuffer singleLevelTextBuf = null;
            while (xmlReader.hasNext()) {
                XMLEvent event = xmlReader.nextEvent();
                switch (event.getEventType()) {
                case XMLEvent.CHARACTERS:
                case XMLEvent.CDATA:
                    if (singleLevelTextBuf != null) {
                        singleLevelTextBuf.append(event.asCharacters().getData());
                    } // else element not meaningful
                    break;
                case XMLEvent.START_ELEMENT:
                    StartElement startElement = event.asStartElement();
                    String elementName = startElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)
                            // TODO another command specific level
                            || "ticket".equals(elementName)) {
                        // reinit buffer at start of meaningful elements
                        singleLevelTextBuf = new StringBuffer();
                    } else {
                        singleLevelTextBuf = null; // not useful
                    }
                    break;
                case XMLEvent.END_ELEMENT:
                    if (singleLevelTextBuf == null) {
                        break; // element not meaningful
                    }

                    // TODO or merely put it in the map since the element has been tested at start
                    EndElement endElement = event.asEndElement();
                    elementName = endElement.getName().getLocalPart();
                    if (defaultElementSet.contains(elementName)) {
                        String value = singleLevelTextBuf.toString();
                        elementValueMap.put(elementName, value);
                        // TODO test if it is code and it is not OK, break to error handling
                    }
                    // TODO another command specific level
                    else if ("ticket".equals(elementName)) {
                        ticket = singleLevelTextBuf.toString();
                    }
                    // singleLevelTextBuf = new StringBuffer(); // no ! in start
                    break;
                }
            }
        } catch (XMLStreamException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Throwable t) {
            // TODO Auto-generated catch block
            t.printStackTrace();
            //throw t;
        }

        String code = elementValueMap.get(RestConstants.TAG_CODE);
        assertTrue(RestConstants.CODE_OK.equals(code));
        System.out.println("got ticket " + ticket);

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:fr.dutra.confluence2wordpress.util.UrlUtils.java

private static URI followRedirectsInternal(URI url, int maxRedirections) {
    URI response = url;// ww w. ja va 2  s.c  o m
    HttpClient client = new HttpClient();
    DefaultHttpMethodRetryHandler handler = new DefaultHttpMethodRetryHandler(1, false);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, handler);
    HttpMethod method = new HeadMethod(url.toASCIIString());
    //method.setRequestHeader("Accept-Language", locale.getLanguage() + ",en");
    method.setFollowRedirects(false);
    try {
        int statusCode = client.executeMethod(method);
        if ((statusCode == HttpStatus.SC_MOVED_PERMANENTLY) | (statusCode == HttpStatus.SC_MOVED_TEMPORARILY)) {
            if (maxRedirections > 0) {
                Header location = method.getResponseHeader("Location");
                if (!location.getValue().equals("")) {
                    // recursively check URL until it's not redirected any more
                    // locations can be relative to previous URL
                    URI target = url.resolve(location.getValue());
                    response = followRedirectsInternal(target, maxRedirections - 1);
                }
            }
        }
    } catch (Exception e) {
        //HttpClient can also throw IllegalArgumentException when URLs are malformed
    }
    return response;
}