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.ibm.stocator.fs.swift.SwiftAPIDirect.java

/**
 * GET object//  ww w . j av a 2s.c o m
 *
 * @param path path to object
 * @param authToken authentication token
 * @param bytesFrom from from
 * @param bytesTo bytes to
 * @return SwiftGETResponse that includes input stream and length
 * @throws IOException if network errors
 */
public static SwiftGETResponse getObject(Path path, String authToken, long bytesFrom, long bytesTo)
        throws IOException {
    GetMethod method = new GetMethod(path.toString());
    method.addRequestHeader(new Header("X-Auth-Token", authToken));
    if (bytesTo > 0) {
        final String rangeValue = String.format("bytes=%d-%d", bytesFrom, bytesTo);
        method.addRequestHeader(new Header(Constants.RANGES_HTTP_HEADER, rangeValue));
    }
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    methodParams.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 15000);
    methodParams.setSoTimeout(60000);
    method.addRequestHeader(Constants.USER_AGENT_HTTP_HEADER, Constants.STOCATOR_USER_AGENT);
    final HttpClient client = new HttpClient();
    int statusCode = client.executeMethod(method);
    SwiftInputStreamWrapper httpStream = new SwiftInputStreamWrapper(method);
    SwiftGETResponse getResponse = new SwiftGETResponse(httpStream, method.getResponseContentLength());
    return getResponse;
}

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

/**
 * @return the http response code returned from the server. Response code 200 means success.
 *///w w w  .j  a v  a2s .  c o m
public static int fastFailPing(AuthenticatedUrl url) throws IOException {
    PingRequest pingRequest = null;
    try {
        HttpClient httpClient = getHttpClient(url);
        pingRequest = new PingRequest(url.getPath());
        HttpMethodParams params = pingRequest.getParams();
        params.setSoTimeout(PING_TIMEOUT);
        httpClient.executeMethod(pingRequest);
        return pingRequest.getStatusCode();
    } finally {
        if (pingRequest != null) {
            pingRequest.releaseConnection();
        }
    }
}

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

public static Cookie[] requestNewSession(AuthenticatedUrl url) {
    CreateSessionRequest createSessionRequest = null;
    try {//from   ww w. j a v a 2  s.c  o  m
        HttpClient httpClient = getHttpClient(url);
        createSessionRequest = new CreateSessionRequest(url.getPath());
        HttpMethodParams params = createSessionRequest.getParams();
        params.setSoTimeout(PING_TIMEOUT);
        httpClient.executeMethod(createSessionRequest);
        return httpClient.getState().getCookies();
    } catch (Exception e) {
        throw new RuntimeException("Failed to create session", e);
    } finally {
        if (createSessionRequest != null) {
            createSessionRequest.releaseConnection();
        }
    }
}

From source file:com.cordys.coe.ac.httpconnector.execution.MethodExecutor.java

/**
 * Send the HTTP request to the web server and returns the response.
 * //from w  w  w .  ja  v a 2 s .  c  o  m
 * @param reqNode
 *            Request XML node.
 * @param serverConnection
 *            Server connection information.
 * @param methodInfo
 *            Method information information.
 * @param counters
 *            JMX performance counters
 * @return Response XML node.
 * @throws ConnectorException
 * @throws HandlerException
 */
