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

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

Introduction

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

Prototype

public void setSoTimeout(int paramInt) 

Source Link

Usage

From source file:com.starit.diamond.client.impl.DefaultDiamondSubscriber.java

private void configureAckHttpMethod(HttpMethod httpMethod, long onceTimeOut) {
    // appName/*  w  ww.  ja  v  a2 s  . c om*/
    if (null != this.appName) {
        httpMethod.addRequestHeader(Constants.APPNAME, this.appName);
    }
    httpMethod.addRequestHeader(Constants.CLIENT_VERSION_HEADER, Constants.CLIENT_VERSION);

    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);

    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(
            diamondConfigure.getDomainNameList().get(this.domainNamePos.get()), diamondConfigure.getPort());
}

From source file:com.starit.diamond.client.impl.DefaultDiamondSubscriber.java

private void configureHttpMethod(boolean skipContentCache, CacheData cacheData, long onceTimeOut,
        HttpMethod httpMethod) {/*from w ww  .j a v  a2 s.  c om*/
    if (skipContentCache && null != cacheData) {
        if (null != cacheData.getLastModifiedHeader() && Constants.NULL != cacheData.getLastModifiedHeader()) {
            httpMethod.addRequestHeader(Constants.IF_MODIFIED_SINCE, cacheData.getLastModifiedHeader());
        }
        if (null != cacheData.getMd5() && Constants.NULL != cacheData.getMd5()) {
            httpMethod.addRequestHeader(Constants.CONTENT_MD5, cacheData.getMd5());
        }
    }
    // appName
    if (null != this.appName) {
        httpMethod.addRequestHeader(Constants.APPNAME, this.appName);
    }
    httpMethod.addRequestHeader(Constants.CLIENT_VERSION_HEADER, Constants.CLIENT_VERSION);

    httpMethod.addRequestHeader(Constants.ACCEPT_ENCODING, "gzip,deflate");

    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout((int) onceTimeOut);
    // ///////////////////////
    httpMethod.setParams(params);
    httpClient.getHostConfiguration().setHost(
            diamondConfigure.getDomainNameList().get(this.domainNamePos.get()), diamondConfigure.getPort());
}

From source file:com.starit.diamond.client.impl.DefaultDiamondSubscriber.java

/**
 * DiamondServer??DataID//from  ww w .  j  a va  2 s  .  co  m
 * 
 * @param timeout
 * @return
 */
Set<String> checkUpdateDataIds(long timeout) {
    if (!isRun) {
        throw new RuntimeException(
                "DiamondSubscriber????DataID");
    }
    // =======================?=======================
    if (MockServer.isTestMode()) {
        return testData();
    }
    // ==========================================================
    long waitTime = 0;

    String probeUpdateString = getProbeUpdateString();
    if (StringUtils.isBlank(probeUpdateString)) {
        return null;
    }

    while (0 == timeout || timeout > waitTime) {
        // 
        long onceTimeOut = getOnceTimeOut(waitTime, timeout);
        waitTime += onceTimeOut;

        PostMethod postMethod = new PostMethod(Constants.CONFIG_HTTP_URI_FILE);

        postMethod.addParameter(Constants.PROBE_MODIFY_REQUEST, probeUpdateString);

        if (null != this.appName) {
            postMethod.addRequestHeader(Constants.APPNAME, this.appName);
        }
        postMethod.addRequestHeader(Constants.CLIENT_VERSION_HEADER, Constants.CLIENT_VERSION);
        // HttpMethod?
        HttpMethodParams params = new HttpMethodParams();
        params.setSoTimeout((int) onceTimeOut);
        // ///////////////////////
        postMethod.setParams(params);

        try {
            httpClient.getHostConfiguration().setHost(
                    diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
                    this.diamondConfigure.getPort());

            int httpStatus = httpClient.executeMethod(postMethod);

            switch (httpStatus) {
            case SC_OK: {

                Set<String> result = getUpdateDataIds(postMethod);
                return result;
            }

            case SC_SERVICE_UNAVAILABLE: {
                rotateToNextDomain();
            }
                break;

            default: {
                log.warn("?DataIDHTTP State: " + httpStatus);
                rotateToNextDomain();
            }
            }
        } catch (HttpException e) {
            log.error("???Http" + e);
            rotateToNextDomain();
        } catch (IOException e) {
            log.error("???IO" + e);
            rotateToNextDomain();
        } catch (Exception e) {
            log.error("", e);
            rotateToNextDomain();
        } finally {
            postMethod.releaseConnection();
        }
    }
    throw new RuntimeException("?DataID "
            + diamondConfigure.getDomainNameList().get(this.domainNamePos.get()) + ", "
            + timeout);
}

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 av a  2s .c om*/

    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:org.apache.hadoop.fs.swift.http.SwiftRestClient.java

