Example usage for org.apache.commons.httpclient.params HttpMethodParams SO_TIMEOUT

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams SO_TIMEOUT

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpMethodParams SO_TIMEOUT.

Prototype

String SO_TIMEOUT

To view the source code for org.apache.commons.httpclient.params HttpMethodParams SO_TIMEOUT.

Click Source Link

Usage

From source file:com.mengka.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

public BatchContextResult<ConfigInfoEx> batchAddOrUpdate(String serverId, String groupName,
        Map<String, String> dataId2ContentMap) {
    // /*  www .j ava 2 s.c o m*/
    BatchContextResult<ConfigInfoEx> response = new BatchContextResult<ConfigInfoEx>();

    // map?null
    if (dataId2ContentMap == null) {
        log.error("dataId2ContentMap cannot be null, serverId=" + serverId + " ,group=" + groupName);
        response.setSuccess(false);
        response.setStatusMsg("dataId2ContentMap cannot be null");
        return response;
    }

    // dataIdcontentmap????
    StringBuilder allDataIdAndContentBuilder = new StringBuilder();
    for (String dataId : dataId2ContentMap.keySet()) {
        String content = dataId2ContentMap.get(dataId);
        allDataIdAndContentBuilder.append(dataId + Constants.WORD_SEPARATOR + content)
                .append(Constants.LINE_SEPARATOR);
    }
    String allDataIdAndContent = allDataIdAndContentBuilder.toString();

    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg("login fail, serverId=" + serverId);
        return response;
    }

    // HTTP method
    PostMethod post = new PostMethod("/diamond-server/admin.do?method=batchAddOrUpdate");
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        // ?
        NameValuePair dataId_value = new NameValuePair("allDataIdAndContent", allDataIdAndContent);
        NameValuePair group_value = new NameValuePair("group", groupName);

        post.setRequestBody(new NameValuePair[] { dataId_value, group_value });

        // http??
        int status = client.executeMethod(post);
        response.setStatusCode(status);
        String responseMsg = post.getResponseBodyAsString();
        response.setResponseMsg(responseMsg);

        if (status == HttpStatus.SC_OK) {
            String json = null;
            try {
                json = responseMsg;

                // ???json, ??BatchContextResult
                List<ConfigInfoEx> configInfoExList = new LinkedList<ConfigInfoEx>();
                Object resultObj = JSONUtils.deserializeObject(json, new TypeReference<List<ConfigInfoEx>>() {
                });
                if (!(resultObj instanceof List<?>)) {
                    throw new RuntimeException("batch write deserialize type error, not list, json=" + json);
                }
                List<ConfigInfoEx> resultList = (List<ConfigInfoEx>) resultObj;
                for (ConfigInfoEx configInfoEx : resultList) {
                    configInfoExList.add(configInfoEx);
                }
                response.getResult().addAll(configInfoExList);
                // ????, ???
                response.setStatusMsg("batch write success");
                log.info("batch write success,serverId=" + serverId + ",allDataIdAndContent="
                        + allDataIdAndContent + ",group=" + groupName + ",json=" + json);
            } catch (Exception e) {
                response.setSuccess(false);
                response.setStatusMsg("batch write deserialize error");
                log.error("batch write deserialize error, serverId=" + serverId + ",allDataIdAndContent="
                        + allDataIdAndContent + ",group=" + groupName + ",json=" + json, e);
            }
        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg("batch write timeout, socket timeout(ms):" + require_timeout);
            log.error("batch write timeout, socket timeout(ms):" + require_timeout + ", serverId=" + serverId
                    + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName);
        } else {
            response.setSuccess(false);
            response.setStatusMsg("batch write fail, status:" + status);
            log.error("batch write fail, status:" + status + ", response:" + responseMsg + ",serverId="
                    + serverId + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName);
        }
    } catch (HttpException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch write http exception" + e.getMessage());
        log.error("batch write http exception, serverId=" + serverId + ",allDataIdAndContent="
                + allDataIdAndContent + ",group=" + groupName, e);
    } catch (IOException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch write io exception" + e.getMessage());
        log.error("batch write io exception, serverId=" + serverId + ",allDataIdAndContent="
                + allDataIdAndContent + ",group=" + groupName, e);
    } finally {
        // ?
        post.releaseConnection();
    }

    return response;
}

From source file:cn.leancloud.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