public static int sendRequest(int reqNode, IServerConnection serverConnection, IMethodConfiguration methodInfo,
        PerformanceCounters counters) throws ConnectorException, HandlerException {
    boolean setJMXInfo = counters == null ? false : true;
    // Get request and response handlers for converting the data.
    IRequestHandler requestHandler = methodInfo.getRequestHandler();
    IResponseHandler responseHandler = methodInfo.getResponseHandler();

    // Create the connection
    HttpClient client = serverConnection.getHttpClient();

    client.getParams().setContentCharset("UTF-8");
    client.getParams().setCredentialCharset("UTF-8");
    client.getParams().setHttpElementCharset("UTF-8");

    HttpMethod httpMethod;
    int timeout = serverConnection.getTimeout();

    // Convert the SOAP request XML into an HTTP request.
    long startTime = 0;
    if (setJMXInfo) {
        startTime = counters.getStartTime();
    }
    httpMethod = requestHandler.process(reqNode, serverConnection, client);
    if (setJMXInfo) {
        counters.finishRequestTransformation(startTime);
    }

    // Set additional HTTP parameters.
    HttpMethodParams hmpMethodParams = httpMethod.getParams();

    if (hmpMethodParams != null) {
        // Set the authentication character set to UTF-8, if not set.
        String sCredCharset = hmpMethodParams.getCredentialCharset();

        if ((sCredCharset == null) || (sCredCharset.length() == 0)) {
            hmpMethodParams.setCredentialCharset("UTF-8");
        }

        if (timeout > 0) {
            hmpMethodParams.setSoTimeout(timeout);
        }
    }

    // Send the request and handle the response.
    try {
        if (setJMXInfo) {
            startTime = counters.getStartTime();
        }
        int statusCode = client.executeMethod(httpMethod);
        if (setJMXInfo) {
            counters.finishHTTP(startTime);
        }
        int validStatusCode = methodInfo.getValidResponseCode();

        if (statusCode != HttpStatus.SC_OK) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Received HTTP error code: " + statusCode);
            }
        }

        if (setJMXInfo) {
            startTime = counters.getStartTime();
        }
        // Convert the response into XML.
        int responseNode = responseHandler.convertResponseToXml(httpMethod, serverConnection,
                Node.getDocument(reqNode));
        if (setJMXInfo) {
            counters.finishResponseTransformation(startTime);
        }
        if ((validStatusCode >= 0) && (statusCode != validStatusCode)) {
            if (responseNode != 0) {
                Node.delete(responseNode);
                responseNode = 0;
            }

            throw new ConnectorException(ConnectorExceptionMessages.INVALID_STATUS_CODE_RECEIVED_0_EXPECTED_1,
                    statusCode, validStatusCode);
        }

        return responseNode;
    } catch (ConnectorException e) {
        throw e;
    } catch (HttpException e) {
        throw new ConnectorException(e, ConnectorExceptionMessages.HTTP_REQUEST_FAILED_0, e.getMessage());
    } catch (IOException e) {
        throw new ConnectorException(e, ConnectorExceptionMessages.HTTP_CONNECTION_FAILED_0, e.getMessage());
    } catch (XMLException e) {
        throw new ConnectorException((Throwable) e, ConnectorExceptionMessages.INVALID_RESPONSE_XML_RECEIVED);
    } finally {
        // Release the connection.
        httpMethod.releaseConnection();
    }
}

From source file:com.zimbra.cs.service.FeedManager.java