/**
 * Performs the HTTP request, validates the response code and returns
 * the received data. HTTP Status codes are converted into exceptions.
 *
 * @param uri       URI to source/*from w w w  .  j av a 2  s . c  o m*/
 * @param processor HttpMethodProcessor
 * @param <M>       method
 * @param <R>       result type
 * @return result of HTTP request
 * @throws IOException IO problems
 * @throws SwiftBadRequestException the status code indicated "Bad request"
 * @throws SwiftInvalidResponseException the status code is out of range
 * for the action (excluding 404 responses)
 * @throws SwiftInternalStateException the internal state of this client
 * is invalid
 * @throws FileNotFoundException a 404 response was returned
 */
private <M extends HttpMethod, R> R perform(URI uri, HttpMethodProcessor<M, R> processor)
        throws IOException, SwiftBadRequestException, SwiftInternalStateException,
        SwiftInvalidResponseException, FileNotFoundException {
    checkNotNull(uri);
    checkNotNull(processor);

    final M method = processor.createMethod(uri.toString());

    //retry policy
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(retryCount, false));
    methodParams.setSoTimeout(connectTimeout);

    try {
        int statusCode = exec(method);

        //look at the response and see if it was valid or not.
        //Valid is more than a simple 200; even 404 "not found" is considered
        //valid -which it is for many methods.

        //validate the allowed status code for this operation
        int[] allowedStatusCodes = processor.getAllowedStatusCodes();
        boolean validResponse = isStatusCodeExpected(statusCode, allowedStatusCodes);

        if (!validResponse) {
            IOException ioe = buildException(uri, method, statusCode);
            throw ioe;
        }

        return processor.extractResult(method);
    } catch (IOException e) {
        //release the connection -always

        method.releaseConnection();
        throw e;
    }
}

From source file:org.apache.maven.wagon.providers.webdav.HttpMethodConfiguration.java

private void fillParams(HttpMethodParams p) {
    if (!hasParams()) {
        return;//from  www.  ja v  a  2  s.c  o  m
    }

    if (connectionTimeout > 0) {
        p.setSoTimeout(connectionTimeout);
    }

    if (params != null) {
        Pattern coercePattern = Pattern.compile(COERCE_PATTERN);

        for (Map.Entry<Object, Object> entry : params.entrySet()) {
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();

            Matcher matcher = coercePattern.matcher(value);
            if (matcher.matches()) {
                char type = matcher.group(1).charAt(0);
                value = matcher.group(2);

                switch (type) {
                case 'i': {
                    p.setIntParameter(key, Integer.parseInt(value));
                    break;
                }
                case 'd': {
                    p.setDoubleParameter(key, Double.parseDouble(value));
                    break;
                }
                case 'l': {
                    p.setLongParameter(key, Long.parseLong(value));
                    break;
                }
                case 'b': {
                    p.setBooleanParameter(key, Boolean.valueOf(value).booleanValue());
                    break;
                }
                case 'c': {
                    String[] entries = value.split(",");
                    List<String> collection = new ArrayList<String>();
                    for (String e : entries) {
                        collection.add(e.trim());
                    }

                    p.setParameter(key, collection);
                    break;
                }
                case 'm': {
                    String[] entries = value.split(",");

                    Map<String, String> map = new LinkedHashMap<String, String>();
                    for (String e : entries) {
                        int idx = e.indexOf("=>");
                        if (idx < 1) {
                            break;
                        }

                        String mapKey = e.substring(0, idx);
                        String mapVal = e.substring(idx + 1, e.length());
                        map.put(mapKey.trim(), mapVal.trim());
                    }

                    p.setParameter(key, map);
                    break;
                }
                }
            } else {
                p.setParameter(key, value);
            }
        }
    }
}