@Override
public BatchContextResult<ConfigInfoEx> batchAddOrUpdate(String serverId, String groupName,
        Map<String, String> dataId2ContentMap) {
    // /*from   w ww .  j a  v a2 s  .c om*/
    BatchContextResult<ConfigInfoEx> response = new BatchContextResult<ConfigInfoEx>();

    // map?null
    if (dataId2ContentMap == null) {
        log.error("dataId2ContentMap cannot be null, serverId=" + serverId + " ,group=" + groupName);
        response.setSuccess(false);
        response.setStatusMsg("dataId2ContentMap cannot be null");
        return response;
    }

    // dataIdcontentmap????
    StringBuilder allDataIdAndContentBuilder = new StringBuilder();
    for (String dataId : dataId2ContentMap.keySet()) {
        String content = dataId2ContentMap.get(dataId);
        allDataIdAndContentBuilder.append(dataId + Constants.WORD_SEPARATOR + content)
                .append(Constants.LINE_SEPARATOR);
    }
    String allDataIdAndContent = allDataIdAndContentBuilder.toString();

    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg("login fail, serverId=" + serverId);
        return response;
    }

    // HTTP method
    PostMethod post = new PostMethod("/diamond-server/admin.do?method=batchAddOrUpdate");
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        // ?
        NameValuePair dataId_value = new NameValuePair("allDataIdAndContent", allDataIdAndContent);
        NameValuePair group_value = new NameValuePair("group", groupName);

        post.setRequestBody(new NameValuePair[] { dataId_value, group_value });

        // http??
        int status = client.executeMethod(post);
        response.setStatusCode(status);
        String responseMsg = post.getResponseBodyAsString();
        response.setResponseMsg(responseMsg);

        if (status == HttpStatus.SC_OK) {
            String json = null;
            try {
                json = responseMsg;

                // ???json, ??BatchContextResult
                List<ConfigInfoEx> configInfoExList = new LinkedList<ConfigInfoEx>();
                Object resultObj = JSONUtils.deserializeObject(json, new TypeReference<List<ConfigInfoEx>>() {
                });
                if (!(resultObj instanceof List<?>)) {
                    throw new RuntimeException("batch write deserialize type error, not list, json=" + json);
                }
                List<ConfigInfoEx> resultList = (List<ConfigInfoEx>) resultObj;
                for (ConfigInfoEx configInfoEx : resultList) {
                    configInfoExList.add(configInfoEx);
                }
                response.getResult().addAll(configInfoExList);
                // ????, ???
                response.setStatusMsg("batch write success");
                log.info("batch write success,serverId=" + serverId + ",allDataIdAndContent="
                        + allDataIdAndContent + ",group=" + groupName + ",json=" + json);
            } catch (Exception e) {
                response.setSuccess(false);
                response.setStatusMsg("batch write deserialize error");
                log.error("batch write deserialize error, serverId=" + serverId + ",allDataIdAndContent="
                        + allDataIdAndContent + ",group=" + groupName + ",json=" + json, e);
            }
        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg("batch write timeout, socket timeout(ms):" + require_timeout);
            log.error("batch write timeout, socket timeout(ms):" + require_timeout + ", serverId=" + serverId
                    + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName);
        } else {
            response.setSuccess(false);
            response.setStatusMsg("batch write fail, status:" + status);
            log.error("batch write fail, status:" + status + ", response:" + responseMsg + ",serverId="
                    + serverId + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName);
        }
    } catch (HttpException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch write http exception" + e.getMessage());
        log.error("batch write http exception, serverId=" + serverId + ",allDataIdAndContent="
                + allDataIdAndContent + ",group=" + groupName, e);
    } catch (IOException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch write io exception" + e.getMessage());
        log.error("batch write io exception, serverId=" + serverId + ",allDataIdAndContent="
                + allDataIdAndContent + ",group=" + groupName, e);
    } finally {
        // ?
        post.releaseConnection();
    }

    return response;
}

From source file:fr.cls.atoll.motu.processor.wps.framework.WPSFactory.java

