Example usage for org.apache.commons.httpclient HttpClient setTimeout

List of usage examples for org.apache.commons.httpclient HttpClient setTimeout

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient setTimeout.

Prototype

public void setTimeout(int paramInt)

Source Link

Usage

From source file:org.activebpel.rt.axis.bpel.handlers.AeHTTPSender.java

/**
 * Extracts info from message context./*from   ww w  . j  a v  a2 s. co  m*/
 *
 * @param method Post method
 * @param httpClient The client used for posting
 * @param msgContext the message context
 * @param tmpURL the url to post to.
 *
 * @throws Exception
 * @deprecated
 */
private void addContextInfo(HttpMethodBase method, HttpClient httpClient, MessageContext msgContext, URL tmpURL)
        throws Exception {

    // optionally set a timeout for the request
    if (msgContext.getTimeout() != 0) {
        /* ISSUE: these are not the same, but MessageContext has only one
         definition of timeout */
        // SO_TIMEOUT -- timeout for blocking reads
        httpClient.setTimeout(msgContext.getTimeout());
        // timeout for initial connection
        httpClient.setConnectionTimeout(msgContext.getTimeout());
    }

    // Get SOAPAction, default to ""
    String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; //$NON-NLS-1$

    if (action == null) {
        action = ""; //$NON-NLS-1$
    }
    Message msg = msgContext.getRequestMessage();
    if (msg != null) {
        method.setRequestHeader(new Header(HTTPConstants.HEADER_CONTENT_TYPE,
                msg.getContentType(msgContext.getSOAPConstants())));
    }
    method.setRequestHeader(new Header(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\"")); //$NON-NLS-1$ //$NON-NLS-2$
    String userID = msgContext.getUsername();
    String passwd = msgContext.getPassword();

    // if UserID is not part of the context, but is in the URL, use
    // the one in the URL.
    if ((userID == null) && (tmpURL.getUserInfo() != null)) {
        String info = tmpURL.getUserInfo();
        int sep = info.indexOf(':');

        if ((sep >= 0) && (sep + 1 < info.length())) {
            userID = info.substring(0, sep);
            passwd = info.substring(sep + 1);
        } else {
            userID = info;
        }
    }
    if (userID != null) {
        Credentials cred = new UsernamePasswordCredentials(userID, passwd);
        httpClient.getState().setCredentials(null, null, cred);

        // Change #2
        //
        // Comment out the lines below since they force all authentication
        // to be Basic. This is a problem if the web service you're invoking 
        // is expecting Digest.

        // The following 3 lines should NOT be required. But Our SimpleAxisServer fails
        // during all-tests if this is missing.
        //            StringBuffer tmpBuf = new StringBuffer();
        //            tmpBuf.append(userID).append(":").append((passwd == null) ? "" : passwd);
        //            method.addRequestHeader(HTTPConstants.HEADER_AUTHORIZATION, "Basic " + Base64.encode(tmpBuf.toString().getBytes()));
    }

    // Transfer MIME headers of SOAPMessage to HTTP headers.
    MimeHeaders mimeHeaders = msg.getMimeHeaders();
    if (mimeHeaders != null) {
        for (Iterator i = mimeHeaders.getAllHeaders(); i.hasNext();) {
            MimeHeader mimeHeader = (MimeHeader) i.next();
            method.addRequestHeader(mimeHeader.getName(), mimeHeader.getValue());
        }
    }

    // process user defined headers for information.
    Hashtable userHeaderTable = (Hashtable) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);

    if (userHeaderTable != null) {
        for (java.util.Iterator e = userHeaderTable.entrySet().iterator(); e.hasNext();) {
            java.util.Map.Entry me = (java.util.Map.Entry) e.next();
            Object keyObj = me.getKey();

            if (null == keyObj) {
                continue;
            }
            String key = keyObj.toString().trim();
            String value = me.getValue().toString().trim();

            method.addRequestHeader(key, value);
        }
    }
}

From source file:org.apache.ivy.util.url.HttpClientHandler.java

private GetMethod doGet(URL url, int timeout) throws IOException {
    HttpClient client = getClient();
    client.setTimeout(timeout);

    GetMethod get = new GetMethod(normalizeToString(url));
    get.setDoAuthentication(useAuthentication(url) || useProxyAuthentication());
    get.setRequestHeader("Accept-Encoding", "gzip,deflate");
    client.executeMethod(get);/* w  ww.jav  a  2  s . c  o  m*/
    return get;
}

From source file:org.apache.ivy.util.url.HttpClientHandler.java

private HeadMethod doHead(URL url, int timeout) throws IOException {
    HttpClient client = getClient();
    client.setTimeout(timeout);

    HeadMethod head = new HeadMethod(normalizeToString(url));
    head.setDoAuthentication(useAuthentication(url) || useProxyAuthentication());
    client.executeMethod(head);/*from w  w  w  . ja  v a 2s  .  c  om*/
    return head;
}