private static RemoteDataInfo retrieveRemoteData(String url, Folder.SyncData fsd)
        throws ServiceException, HttpException, IOException {
    assert !Strings.isNullOrEmpty(url);

    HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(client);

    // cannot set connection timeout because it'll affect all HttpClients associated with the conn mgr.
    // see comments in ZimbraHttpConnectionManager
    // client.setConnectionTimeout(10000);

    HttpMethodParams params = new HttpMethodParams();
    params.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, MimeConstants.P_CHARSET_UTF8);
    params.setSoTimeout(60000);

    GetMethod get = null;/*from  w w  w  .  ja  v a 2  s.  c  om*/
    BufferedInputStream content = null;
    long lastModified = 0;
    String expectedCharset = MimeConstants.P_CHARSET_UTF8;
    int redirects = 0;
    int statusCode = HttpServletResponse.SC_NOT_FOUND;
    try {
        do {
            String lcurl = url.toLowerCase();
            if (lcurl.startsWith("webcal:")) {
                url = "http:" + url.substring(7);
            } else if (lcurl.startsWith("feed:")) {
                url = "http:" + url.substring(5);
            } else if (!lcurl.startsWith("http:") && !lcurl.startsWith("https:")) {
                throw ServiceException.INVALID_REQUEST("url must begin with http: or https:", null);
            }

            // username and password are encoded in the URL as http://user:pass@host/...
            if (url.indexOf('@') != -1) {
                HttpURL httpurl = lcurl.startsWith("https:") ? new HttpsURL(url) : new HttpURL(url);
                if (httpurl.getUser() != null) {
                    String user = httpurl.getUser();
                    if (user.indexOf('%') != -1) {
                        try {
                            user = URLDecoder.decode(user, "UTF-8");
                        } catch (OutOfMemoryError e) {
                            Zimbra.halt("out of memory", e);
                        } catch (Throwable t) {
                        }
                    }
                    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user,
                            httpurl.getPassword());
                    client.getParams().setAuthenticationPreemptive(true);
                    client.getState().setCredentials(AuthScope.ANY, creds);
                }
            }

            try {
                get = new GetMethod(url);
            } catch (OutOfMemoryError e) {
                Zimbra.halt("out of memory", e);
                return null;
            } catch (Throwable t) {
                throw ServiceException.INVALID_REQUEST("invalid url for feed: " + url, t);
            }
            get.setParams(params);
            get.setFollowRedirects(true);
            get.setDoAuthentication(true);
            get.addRequestHeader("User-Agent", HTTP_USER_AGENT);
            get.addRequestHeader("Accept", HTTP_ACCEPT);
            if (fsd != null && fsd.getLastSyncDate() > 0) {
                String lastSyncAt = org.apache.commons.httpclient.util.DateUtil
                        .formatDate(new Date(fsd.getLastSyncDate()));
                get.addRequestHeader("If-Modified-Since", lastSyncAt);
            }
            HttpClientUtil.executeMethod(client, get);

            Header locationHeader = get.getResponseHeader("location");
            if (locationHeader != null) {
                // update our target URL and loop again to do another HTTP GET
                url = locationHeader.getValue();
                get.releaseConnection();
            } else {
                statusCode = get.getStatusCode();
                if (statusCode == HttpServletResponse.SC_OK) {
                    Header contentEncoding = get.getResponseHeader("Content-Encoding");
                    InputStream respInputStream = get.getResponseBodyAsStream();
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().indexOf("gzip") != -1) {
                            respInputStream = new GZIPInputStream(respInputStream);
                        }
                    }
                    content = new BufferedInputStream(respInputStream);
                    expectedCharset = get.getResponseCharSet();

                    Header lastModHdr = get.getResponseHeader("Last-Modified");
                    if (lastModHdr == null) {
                        lastModHdr = get.getResponseHeader("Date");
                    }
                    if (lastModHdr != null) {
                        try {
                            Date d = org.apache.commons.httpclient.util.DateUtil
                                    .parseDate(lastModHdr.getValue());
                            lastModified = d.getTime();
                        } catch (DateParseException e) {
                            ZimbraLog.misc.warn(
                                    "unable to parse Last-Modified/Date header: " + lastModHdr.getValue(), e);
                            lastModified = System.currentTimeMillis();
                        }
                    } else {
                        lastModified = System.currentTimeMillis();
                    }
                } else if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
                    ZimbraLog.misc.debug("Remote data at " + url + " not modified since last sync");
                    return new RemoteDataInfo(statusCode, redirects, null, expectedCharset, lastModified);
                } else {
                    throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusLine().toString(), null);
                }
                break;
            }
        } while (++redirects <= MAX_REDIRECTS);
    } catch (ServiceException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    } catch (HttpException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    } catch (IOException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    }
    RemoteDataInfo rdi = new RemoteDataInfo(statusCode, redirects, content, expectedCharset, lastModified);
    rdi.setGetMethod(get);
    return rdi;
}