/**
 * Post async.//from w  w w . j av  a 2  s . c om
 * 
 * @param url the url
 * @param postBody the post body
 * @param headers the headers
 * 
 * @return the int
 * 
 * @throws HttpException the http exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static int postAsync(String url, InputStream postBody, Map<String, String> headers)
        throws HttpException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("postAsync(String, InputStream, Map<String,String>) - entering");
    }

    // TODO no proxies used
    HttpClient client = new HttpClient();
    HttpMethodParams httpMethodParams = new HttpMethodParams();
    httpMethodParams.setIntParameter(HttpMethodParams.SO_TIMEOUT, 1);

    PostMethod post = new PostMethod(url);
    post.setRequestEntity(new InputStreamRequestEntity(postBody));
    post.setParams(httpMethodParams);

    for (String key : headers.keySet()) {
        post.setRequestHeader(key, headers.get(key));
    }
    int retcode = -1;
    try {
        retcode = client.executeMethod(post);
    } catch (SocketTimeoutException e) {
        LOG.error("postAsync(String, InputStream, Map<String,String>)", e);

        // do nothing
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("postAsync(String, InputStream, Map<String,String>) - exiting");
    }
    return retcode;
}

From source file:org.entando.entando.plugins.jpoauthclient.aps.system.httpclient.OAuthHttpClient.java

@Override
public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpMethod httpMethod;// w  w  w  . ja v  a  2s .c  o  m
    if (isPost || isPut) {
        EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e)
                    : new InputStreamRequestEntity(e, Long.parseLong(length)));
            excerpt = e.getExcerpt();
        }
        httpMethod = entityEnclosingMethod;
    } else if (isDelete) {
        httpMethod = new DeleteMethod(url);
    } else {
        httpMethod = new GetMethod(url);
    }
    for (Map.Entry<String, Object> p : parameters.entrySet()) {
        String name = p.getKey();
        String value = p.getValue().toString();
        if (FOLLOW_REDIRECTS.equals(name)) {
            httpMethod.setFollowRedirects(Boolean.parseBoolean(value));
        } else if (READ_TIMEOUT.equals(name)) {
            httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value));
        }
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpMethod.addRequestHeader(header.getKey(), header.getValue());
    }
    HttpClient client = this._clientPool.getHttpClient(new URL(httpMethod.getURI().toString()));
    client.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset());
}

From source file:org.intalio.tempo.workflow.fds.core.MessageSender.java

/**
 * Sends an XML request to a specific HTTP endpoint with a specific
 * <code>SOAPAction</code> header and returns the reply as XML.
 * /*from w w w  .  java2 s.  co m*/
 * @param requestMessage
 *            The request XML payload.
 * @param endpoint
 *            The endpoint URL, such as
 *            <code>http://localhost/webservice</code>
 * @param soapAction
 *            The <code>SOAPAction</code> to send the message with.
 * @return The reply from the endpoint as an XML <code>Document</code>.
 * @throws HttpException
 *             If an HTTP-level error happens.
 * @throws IOException
 *             If a low-level input/output error happens (e.g. a
 *             disconnection during the request/response).
 * @throws DocumentException 
 * @see <a href="http://www.w3.org/TR/soap/">The SOAP specification.</a>
 */
public Document requestAndGetReply(Document requestMessage, String endpoint, String soapAction)
        throws HttpException, IOException, DocumentException {
    Document result = null;

    PostMethod postMethod = new PostMethod(endpoint);
    postMethod.addRequestHeader("SOAPAction", soapAction);
    postMethod.setRequestEntity(
            new ByteArrayRequestEntity(requestMessage.asXML().getBytes(), "text/xml; charset=UTF-8"));

    HttpClient httpClient = new HttpClient();

    // turn off retrying, since retrying SOAP requests can cause side-effects
    DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);
    httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);

    // set the timeout
    httpClient.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,
            FormDispatcherConfiguration.getInstance().getHttpTimeout());

    // Prepare an XML parser 
    SAXReader reader = new SAXReader();
    InputStream responseInputStream = null;
    try {
        httpClient.executeMethod(postMethod);
        responseInputStream = postMethod.getResponseBodyAsStream();
        result = reader.read(responseInputStream);
    } finally {
        postMethod.releaseConnection();
        if (responseInputStream != null)
            responseInputStream.close();
    }

    return result;
}

From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java

