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:edu.uci.ics.pregelix.example.util.TestExecutor.java

public void executeDDL(String str, String url) throws Exception {
    // Create a method instance.
    PostMethod method = new PostMethod(url);
    method.setRequestEntity(new StringRequestEntity(str));
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    executeHttpMethod(method);/*from   w  ww  .j a  v  a 2  s.c  o m*/
}

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

public void logout() {
    // 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 + "logout");
    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("ticket", ticket) }; // TODO always provide ticket
    method.setQueryString(params);//  w  w w.j  a v  a 2  s  . c om

    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();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

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

From source file:hudson.plugins.simpleupdatesite.SimpleUpdateSitePlugIn.java

public String getUpdateSiteJSON(String url) throws HttpException, IOException {
    GetMethod method = new GetMethod(url);
    InputStream responseBodyAsStream = null;
    try {//from w  ww  . ja  v a 2 s .co m
        method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        HttpClient client = new HttpClient();
        client.getParams().setConnectionManagerTimeout(Constant.HTTP_TIMEOUT);
        client.getParams().setSoTimeout(Constant.HTTP_TIMEOUT);
        DefaultHttpMethodRetryHandler handler = new DefaultHttpMethodRetryHandler(2, false);
        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, handler);
        client.executeMethod(method);
        responseBodyAsStream = method.getResponseBodyAsStream();
        return IOUtils.toString(responseBodyAsStream, "UTF-8");
    } finally {
        IOUtils.closeQuietly(responseBodyAsStream);
        method.releaseConnection();
    }
}

From source file:net.sf.taverna.t2.activities.biomoby.ExecuteAsyncCgiService.java

private static boolean pollAsyncCgiService(String msName, String url, EndpointReference epr, String[] queryIds,
        String[] result) throws MobyException {
    // Needed to remap results
    HashMap<String, Integer> queryMap = new HashMap<String, Integer>();
    for (int qi = 0; qi < queryIds.length; qi++) {
        String queryId = queryIds[qi];
        if (queryId != null)
            queryMap.put(queryId, new Integer(qi));
    }//  w w w .j  a  va2s  .  c o m

    if (queryMap.size() == 0)
        return false;

    // construct the GetMultipleResourceProperties XML
    StringBuffer xml = new StringBuffer();
    xml.append("<wsrf-rp:GetMultipleResourceProperties xmlns:wsrf-rp='" + RESOURCE_PROPERTIES_NS
            + "' xmlns:mobyws='http://biomoby.org/'>");
    for (String q : queryMap.keySet())
        xml.append("<wsrf-rp:ResourceProperty>mobyws:" + STATUS_PREFIX + q + "</wsrf-rp:ResourceProperty>");
    xml.append("</wsrf-rp:GetMultipleResourceProperties>");

    StringBuffer httpheader = new StringBuffer();
    httpheader.append("<moby-wsrf>");
    httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">"
            + GET_MULTIPLE_RESOURCE_PROPERTIES_ACTION + "</wsa:Action>");
    httpheader.append(
            "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">"
                    + url + "</wsa:To>");
    httpheader.append(
            "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">"
                    + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>");
    httpheader.append("</moby-wsrf>");

    AnalysisEvent[] l_ae = null;
    // First, status from queries
    String response = "";
    // construct the Httpclient
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
    // create the post method
    PostMethod method = new PostMethod(url + "/status");
    // add the moby-wsrf header (with no newlines)
    method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", ""));

    // put our data in the request
    RequestEntity entity;
    try {
        entity = new StringRequestEntity(xml.toString(), "text/xml", null);
    } catch (UnsupportedEncodingException e) {
        throw new MobyException("Problem posting data to webservice", e);
    }
    method.setRequestEntity(entity);

    // retry up to 10 times
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(10, true));

    // call the method
    try {
        if (client.executeMethod(method) != HttpStatus.SC_OK)
            throw new MobyException("Async HTTP POST service returned code: " + method.getStatusCode() + "\n"
                    + method.getStatusLine() + "\nduring our polling request");
        response = stream2String(method.getResponseBodyAsStream());
    } catch (IOException e) {
        throw new MobyException("Problem reading response from webservice", e);
    } finally {
        // Release current connection to the connection pool once you
        // are
        // done
        method.releaseConnection();
    }

    if (response != null) {
        l_ae = AnalysisEvent.createFromXML(response);
    }

    if (l_ae == null || l_ae.length == 0) {
        new MobyException("Troubles while checking asynchronous MOBY job status from service " + msName);
    }

    ArrayList<String> finishedQueries = new ArrayList<String>();
    // Second, gather those finished queries
    for (int iae = 0; iae < l_ae.length; iae++) {
        AnalysisEvent ae = l_ae[iae];
        if (ae.isCompleted()) {
            String queryId = ae.getQueryId();
            if (!queryMap.containsKey(queryId)) {
                throw new MobyException(
                        "Invalid result queryId on asynchronous MOBY job status fetched from " + msName);
            }
            finishedQueries.add(queryId);
        }
    }

    // Third, let's fetch the results from the finished queries
    if (finishedQueries.size() > 0) {
        String[] resQueryIds = finishedQueries.toArray(new String[0]);
        for (int x = 0; x < resQueryIds.length; x++) {
            // construct the GetMultipleResourceProperties XML
            xml = new StringBuffer();
            xml.append("<wsrf-rp:GetMultipleResourceProperties xmlns:wsrf-rp='" + RESOURCE_PROPERTIES_NS
                    + "' xmlns:mobyws='http://biomoby.org/'>");
            for (String q : resQueryIds)
                xml.append("<wsrf-rp:ResourceProperty>mobyws:" + RESULT_PREFIX + q
                        + "</wsrf-rp:ResourceProperty>");
            xml.append("</wsrf-rp:GetMultipleResourceProperties>");

            httpheader = new StringBuffer();
            httpheader.append("<moby-wsrf>");
            httpheader.append("<wsa:Action xmlns:wsa=\"http://www.w3.org/2005/08/addressing\">"
                    + GET_MULTIPLE_RESOURCE_PROPERTIES_ACTION + "</wsa:Action>");
            httpheader.append(
                    "<wsa:To xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsu:Id=\"To\">"
                            + url + "</wsa:To>");
            httpheader.append(
                    "<mobyws:ServiceInvocationId xmlns:mobyws=\"http://biomoby.org/\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\" wsa:IsReferenceParameter=\"true\">"
                            + epr.getServiceInvocationId() + "</mobyws:ServiceInvocationId>");
            httpheader.append("</moby-wsrf>");
            client = new HttpClient();
            client.getParams().setParameter("http.useragent", "jMoby/Taverna2");
            // create the post method
            method = new PostMethod(url + "/results");
            // add the moby-wsrf header (with no newlines)
            method.addRequestHeader("moby-wsrf", httpheader.toString().replaceAll("\r\n", ""));

            // put our data in the request
            entity = null;
            try {
                entity = new StringRequestEntity(xml.toString(), "text/xml", null);
            } catch (UnsupportedEncodingException e) {
                throw new MobyException("Problem posting data to webservice", e);
            }
            method.setRequestEntity(entity);

            // retry up to 10 times
            client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(10, true));

            // call the method
            try {
                if (client.executeMethod(method) != HttpStatus.SC_OK)
                    throw new MobyException("Async HTTP POST service returned code: " + method.getStatusCode()
                            + "\n" + method.getStatusLine() + "\nduring our polling request");
                // place the result in the array
                result[x] = stream2String(method.getResponseBodyAsStream());
                // Marking as null
                queryIds[x] = null;
            } catch (IOException e) {
                logger.warn("Problem getting result from webservice\n" + e.getMessage());
            } finally {
                // Release current connection
                method.releaseConnection();
            }
        }

    }
    return finishedQueries.size() != queryMap.size();
}