From source file:org.apache.taverna.raven.plugins.ui.CheckForNoticeStartupHook.java

public boolean startup() {

    if (GraphicsEnvironment.isHeadless()) {
        return true; // if we are running headlessly just return
    }// w w  w . java2 s.com

    long noticeTime = -1;
    long lastCheckedTime = -1;

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(TIMEOUT);
    client.setTimeout(TIMEOUT);
    PluginManager.setProxy(client);
    String message = null;

    try {
        URI noticeURI = new URI(BASE_URL + "/" + version + "/" + SUFFIX);
        HttpMethod method = new GetMethod(noticeURI.toString());
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("HTTP status " + statusCode + " while getting " + noticeURI);
            return true;
        }
        String noticeTimeString = null;
        Header h = method.getResponseHeader("Last-Modified");
        message = method.getResponseBodyAsString();
        if (h != null) {
            noticeTimeString = h.getValue();
            noticeTime = format.parse(noticeTimeString).getTime();
            logger.info("NoticeTime is " + noticeTime);
        }

    } catch (URISyntaxException e) {
        logger.error("URI problem", e);
        return true;
    } catch (IOException e) {
        logger.info("Could not read notice", e);
    } catch (ParseException e) {
        logger.error("Could not parse last-modified time", e);
    }

    if (lastNoticeCheckFile.exists()) {
        lastCheckedTime = lastNoticeCheckFile.lastModified();
    }

    if ((message != null) && (noticeTime != -1)) {
        if (noticeTime > lastCheckedTime) {
            // Show the notice dialog
            JOptionPane.showMessageDialog(null, message, "Taverna notice", JOptionPane.INFORMATION_MESSAGE,
                    WorkbenchIcons.tavernaCogs64x64Icon);
            try {
                FileUtils.touch(lastNoticeCheckFile);
            } catch (IOException e) {
                logger.error("Unable to touch file", e);
            }
        }
    }
    return true;
}

From source file:org.dspace.submit.lookup.CiNiiService.java

/**
 * Get metadata by searching CiNii RDF API with CiNii NAID
 *
 *///  w  w w .  ja v a  2 s .c  o m
private Record search(String id, String appId) throws IOException, HttpException {
    GetMethod method = null;
    try {
        HttpClient client = new HttpClient();
        client.setTimeout(timeout);
        method = new GetMethod("http://ci.nii.ac.jp/naid/" + id + ".rdf?appid=" + appId);
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode == HttpStatus.SC_BAD_REQUEST)
                throw new RuntimeException("CiNii RDF is not valid");
            else
                throw new RuntimeException("CiNii RDF Http call failed: " + method.getStatusLine());
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(true);

            DocumentBuilder db = factory.newDocumentBuilder();
            Document inDoc = db.parse(method.getResponseBodyAsStream());

            Element xmlRoot = inDoc.getDocumentElement();

            return CiNiiUtils.convertCiNiiDomToRecord(xmlRoot);
        } catch (Exception e) {
            throw new RuntimeException("CiNii RDF identifier is not valid or not exist");
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.dspace.submit.lookup.CiNiiService.java

/**
 * Get CiNii NAIDs by searching CiNii OpenURL API with title, author and year
 *
 *//* w  w  w .  j av  a 2  s  .  c  om*/
private List<String> getCiNiiIDs(String title, String author, int year, int maxResults, String appId)
        throws IOException, HttpException {
    // Need at least one query term
    if (title == null && author == null && year == -1) {
        return null;
    }

    GetMethod method = null;
    List<String> ids = new ArrayList<String>();
    try {
        HttpClient client = new HttpClient();
        client.setTimeout(timeout);
        StringBuilder query = new StringBuilder();
        query.append("format=rss&appid=").append(appId).append("&count=").append(maxResults);
        if (title != null) {
            query.append("&title=").append(URLEncoder.encode(title, "UTF-8"));
        }
        if (author != null) {
            query.append("&author=").append(URLEncoder.encode(author, "UTF-8"));
        }
        if (year != -1) {
            query.append("&year_from=").append(String.valueOf(year));
            query.append("&year_to=").append(String.valueOf(year));
        }
        method = new GetMethod("http://ci.nii.ac.jp/opensearch/search?" + query.toString());
        // Execute the method.
        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode == HttpStatus.SC_BAD_REQUEST)
                throw new RuntimeException("CiNii OpenSearch query is not valid");
            else
                throw new RuntimeException("CiNii OpenSearch call failed: " + method.getStatusLine());
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setValidating(false);
            factory.setIgnoringComments(true);
            factory.setIgnoringElementContentWhitespace(true);

            DocumentBuilder db = factory.newDocumentBuilder();
            Document inDoc = db.parse(method.getResponseBodyAsStream());

            Element xmlRoot = inDoc.getDocumentElement();
            List<Element> items = XMLUtils.getElementList(xmlRoot, "item");

            int url_len = "http://ci.nii.ac.jp/naid/".length();
            for (Element item : items) {
                String about = item.getAttribute("rdf:about");
                if (about.length() > url_len) {
                    ids.add(about.substring(url_len));
                }
            }

            return ids;
        } catch (Exception e) {
            throw new RuntimeException("CiNii OpenSearch results is not valid or not exist");
        }
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.jboss.web.loadbalancer.Loadbalancer.java

protected HttpClient prepareServerRequest(HttpServletRequest request, HttpServletResponse response,
        HttpMethod method) {/*from  w w  w  .  j  a va  2 s  .c o m*/
    // clear state
    HttpClient client = new HttpClient(connectionManager);
    client.setStrictMode(false);
    client.setTimeout(connectionTimeout);
    method.setFollowRedirects(false);
    method.setDoAuthentication(false);
    client.getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);

    Enumeration reqHeaders = request.getHeaderNames();

    while (reqHeaders.hasMoreElements()) {
        String headerName = (String) reqHeaders.nextElement();
        String headerValue = request.getHeader(headerName);

        if (!ignorableHeader.contains(headerName.toLowerCase())) {
            method.setRequestHeader(headerName, headerValue);
        }
    }

    //Cookies
    Cookie[] cookies = request.getCookies();
    HttpState state = client.getState();

    for (int i = 0; cookies != null && i < cookies.length; ++i) {
        Cookie cookie = cookies[i];

        org.apache.commons.httpclient.Cookie reqCookie = new org.apache.commons.httpclient.Cookie();

        reqCookie.setName(cookie.getName());
        reqCookie.setValue(cookie.getValue());

        if (cookie.getPath() != null) {
            reqCookie.setPath(cookie.getPath());
        } else {
            reqCookie.setPath("/");
        }

        reqCookie.setSecure(cookie.getSecure());

        reqCookie.setDomain(method.getHostConfiguration().getHost());
        state.addCookie(reqCookie);
    }
    return client;
}