From source file:com.motorola.studio.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);

    StudioLogger.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;//  w  w  w . j  a v  a  2  s  . c om
    if (proxyService.isProxiesEnabled() || proxyService.isSystemProxiesEnabled()) {
        Authenticator.setDefault(new NetAuthenticator());
        if (url.startsWith("https")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTPS_PROXY_TYPE);
            StudioLogger.debug(HttpUtils.class, "Using https proxy"); //$NON-NLS-1$
        } else if (url.startsWith("http")) {
            proxyData = proxyService.getProxyData(IProxyData.HTTP_PROXY_TYPE);
            StudioLogger.debug(HttpUtils.class, "Using http proxy"); //$NON-NLS-1$
        } else {
            StudioLogger.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 {
        StudioLogger.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) {
                StudioLogger.debug(HttpUtils.class, "Client requested authentication; retrieving credentials"); //$NON-NLS-1$

                credentials = authenticationRealmCache.get(authenticationRealm);

                if (credentials == null) {
                    StudioLogger.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) {
                StudioLogger.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);
                }

                StudioLogger.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:com.taobao.diamond.client.processor.ServerAddressProcessor.java

/**
 * diamond//from  ww w .j  a  v  a 2  s  .c om
 * 
 * @param acquireCount
 *            01
 * @return
 */
private boolean acquireServerAddressOnce(int acquireCount) {
    HostConfiguration hostConfiguration = configHttpClient.getHostConfiguration();
    String configServerAddress;
    int port;
    if (null != diamondConfigure.getConfigServerAddress()) {
        configServerAddress = diamondConfigure.getConfigServerAddress();
        port = diamondConfigure.getConfigServerPort();
    } else {
        if (acquireCount == 0) {
            configServerAddress = Constants.DEFAULT_DOMAINNAME;
            port = Constants.DEFAULT_PORT;
        } else {
            configServerAddress = Constants.DAILY_DOMAINNAME;
            port = Constants.DEFAULT_PORT;
        }
    }
    hostConfiguration.setHost(configServerAddress, port);

    String serverAddressUrl = Constants.CONFIG_HTTP_URI_FILE;

    HttpMethod httpMethod = new GetMethod(serverAddressUrl);
    // HttpMethod
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout(diamondConfigure.getOnceTimeout());
    // ///////////////////////
    httpMethod.setParams(params);

    try {
        if (SC_OK == configHttpClient.executeMethod(httpMethod)) {
            InputStreamReader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            String address = null;
            List<String> newDomainNameList = new LinkedList<String>();
            while ((address = bufferedReader.readLine()) != null) {
                address = address.trim();
                if (StringUtils.isNotBlank(address)) {
                    newDomainNameList.add(address);
                }
            }
            if (newDomainNameList.size() > 0) {
                log.debug("");
                this.diamondConfigure.setDomainNameList(newDomainNameList);
                return true;
            }
        } else {
            log.warn("");
        }
    } catch (HttpException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (IOException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (Exception e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } finally {
        httpMethod.releaseConnection();
    }
    return false;
}

From source file:cn.leancloud.diamond.client.processor.ServerAddressProcessor.java

/**
 * ?diamond??//from   w  ww . j  ava2s  .c o m
 * 
 * @param acquireCount
 *            ?01?
 * @return
 */
private boolean acquireServerAddressOnce(int acquireCount) {
    HostConfiguration hostConfiguration = configHttpClient.getHostConfiguration();
    String configServerAddress;
    int port;
    if (null != diamondConfigure.getConfigServerAddress()) {
        configServerAddress = diamondConfigure.getConfigServerAddress();
        port = diamondConfigure.getConfigServerPort();
    } else {
        if (acquireCount == 0) {
            configServerAddress = Constants.DEFAULT_DOMAINNAME;
            port = Constants.DEFAULT_PORT;
        } else {
            configServerAddress = Constants.DAILY_DOMAINNAME;
            port = Constants.DEFAULT_PORT;
        }
    }
    hostConfiguration.setHost(configServerAddress, port);

    String serverAddressUrl = Constants.CONFIG_HTTP_URI_FILE;

    HttpMethod httpMethod = new GetMethod(serverAddressUrl);
    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout(diamondConfigure.getOnceTimeout());
    // ///////////////////////
    httpMethod.setParams(params);

    try {
        if (SC_OK == configHttpClient.executeMethod(httpMethod)) {
            InputStreamReader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            String address = null;
            List<String> newDomainNameList = new LinkedList<String>();
            while ((address = bufferedReader.readLine()) != null) {
                address = address.trim();
                if (StringUtils.isNotBlank(address)) {
                    newDomainNameList.add(address);
                }
            }
            if (newDomainNameList.size() > 0) {
                log.debug("?");
                this.diamondConfigure.setDomainNameList(newDomainNameList);
                return true;
            }
        } else {
            log.warn("??");
        }
    } catch (HttpException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (IOException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (Exception e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } finally {
        httpMethod.releaseConnection();
    }
    return false;
}

From source file:com.starit.diamond.client.processor.ServerAddressProcessor.java

/**
 * ?diamond??/*from  w ww . j  a  v a 2s.co m*/
 * 
 * @param acquireCount
 *            ?01?
 * @return
 */
private boolean acquireServerAddressOnce(int acquireCount) {
    HostConfiguration hostConfiguration = configHttpClient.getHostConfiguration();
    String configServerAddress;
    int port;
    if (null != diamondConfigure.getConfigServerAddress()) {
        configServerAddress = diamondConfigure.getConfigServerAddress();
        port = diamondConfigure.getConfigServerPort();
    } else {
        if (acquireCount == 0) {
            configServerAddress = Constants.DEFAULT_DOMAINNAME;
            port = Constants.DEFAULT_PORT;
        } else {
            configServerAddress = Constants.DAILY_DOMAINNAME;
            port = Constants.DEFAULT_PORT;
        }
    }
    hostConfiguration.setHost(configServerAddress, port);

    // ??serverURL by leiwen
    String serverAddressUrl = Constants.BASE_URI + "/" + clusterType;

    HttpMethod httpMethod = new GetMethod(serverAddressUrl);
    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout(diamondConfigure.getOnceTimeout());
    // ///////////////////////
    httpMethod.setParams(params);

    try {
        if (SC_OK == configHttpClient.executeMethod(httpMethod)) {
            InputStreamReader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            String address = null;
            List<String> newDomainNameList = new LinkedList<String>();
            while ((address = bufferedReader.readLine()) != null) {
                address = address.trim();
                if (StringUtils.isNotBlank(address)) {
                    newDomainNameList.add(address);
                }
            }
            if (newDomainNameList.size() > 0) {
                log.debug("?");
                this.diamondConfigure.setDomainNameList(newDomainNameList);
                return true;
            }
        } else {
            log.warn("??");
        }
    } catch (HttpException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (IOException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (Exception e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } finally {
        httpMethod.releaseConnection();
    }
    return false;
}

From source file:com.mengka.diamond.client.processor.ServerAddressProcessor.java

/**
 * ?diamond??//from ww  w  .j a  v a2 s .  com
 * 
 * @param acquireCount
 *            ?01?
 * @return
 */
private boolean acquireServerAddressOnce(int acquireCount) {
    HostConfiguration hostConfiguration = configHttpClient.getHostConfiguration();
    String configServerAddress;
    int port;
    if (null != diamondConfigure.getConfigServerAddress()) {
        configServerAddress = diamondConfigure.getConfigServerAddress();
        port = diamondConfigure.getConfigServerPort();
    } else {
        if (acquireCount == 0) {
            configServerAddress = Constants.CONFIG_DEFAULT_DOMAINNAME;
            port = Constants.CONFIG_DEFAULT_PORT;
        } else {
            configServerAddress = Constants.CONFIG_DAILY_DOMAINNAME;
            port = Constants.CONFIG_DEFAULT_PORT;
        }
    }
    hostConfiguration.setHost(configServerAddress, port);

    String serverAddressUrl = Constants.SERVER_ADDRESS_URI;

    HttpMethod httpMethod = new GetMethod(serverAddressUrl);
    // HttpMethod?
    HttpMethodParams params = new HttpMethodParams();
    params.setSoTimeout(diamondConfigure.getOnceTimeout());
    // ///////////////////////
    httpMethod.setParams(params);

    try {
        if (SC_OK == configHttpClient.executeMethod(httpMethod)) {
            InputStreamReader reader = new InputStreamReader(httpMethod.getResponseBodyAsStream());
            BufferedReader bufferedReader = new BufferedReader(reader);
            String address = null;
            List<String> newDomainNameList = new LinkedList<String>();
            while ((address = bufferedReader.readLine()) != null) {
                address = address.trim();
                if (StringUtils.isNotBlank(address) && !address.startsWith("#")) {
                    if (address.contains(":")) {
                        address = address.substring(0, address.indexOf(":"));
                    }
                    if (address.contains("\\")) {
                        address = address.substring(0, address.indexOf("\\"));
                    }
                    if (address.contains("/")) {
                        address = address.substring(0, address.indexOf("/"));
                    }
                    newDomainNameList.add(address);
                }
            }
            if (newDomainNameList.size() > 0) {
                log.debug("?");
                this.diamondConfigure.setDomainNameList(newDomainNameList);
                return true;
            }
        } else {
            log.error("??, hostsconfig.tbj.com");
        }
    } catch (HttpException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (IOException e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } catch (Exception e) {
        log.error(getErrorMessage(configServerAddress) + ", " + e);
    } finally {
        httpMethod.releaseConnection();
    }
    return false;
}