From source file:org.eclipse.andmore.android.common.utilities.HttpUtils.java

private InputStream getInputStreamForUrl(String url, IProgressMonitor monitor, boolean returnStream)
        throws IOException {
    SubMonitor subMonitor = SubMonitor.convert(monitor);

    subMonitor.beginTask(UtilitiesNLS.HttpUtils_MonitorTask_PreparingConnection, 300);

    AndmoreLogger.debug(HttpUtils.class, "Verifying proxy usage for opening http connection"); //$NON-NLS-1$

    // Try to retrieve proxy configuration to use if necessary
    IProxyService proxyService = ProxyManager.getProxyManager();
    IProxyData proxyData = null;/*from w w w  .  j  av a  2  s. co  m*/
    if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) {
        Authenticator.setDefault(new NetAuthenticator());
        if (url.startsWith("https")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE);
            AndmoreLogger.debug(HttpUtils.class, "Using https proxy"); //$NON-NLS-1$
        } else if (url.startsWith("http")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE);
            AndmoreLogger.debug(HttpUtils.class, "Using http proxy"); //$NON-NLS-1$
        } else {
            AndmoreLogger.debug(HttpUtils.class, "Not using any proxy"); //$NON-NLS-1$
        }
    }

    // Creates the http client and the method to be executed
    HttpClient client = null;
    client = new HttpClient();

    // If there is proxy data, work with it
    if (proxyData != null) {
        if (proxyData.getHost() != null) {
            // Sets proxy host and port, if any
            client.getHostConfiguration().setProxy(proxyData.getHost(), proxyData.getPort());
        }

        if ((proxyData.getUserId() != null) && (proxyData.getUserId().trim().length() > 0)) {
            // Sets proxy user and password, if any
            Credentials cred = new UsernamePasswordCredentials(proxyData.getUserId(),
                    proxyData.getPassword() == null ? "" : proxyData.getPassword()); //$NON-NLS-1$
            client.getState().setProxyCredentials(AuthScope.ANY, cred);
        }
    }

    InputStream streamForUrl = null;
    getMethod = new GetMethod(url);
    getMethod.setFollowRedirects(true);

    // set a 30 seconds timeout
    HttpMethodParams params = getMethod.getParams();
    params.setSoTimeout(15 * ONE_SECOND);
    getMethod.setParams(params);

    boolean trying = true;
    Credentials credentials = null;
    subMonitor.worked(100);
    subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_ContactingSite);
    do {
        AndmoreLogger.info(HttpUtils.class, "Attempting to make a connection"); //$NON-NLS-1$

        // retry to connect to the site once, also set the timeout for 5
        // seconds
        HttpClientParams clientParams = client.getParams();
        clientParams.setIntParameter(HttpClientParams.MAX_REDIRECTS, 1);
        clientParams.setSoTimeout(5 * ONE_SECOND);
        client.setParams(clientParams);

        client.executeMethod(getMethod);
        if (subMonitor.isCanceled()) {
            break;
        } else {
            AuthState authorizationState = getMethod.getHostAuthState();
            String authenticationRealm = authorizationState.getRealm();

            if (getMethod.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                AndmoreLogger.debug(HttpUtils.class, "Client requested authentication; retrieving credentials"); //$NON-NLS-1$

                credentials = authenticationRealmCache.get(authenticationRealm);

                if (credentials == null) {
                    AndmoreLogger.debug(HttpUtils.class,
                            "Credentials not found; prompting user for login/password"); //$NON-NLS-1$

                    subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_WaitingAuthentication);

                    LoginPasswordDialogCreator dialogCreator = new LoginPasswordDialogCreator(url);
                    if (dialogCreator.openLoginPasswordDialog() == LoginPasswordDialogCreator.OK) {

                        credentials = new UsernamePasswordCredentials(dialogCreator.getTypedLogin(),
                                dialogCreator.getTypedPassword());
                    } else {
                        // cancel pressed; stop trying
                        trying = false;

                        // set the monitor canceled to be able to stop
                        // process
                        subMonitor.setCanceled(true);
                    }

                }

                if (credentials != null) {
                    AuthScope scope = new AuthScope(null, -1, authenticationRealm);
                    client.getState().setCredentials(scope, credentials);
                }

                subMonitor.worked(100);
            } else if (getMethod.getStatusCode() == HttpStatus.SC_OK) {
                AndmoreLogger.debug(HttpUtils.class, "Http connection suceeded"); //$NON-NLS-1$

                subMonitor.setTaskName(UtilitiesNLS.HttpUtils_MonitorTask_RetrievingSiteContent);
                if ((authenticationRealm != null) && (credentials != null)) {
                    authenticationRealmCache.put(authenticationRealm, credentials);
                } else {
                    // no authentication was necessary, just work the
                    // monitor
                    subMonitor.worked(100);
                }

                AndmoreLogger.info(HttpUtils.class, "Retrieving site content"); //$NON-NLS-1$

                // if the stream should not be returned (ex: only testing
                // the connection is
                // possible), then null will be returned
                if (returnStream) {
                    streamForUrl = getMethod.getResponseBodyAsStream();
                }

                // succeeded; stop trying
                trying = false;

                subMonitor.worked(100);
            } else {
                // unhandled return status code
                trying = false;

                subMonitor.worked(200);
            }
        }
    } while (trying);

    subMonitor.done();

    return streamForUrl;
}

