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:com.ning.http.client.providers.apache.TestableApacheAsyncHttpProvider.java

public TestableApacheAsyncHttpProvider(AsyncHttpClientConfig config) {
    super(config);
    this.config = config;
    connectionManager = new MultiThreadedHttpConnectionManager();

    params = new HttpClientParams();
    params.setParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, Boolean.TRUE);
    params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

}

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

public void login() {
    // 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);// www  .j  a  v a 2 s.co 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:edu.uci.ics.asterix.test.aql.TestsUtils.java

public static void executeUpdate(String str) throws Exception {
    final String url = "http://localhost:19002/update";

    // 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);//  www .  j ava  2s  . com
}

From source file:net.bpelunit.framework.control.run.TestCaseRunner.java

/**
 * //from   w w w .j a  v  a 2 s.  co m
 * Sends a synchronous message, waits for the result, and returns the
 * result. This method blocks until either a result has been retrieved, a
 * send error has occurred, or the thread was interrupted.
 * 
 * @param message
 *            the message to be sent
 * @return the resulting incoming message
 * @throws SynchronousSendException
 * @throws InterruptedException
 */
public IncomingMessage sendMessageSynchronous(OutgoingMessage message)
        throws SynchronousSendException, InterruptedException {
    PostMethod method = new PostMethod(message.getTargetURL());

    // Set parameters:
    // -> Do not retry
    // -> Socket timeout to default timeout value.
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, Integer.valueOf(BPELUnitRunner.getTimeout()));

    method.addRequestHeader("SOAPAction", "\"" + message.getSOAPHTTPAction() + "\"");
    RequestEntity entity;
    try {
        entity = new StringRequestEntity(message.getMessageAsString(), BPELUnitConstants.TEXT_XML_CONTENT_TYPE,
                BPELUnitConstants.DEFAULT_HTTP_CHARSET);
    } catch (UnsupportedEncodingException e) {
        // cannot happen since we use the default HTTP Encoding.
        throw new SynchronousSendException("Unsupported encoding when trying to post message to web service.",
                e);
    }

    for (String option : message.getProtocolOptionNames()) {
        method.addRequestHeader(option, message.getProtocolOption(option));
    }
    method.setRequestEntity(entity);

    try {
        // Execute the method.

        int statusCode = fClient.executeMethod(method);
        InputStream in = method.getResponseBodyAsStream();

        IncomingMessage returnMsg = new IncomingMessage();
        returnMsg.setStatusCode(statusCode);
        returnMsg.setMessage(in);

        return returnMsg;

    } catch (Exception e) {
        if (isAborting()) {
            throw new InterruptedException();
        } else {
            throw new SynchronousSendException(e);
        }
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

}

From source file:com.zimbra.common.soap.SoapHttpTransport.java

public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId,
        String changeToken, String tokenType, ResponseHandler respHandler)
        throws IOException, HttpException, ServiceException {
    PostMethod method = null;/*from   w w  w. j  a  va 2 s  .com*/

    try {
        // Assemble post method.  Append document name, so that the request
        // type is written to the access log.
        String uri, query;
        int i = mUri.indexOf('?');
        if (i >= 0) {
            uri = mUri.substring(0, i);
            query = mUri.substring(i);
        } else {
            uri = mUri;
            query = "";
        }
        if (!uri.endsWith("/"))
            uri += '/';
        uri += getDocumentName(document);
        method = new PostMethod(uri + query);

        // Set user agent if it's specified.
        String agentName = getUserAgentName();
        if (agentName != null) {
            String agentVersion = getUserAgentVersion();
            if (agentVersion != null)
                agentName += " " + agentVersion;
            method.setRequestHeader(new Header("User-Agent", agentName));
        }

        // the content-type charset will determine encoding used
        // when we set the request body
        method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
        if (getClientIp() != null) {
            method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            if (ZimbraLog.misc.isDebugEnabled()) {
                ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER,
                        getClientIp());
            }
        }
        Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken,
                tokenType);
        String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
        HttpMethodParams params = method.getParams();

        method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));

        if (getRequestProtocol().hasSOAPActionHeader())
            method.setRequestHeader("SOAPAction", mUri);

        if (mCustomHeaders != null) {
            for (Map.Entry<String, String> entry : mCustomHeaders.entrySet())
                method.setRequestHeader(entry.getKey(), entry.getValue());
        }

        String host = method.getURI().getHost();
        HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
        String trustedToken = getTrustedToken();
        if (trustedToken != null) {
            state.addCookie(
                    new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
        }
        params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES
                : CookiePolicy.BROWSER_COMPATIBILITY);
        params.setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
        params.setSoTimeout(mTimeout);
        params.setVersion(HttpVersion.HTTP_1_1);
        method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");

        if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
            state.setProxyCredentials(new AuthScope(null, -1),
                    new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
        }

        if (mHttpDebugListener != null) {
            mHttpDebugListener.sendSoapMessage(method, soapReq, state);
        }

        int responseCode = mClient.executeMethod(mHostConfig, method, state);
        // SOAP allows for "200" on success and "500" on failure;
        //   real server issues will probably be "503" or "404"
        if (responseCode != HttpServletResponse.SC_OK
                && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
            throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri);

        // Read the response body.  Use the stream API instead of the byte[]
        // version to avoid HTTPClient whining about a large response.
        InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(),
                SoapProtocol.getCharset());
        String responseStr = "";

        try {
            if (respHandler != null) {
                respHandler.process(reader);
                return null;
            } else {
                responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false);
                Element soapResp = parseSoapResponse(responseStr, raw);

                if (mHttpDebugListener != null) {
                    mHttpDebugListener.receiveSoapMessage(method, soapResp);
                }
                return soapResp;
            }
        } catch (SoapFaultException x) {
            // attach request/response to the exception and rethrow
            x.setFaultRequest(soapMessage);
            x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
            throw x;
        }
    } finally {
        // Release the connection to the connection manager
        if (method != null)
            method.releaseConnection();

        // really not necessary if running in the server because the reaper thread
        // of our connection manager will take care it.
        // if called from CLI, all connections will be closed when the CLI
        // exits.  Leave it here anyway.
        if (!mKeepAlive)
            mClient.getHttpConnectionManager().closeIdleConnections(0);
    }
}