public static String doGet(String url, String queryString, String charset, String token) {
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    GetMethod getMethod = new GetMethod(url);
    if (!Global.isEmpty(queryString)) {
        getMethod.setQueryString(queryString);
    }/*w ww . ja  v  a 2  s  . c  o  m*/
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);

    if (!Global.isEmpty(token)) {
        getMethod.addRequestHeader("X-Auth-Token", token);
    }
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    String response = "";
    try {
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("request error: " + getMethod.getStatusLine());
        }
        byte[] responseBody = getMethod.getResponseBody();
        response = new String(responseBody, charset);
        logger.debug("----------response:" + response);
    } catch (HttpException e) {
        logger.error("Exception", e);
    } catch (IOException e) {
        logger.error("Exception", e);
    } finally {
        getMethod.releaseConnection();
    }
    return response;
}

From source file:org.openo.nfvo.monitor.umc.util.APIHttpClient.java

public static String doGet(String url, String queryString, String charset, String token) {
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    GetMethod getMethod = new GetMethod(url);
    if (!Global.isEmpty(queryString)) {
        getMethod.setQueryString(queryString);
    }/*from   www. j ava  2s  .c  o  m*/
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);

    if (!Global.isEmpty(token)) {
        getMethod.addRequestHeader("X-Auth-Token", token);
    }
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    String response = "";
    try {
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("request error: " + getMethod.getStatusLine());
        } else {
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            logger.debug("----------response:" + response);
        }

    } catch (HttpException e) {
        logger.error("Exception", e);
    } catch (IOException e) {
        logger.error("Exception", e);
    } finally {
        getMethod.releaseConnection();
    }
    return response;
}

From source file:org.openremote.beehive.utils.LIRCrawler.java

/**
 * Gets the html body.//from  w w  w. j  a  v  a2s .c o m
 * 
 * @param url
 *           the url
 * 
 * @return the html body
 */
private static String getHtmlBody(String url) {
    String responseBody = "";
    GetMethod getMethod = new GetMethod(url);
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30000);
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
    try {
        int statusCode = httpClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            LOGGER.error("Method failed: " + getMethod.getStatusLine());
        }
        BufferedReader bufferIn = new BufferedReader(
                new InputStreamReader(getMethod.getResponseBodyAsStream()));
        StringBuffer sb = new StringBuffer();
        char[] buf = new char[1024 * 1024];
        int len;
        while ((len = bufferIn.read(buf)) > 0) {
            sb.append(buf, 0, len);
        }
        responseBody = sb.toString();
    } catch (HttpException e) {
        LOGGER.error("Please check your provided http address " + url, e);
        return null;
    } catch (IOException e) {
        LOGGER.error("Occur the network exception, maybe the url [" + url + "] is unreachable.", e);
        return null;
    } finally {
        getMethod.releaseConnection();
    }
    return responseBody;
}

From source file:org.oryxeditor.server.TBPMServlet.java

private String sendRequest(File img, String fileName) {

    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30000);
    PostMethod method = new PostMethod(TBPM_RECOGNITION_URL);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    String response = "";
    try {/*from  w  ww .  ja  v  a 2  s .co  m*/
        Part[] parts = { new FilePart(img.getName(), img) };
        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        client.executeMethod(method);
        //TODO handle response status
        response = method.getResponseBodyAsString();
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    method.releaseConnection();
    return response;
}

From source file:org.pentaho.pac.server.PacServiceImpl.java

public String getHomePageAsHtml(String url) {

    String html = null;/*from   w  w w .  j a  v a  2 s.  c o m*/
    HttpClient client = new HttpClient();
    GetMethod get = null;
    try {

        String timeOut = AppConfigProperties.getInstance().getHomepageTimeout();
        HttpMethodParams params = new HttpMethodParams();
        params.setParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(timeOut));
        get = new GetMethod(url);
        get.setParams(params);
        client.executeMethod(get);

        //getResponseBodyAsString() and the like were decoding as ISO-8859-1 instead of UTF-8.
        //This is indeed the default behavior of HttpClient if the charset is not defined in 
        //the Content-Type reponse header. We're overriding that since we know our source is
        //UTF-8
        byte[] bytes = get.getResponseBody();
        html = new String(bytes, "UTF-8"); //$NON-NLS-1$

    } catch (Exception e) {
        logger.error(e);
        html = showStatic();
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }
    final String BODY_TAG = "<body>"; //$NON-NLS-1$

    int afterBodyIdx = html.indexOf(BODY_TAG);
    if (-1 != afterBodyIdx) {
        html = html.substring(html.indexOf(BODY_TAG) + BODY_TAG.length());
        html = html.substring(0, html.indexOf("</body>")); //$NON-NLS-1$
    }

    return html;
}