From source file:org.eclipse.orion.server.cf.utils.HttpUtil.java

public static void configureHttpMethod(HttpMethod method, Target target) throws JSONException {
    method.addRequestHeader(new Header("Accept", "application/json"));
    method.addRequestHeader(new Header("Content-Type", "application/json"));
    //set default socket timeout for connection
    HttpMethodParams params = method.getParams();
    params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT);
    method.setParams(params);//from w  ww  . ja  v  a2 s .  com
    if (target.getCloud().getAccessToken() != null)
        method.addRequestHeader(new Header("Authorization",
                "bearer " + target.getCloud().getAccessToken().getString("access_token")));
}

From source file:org.eclipse.orion.server.cf.utils.HttpUtil.java

public static void configureHttpMethod(HttpMethod method, Cloud cloud) throws JSONException {
    method.addRequestHeader(new Header("Accept", "application/json"));
    method.addRequestHeader(new Header("Content-Type", "application/json"));
    //set default socket timeout for connection
    HttpMethodParams params = method.getParams();
    params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT);
    method.setParams(params);// ww  w .  j a va2s  .c  om
    if (cloud.getAccessToken() != null)
        method.addRequestHeader(
                new Header("Authorization", "bearer " + cloud.getAccessToken().getString("access_token")));
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static boolean isAlive(URL url) {
    boolean isAlive = false;
    boolean recheck = true;
    String key = toIsAliveKey(url);
    Pair<Integer, Long> lastChecked = isAliveMap.get(key);
    if (lastChecked != null) {
        long checkedOffset = System.currentTimeMillis() - lastChecked.getSecond().longValue();
        if (checkedOffset < CHECK_WINDOW) {
            recheck = false;/*from  w  w  w. ja  v a2 s . co m*/
            isAlive = lastChecked.getFirst() != -1;
        }
    }

    if (recheck) {
        try {
            GetMethod method = new GetMethod(url.toString());
            try {
                HttpMethodParams params = new HttpMethodParams();
                params.setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler(0, false));
                params.setSoTimeout(1000);
                method.setParams(params);
                int responseCode = executeMethod(url, method);
                if (responseCode == HttpURLConnection.HTTP_NOT_FOUND
                        || responseCode == HttpURLConnection.HTTP_ACCEPTED
                        || responseCode == HttpURLConnection.HTTP_ACCEPTED
                        || responseCode == HttpURLConnection.HTTP_OK) {
                    isAlive = true;
                }
            } finally {
                method.releaseConnection();
            }
        } catch (Exception ex) {
            // Do Nothing
        }
    }
    return isAlive;
}