From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java

private String postMethod(String url, String payload, String bonfireUserId, String bonfireGroupId,
        Boolean exception) {//from   ww w  .j av  a 2s.  co  m
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    PostMethod method = new PostMethod(url);
    setHeaders(method, bonfireGroupId, bonfireUserId);
    //method.addRequestHeader("Content-Type", SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML);

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

    String response = "";

    try {
        // We set the payload
        StringRequestEntity payloadEntity = new StringRequestEntity(payload,
                SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML, "UTF-8");
        method.setRequestEntity(payloadEntity);

        // Execute the method.
        int statusCode = client.executeMethod(method);
        logger.debug("Status Code: " + statusCode);

        if (statusCode >= 200 && statusCode > 300) { //TODO test for this case... 
            logger.warn("Get host information of testbeds: " + 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:com.xmlcalabash.library.ApacheHttpRequest.java

private GetMethod doGet() {
    GetMethod method = new GetMethod(requestURI.toASCIIString());

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

    for (Header header : headers) {
        method.addRequestHeader(header);
    }//ww w . j  ava  2s  .c  o  m

    return method;
}

From source file:edu.utah.further.core.ws.HttpUtil.java

/**
 * @param url/*www  .j  a  v  a 2  s . co  m*/
 * @return
 */
private static HttpMethod newGetMethod(final String url) {
    final HttpMethod method = new GetMethod(url);

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

From source file:com.xmlcalabash.library.ApacheHttpRequest.java

private HeadMethod doHead() {
    HeadMethod method = new HeadMethod(requestURI.toASCIIString());

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

    for (Header header : headers) {
        method.addRequestHeader(header);
    }/*  w  ww .jav  a 2 s . co  m*/

    return method;
}

From source file:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java

private HttpMethodBase prepareMethod(HttpMethodBase method) {
    method.setRequestHeader("content-type", "application/json;charset=UTF-8;");
    // Provide custom retry handler
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(NUMBER_OF_RETRIES, false));
    return method;
}

From source file:com.xmlcalabash.library.ApacheHttpRequest.java

private void doPutOrPost(EntityEnclosingMethod method, XdmNode body) {
    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    for (Header header : headers) {
        method.addRequestHeader(header);
    }// w  ww . j a v a 2s . c  om

    contentType = body.getAttributeValue(_content_type);
    if (contentType == null) {
        throw new XProcException("Content-type on c:body is required.");
    }

    // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it
    String postContent = null;
    try {
        if (xmlContentType(contentType)) {
            Serializer serializer = makeSerializer();

            Vector<XdmNode> content = new Vector<XdmNode>();
            XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
            while (iter.hasNext()) {
                XdmNode node = (XdmNode) iter.next();
                content.add(node);
            }

            // FIXME: set serializer properties appropriately!
            StringWriter writer = new StringWriter();
            serializer.setOutputWriter(writer);
            S9apiUtils.serialize(runtime, content, serializer);
            writer.close();
            postContent = writer.toString();
        } else {
            StringWriter writer = new StringWriter();
            XdmSequenceIterator iter = body.axisIterator(Axis.CHILD);
            while (iter.hasNext()) {
                XdmNode node = (XdmNode) iter.next();
                writer.write(node.getStringValue());
            }
            writer.close();
            postContent = writer.toString();
        }

        StringRequestEntity requestEntity = new StringRequestEntity(postContent, contentType, "UTF-8");
        method.setRequestEntity(requestEntity);

    } catch (IOException ioe) {
        throw new XProcException(ioe);
    } catch (SaxonApiException sae) {
        throw new XProcException(sae);
    }
}