From source file:org.methodize.nntprss.feed.Channel.java

private HttpClient getHttpClient() {
    HttpClient httpClient = new HttpClient();
    httpClient.setConnectionTimeout(HTTP_CONNECTION_TIMEOUT);
    httpClient.setTimeout(HTTP_CONNECTION_TIMEOUT);

    // Initialize user id / password for protected feeds
    if (url.getUserInfo() != null) {
        httpClient.getState().setCredentials(null, null,
                new UsernamePasswordCredentials(URLDecoder.decode(url.getUserInfo())));
    }//  w w  w.j  a v a2s. com
    return httpClient;

}

From source file:pkg4.pkg0.Engine.java

void get() {
    try {//from  w  w  w . java 2 s  . c o  m
        Getmethod = new GetMethod(url);
        Getmethod.addRequestHeader("Host", host);
        Getmethod.addRequestHeader("User-Agent",
                " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
        Getmethod.addRequestHeader("Accept",
                "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5");
        Getmethod.addRequestHeader("Accept-Language", "en-US,en;q=0.8");
        Getmethod.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
        Getmethod.addRequestHeader("X-Client-Data", "CKK2yQEIxLbJAQj9lcoB");
        Getmethod.addRequestHeader("Connection", "keepalive,Keep-Alive");
        Getmethod.addRequestHeader("Cookie", cookie);
        Getmethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        Getmethod.addRequestHeader("Content-Length", "" + body.length());
        Getmethod.getFollowRedirects();
        Getmethod.setFollowRedirects(true);
        HttpClient client = new HttpClient();
        client.setTimeout(20000);
        client.setConnectionTimeout(15000);
        int status = client.executeMethod(Getmethod);
        respone = Getmethod.getResponseBodyAsString();

    } catch (Exception m) {
        post();
        m.printStackTrace();
    }
}

From source file:pkg4.pkg0.Engine.java

void post() {
    try {/*  w  w w.  ja  va  2 s . co  m*/
        PostMethod Postmethod = new PostMethod(url);
        Postmethod.addRequestHeader("Host", host);
        Postmethod.addRequestHeader("User-Agent",
                " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
        Postmethod.addRequestHeader("Accept",
                "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5");
        Postmethod.addRequestHeader("Accept-Language", "en-US,en;q=0.8");
        Postmethod.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
        Postmethod.addRequestHeader("X-Client-Data", "CKK2yQEIxLbJAQj9lcoB");
        Postmethod.addRequestHeader("Connection", "keepalive,Keep-Alive");
        Postmethod.addRequestHeader("Cookie", cookie);
        Postmethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        Postmethod.setRequestBody(body);
        Postmethod.addRequestHeader("Content-Length", "" + body.length());
        Postmethod.getFollowRedirects();
        Postmethod.setFollowRedirects(true);
        HttpClient client = new HttpClient();
        client.setTimeout(20000);
        client.setConnectionTimeout(15000);
        int status = client.executeMethod(Postmethod);
        respone = Postmethod.getResponseBodyAsString();

    } catch (Exception m) {
        post();
        m.printStackTrace();
    }
}