From source file:com.gs.jrpip.client.FastServletProxyFactory.java

public static HttpClient getHttpClient(AuthenticatedUrl url) {
    HttpClient httpClient = new HttpClient(HTTP_CONNECTION_MANAGER);
    httpClient.getHostConfiguration().setHost(url.getHost(), url.getPort());
    httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, NoRetryRetryHandler.getInstance());
    url.setCredentialsOnClient(httpClient);
    return httpClient;
}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

public static InputStream executeAnyAQLAsync(String str, boolean defer, OutputFormat fmt) throws Exception {
    final String url = "http://localhost:19002/aql";

    // Create a method instance.
    PostMethod method = new PostMethod(url);
    if (defer) {/*from w w  w  .java 2s .  c  o m*/
        method.setQueryString(new NameValuePair[] { new NameValuePair("mode", "asynchronous-deferred") });
    } else {
        method.setQueryString(new NameValuePair[] { new NameValuePair("mode", "asynchronous") });
    }
    method.setRequestEntity(new StringRequestEntity(str));
    method.setRequestHeader("Accept", fmt.mimeType());

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

    String theHandle = IOUtils.toString(resultStream, "UTF-8");

    //take the handle and parse it so results can be retrieved 
    InputStream handleResult = getHandleResult(theHandle, fmt);
    return handleResult;
}

From source file:com.datos.vfs.provider.webdav.WebdavFileObject.java

protected void configureMethod(final HttpMethodBase httpMethod) {
    httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, WebdavMethodRetryHandler.getInstance());
}

From source file:com.rometools.fetcher.impl.HttpClientFeedFetcher.java

public synchronized void setRetryHandler(final HttpMethodRetryHandler handler) {
    httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, handler);
}

From source file:com.esri.gpt.framework.http.HttpClientRequest.java

/**
 * Adds an retry handler to an HTTP method.
 * @param method the HttpMethod to be executed
 *///from w  ww  .  java 2  s.  com
private void addRetryHandler(HttpMethod method) {
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
}