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

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

Introduction

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

Prototype

public int executeMethod(HttpMethod paramHttpMethod) throws IOException, HttpException 

Source Link

Usage

From source file:com.cloud.test.regression.ApiCommand.java

public static boolean verifyEvents(HashMap<String, Integer> expectedEvents, String level, String host,
        String parameters) {/*from  ww  w  .ja  v a 2  s  .  c o  m*/
    boolean result = false;
    HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
    try {
        // get actual events
        String url = host + "/?command=listEvents&" + parameters;
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        int responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            InputStream is = method.getResponseBodyAsStream();
            ArrayList<HashMap<String, String>> eventValues = UtilsForTest.parseMulXML(is,
                    new String[] { "event" });

            for (int i = 0; i < eventValues.size(); i++) {
                HashMap<String, String> element = eventValues.get(i);
                if (element.get("level").equals(level)) {
                    if (actualEvents.containsKey(element.get("type")) == true) {
                        actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1);
                    } else {
                        actualEvents.put(element.get("type"), 1);
                    }
                }
            }
        }
        method.releaseConnection();
    } catch (Exception ex) {
        s_logger.error(ex);
    }

    // compare actual events with expected events
    Iterator<?> iterator = expectedEvents.keySet().iterator();
    Integer expected;
    Integer actual;
    int fail = 0;
    while (iterator.hasNext()) {
        expected = null;
        actual = null;
        String type = iterator.next().toString();
        expected = expectedEvents.get(type);
        actual = actualEvents.get(type);
        if (actual == null) {
            s_logger.error("Event of type " + type + " and level " + level
                    + " is missing in the listEvents response. Expected number of these events is " + expected);
            fail++;
        } else if (expected.compareTo(actual) != 0) {
            fail++;
            s_logger.info("Amount of events of  " + type + " type and level " + level
                    + " is incorrect. Expected number of these events is " + expected + ", actual number is "
                    + actual);
        }
    }

    if (fail == 0) {
        result = true;
    }

    return result;
}

From source file:dept_integration.Dept_Integchalan.java

public static String doSend(String STATUS, String TRANS_DATE, String TRANSID, String BANK_REFNO,
        String BANK_NAME, String CIN) throws Exception {
    String SCODE = "ihSkaRaA";
    String url = "http://wsdl.jhpolice.gov.in/smsresponse.php";
    String result = null;/*from   w  ww. ja  v a 2  s .  co  m*/
    HttpClient client = null;
    PostMethod method = null;
    client = new HttpClient(new MultiThreadedHttpConnectionManager());

    method = new PostMethod(url);
    // method.addRequestHeader("Content-Type","application/xml");

    method.addParameter("STATUS", STATUS);
    // method.addParameter("signature",URLEncoder.encode(b,"UTF-8"));
    method.addParameter("TRANS_DATE", TRANS_DATE);
    method.addParameter("TRANSID", TRANSID);
    method.addParameter("BANK_REFNO", BANK_REFNO);
    method.addParameter("BANK_NAME", BANK_NAME);
    method.addParameter("CIN", CIN);
    method.addParameter("SCODE", SCODE);

    try {
        int statusCode = client.executeMethod(method);
        // System.out.println("lll"+method.getStatusLine().toString());
        if (statusCode == -1) {
            result = "N";
            System.err.println("HttpError: " + method.getStatusLine());
        } else {
            result = method.getResponseBodyAsString();
            System.out.println(result);
            //result= result.indexOf(""+mobile_no)==-1 ? "N" : "Y";
        }
    } catch (Exception e) {

        e.printStackTrace();

        System.err.println("Fatal protocol violation: " + e.getMessage());
        throw e;

    }

    finally {
        method.abort();
        method.releaseConnection();

    }

    return result;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute Get method, do not follow redirects.
 *
 * @param httpClient      Http client instance
 * @param method          Http method/* w w w  .  j  ava  2  s .com*/
 * @param followRedirects Follow redirects flag
 * @throws IOException on error
 */
public static void executeGetMethod(HttpClient httpClient, GetMethod method, boolean followRedirects)
        throws IOException {
    // do not follow redirects in expired sessions
    method.setFollowRedirects(followRedirects);
    int status = httpClient.executeMethod(method);
    if ((status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
            && acceptsNTLMOnly(method) && !hasNTLM(httpClient)) {
        resetMethod(method);
        LOGGER.debug("Received " + status + " unauthorized at " + method.getURI() + ", retrying with NTLM");
        addNTLM(httpClient);
        status = httpClient.executeMethod(method);
    }
    if (status != HttpStatus.SC_OK && (followRedirects || !isRedirect(status))) {
        LOGGER.warn("GET failed with status " + status + " at " + method.getURI());
        if (status != HttpStatus.SC_NOT_FOUND && status != HttpStatus.SC_FORBIDDEN) {
            LOGGER.warn(method.getResponseBodyAsString());
        }
        throw DavGatewayHttpClientFacade.buildHttpException(method);
    }
    // check for expired session
    if (followRedirects) {
        String queryString = method.getQueryString();
        checkExpiredSession(queryString);
    }
}

From source file:edu.stanford.epad.plugins.qifpwrapper.QIFPHandler.java

public static int invalidateRemoteEPADSessionID(String epadSessionID, String epadHost, int port) {
    String epadSessionURL = buildEPADSessionURL(epadHost, port);
    HttpClient client = new HttpClient();
    DeleteMethod method = new DeleteMethod(epadSessionURL);
    int epadStatusCode;

    method.setRequestHeader("Cookie", "JSESSIONID=" + epadSessionID);

    try {//from  www . j  a v  a2  s .com
        epadStatusCode = client.executeMethod(method);
    } catch (IOException e) {
        log.warning("Error calling EPAD session service to invalidate session ID", e);
        epadStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        method.releaseConnection();
    }

    if (epadStatusCode != HttpServletResponse.SC_OK)
        log.warning("EPAD delete session call returned status code " + epadStatusCode);

    return epadStatusCode;
}

From source file:com.cloud.test.regression.ApiCommand.java

public static boolean verifyEvents(String fileName, String level, String host, String account) {
    boolean result = false;
    HashMap<String, Integer> expectedEvents = new HashMap<String, Integer>();
    HashMap<String, Integer> actualEvents = new HashMap<String, Integer>();
    String key = "";

    File file = new File(fileName);
    if (file.exists()) {
        Properties pro = new Properties();
        try {//w  ww.  ja v  a 2s  .c om
            // get expected events
            FileInputStream in = new FileInputStream(file);
            pro.load(in);
            Enumeration<?> en = pro.propertyNames();
            while (en.hasMoreElements()) {
                key = (String) en.nextElement();
                expectedEvents.put(key, Integer.parseInt(pro.getProperty(key)));
            }

            // get actual events
            String url = host + "/?command=listEvents&account=" + account + "&level=" + level
                    + "&domainid=1&pagesize=100";
            s_logger.info("Getting events with the following url " + url);
            HttpClient client = new HttpClient();
            HttpMethod method = new GetMethod(url);
            int responseCode = client.executeMethod(method);
            if (responseCode == 200) {
                InputStream is = method.getResponseBodyAsStream();
                ArrayList<HashMap<String, String>> eventValues = UtilsForTest.parseMulXML(is,
                        new String[] { "event" });

                for (int i = 0; i < eventValues.size(); i++) {
                    HashMap<String, String> element = eventValues.get(i);
                    if (element.get("level").equals(level)) {
                        if (actualEvents.containsKey(element.get("type")) == true) {
                            actualEvents.put(element.get("type"), actualEvents.get(element.get("type")) + 1);
                        } else {
                            actualEvents.put(element.get("type"), 1);
                        }
                    }
                }
            }
            method.releaseConnection();

            // compare actual events with expected events

            // compare expected result and actual result
            Iterator<?> iterator = expectedEvents.keySet().iterator();
            Integer expected;
            Integer actual;
            int fail = 0;
            while (iterator.hasNext()) {
                expected = null;
                actual = null;
                String type = iterator.next().toString();
                expected = expectedEvents.get(type);
                actual = actualEvents.get(type);
                if (actual == null) {
                    s_logger.error("Event of type " + type + " and level " + level
                            + " is missing in the listEvents response. Expected number of these events is "
                            + expected);
                    fail++;
                } else if (expected.compareTo(actual) != 0) {
                    fail++;
                    s_logger.info("Amount of events of  " + type + " type and level " + level
                            + " is incorrect. Expected number of these events is " + expected
                            + ", actual number is " + actual);
                }
            }
            if (fail == 0) {
                result = true;
            }
        } catch (Exception ex) {
            s_logger.error(ex);
        }
    } else {
        s_logger.info("File " + fileName + " not found");
    }
    return result;
}

From source file:dk.clarin.tools.userhandle.java

public static String getUserId(HttpServletRequest request, List<FileItem> items, String userHandle) {
    /// The eSciDoc id of the user
    String userId = null;/*from w  w w .j  a v  a2s. co m*/
    // First get the user's escidoc-id and email
    org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();

    org.apache.commons.httpclient.methods.GetMethod method;
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(500000);
    logger.debug("getUserId( {} )", userHandle);
    String res = null;

    method = new org.apache.commons.httpclient.methods.GetMethod(
            ToolsProperties.coreServer + "/aa/user-account/" + userHandle);
    try {
        method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
        method.setFollowRedirects(false);
        httpClient.executeMethod(method);
        if (method.getStatusCode() != 200) { // May be 302 Found. This is the most popular redirect code, 
                                             // but also an example of industrial practice contradicting
                                             // the standard. HTTP/1.0 specification (RFC 1945) required
                                             // the client to perform a temporary redirect (the original
                                             // describing phrase was \"Moved Temporarily\"), but popular
                                             // browsers implemented 302 with the functionality of a 
                                             // 303 See Other. Therefore, HTTP/1.1 added status codes 303
                                             // and 307 to distinguish between the two behaviours.
                                             // However, the majority of Web applications and frameworks
                                             // still use the 302 status code as if it were the 303.
            logger.error(
                    "Wrong return code [" + method.getStatusCode() + "]. The user could not be identified!");
            reason = "Wrong return code. The user could not be identified!";
            userId = null;
        } else {
            res = method.getResponseBodyAsString();

            // Extract the user's id
            int startIdx = res.lastIndexOf("xlink:href");
            if (startIdx > 1)
                userId = res.substring(startIdx + 29, res.indexOf("/", startIdx + 29));
            if (userId == null || userId.length() < 3) {
                logger.error("The user could not be identified! reply: " + res);
                reason = "The user could not be identified!";
                userId = null;
            } else
                logger.debug("userId = {}", userId);
        }
    } catch (IOException e) {
        logger.error("Could not contact the eSciDoc server");
        reason = "Could not contact the eSciDoc server";
        userId = null;
    } finally {
        method.releaseConnection();
    }
    /*
    Dangerous, can be forged!
            if(userId == null)
    {
    String [] tmp = request.getParameterValues("id");
    if(tmp != null)
        userId = tmp[0];
    }
    */

    if (userId != null) {
        reason = null;
    }

    logger.debug("user ID: " + userId);

    return userId;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute method with httpClient, follow 30x redirects.
 *
 * @param httpClient Http client instance
 * @param method     Http method//from  ww  w. j a v  a2  s .  c o  m
 * @return last http method after redirects
 * @throws IOException on error
 */
public static HttpMethod executeFollowRedirects(HttpClient httpClient, HttpMethod method) throws IOException {
    HttpMethod currentMethod = method;
    try {
        DavGatewayTray.debug(new BundleMessage("LOG_EXECUTE_FOLLOW_REDIRECTS", currentMethod.getURI()));
        httpClient.executeMethod(currentMethod);
        checkNTLM(httpClient, currentMethod);

        String locationValue = getLocationValue(currentMethod);
        // check javascript redirect (multiple authentication pages)
        if (locationValue == null) {
            locationValue = getJavascriptRedirectUrl(currentMethod);
        }

        int redirectCount = 0;
        while (redirectCount++ < 10 && locationValue != null) {
            currentMethod.releaseConnection();
            currentMethod = new GetMethod(locationValue);
            currentMethod.setFollowRedirects(false);
            DavGatewayTray.debug(new BundleMessage("LOG_EXECUTE_FOLLOW_REDIRECTS_COUNT", currentMethod.getURI(),
                    redirectCount));
            httpClient.executeMethod(currentMethod);
            checkNTLM(httpClient, currentMethod);
            locationValue = getLocationValue(currentMethod);
        }
        if (locationValue != null) {
            currentMethod.releaseConnection();
            throw new HttpException("Maximum redirections reached");
        }
    } catch (IOException e) {
        currentMethod.releaseConnection();
        throw e;
    }
    // caller will need to release connection
    return currentMethod;
}

From source file:com.gnizr.core.util.GnizrDaoUtil.java

public static Integer detectMIMEType(String url) {
    try {/*ww  w.  j a v a  2 s  .  c  o  m*/
        HttpClient httpClient = new HttpClient();
        HeadMethod method = new HeadMethod(url);
        method.getParams().setIntParameter("http.socket.timeout", 5000);
        int code = httpClient.executeMethod(method);
        if (code == 200) {
            Header h = method.getResponseHeader("Content-Type");
            if (h != null) {
                HeaderElement[] headElm = h.getElements();
                if (headElm != null & headElm.length > 0) {
                    String mimeType = headElm[0].getValue();
                    if (mimeType == null) {
                        mimeType = headElm[0].getName();
                    }
                    if (mimeType != null) {
                        return getMimeTypeIdCode(mimeType);
                    }
                }
            }
        }
    } catch (Exception e) {
        // no code;
    }
    return MIMEType.UNKNOWN;
}

From source file:edu.stanford.epad.epadws.queries.XNATQueries.java

public static String getXNATSubjectFieldValue(String sessionID, String xnatSubjectID, String fieldName) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(XNATQueryUtil.buildSubjectURL(xnatSubjectID) + "?format=xml");
    int xnatStatusCode;
    //log.info("Calling XNAT Subject info:" + XNATQueryUtil.buildSubjectURL(xnatSubjectID) + "?format=xml");
    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionID);

    try {//  www .ja v a2 s .  c  om
        xnatStatusCode = client.executeMethod(method);
        String xmlResp = method.getResponseBodyAsString(10000);
        log.debug(xmlResp);
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputStream is = new StringBufferInputStream(xmlResp);
        Document doc = db.parse(is);
        doc.getDocumentElement().normalize();
        NodeList nodes = doc.getElementsByTagName("xnat:field");
        String value = "";
        String subjfieldname = "";
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            value = node.getTextContent();
            if (value != null)
                value = value.replace('\n', ' ').trim();
            NamedNodeMap attrs = node.getAttributes();
            String attrName = null;
            for (int j = 0; attrs != null && j < attrs.getLength(); j++) {
                attrName = attrs.item(j).getNodeName();
                subjfieldname = attrs.item(j).getNodeValue();
                if (fieldName.equalsIgnoreCase(subjfieldname))
                    return value;
            }
        }
        return value;
    } catch (Exception e) {
        log.warning(
                "Warning: error performing XNAT subject query " + XNATQueryUtil.buildSubjectURL(xnatSubjectID),
                e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        method.releaseConnection();
    }
    return null;
}

From source file:it.intecs.pisa.develenv.model.launch.ToolboxScriptRunLaunch.java

protected static InputStream performCheckForPushedMessage(IProject project, String messageId, long checkEach,
        IProgressMonitor monitor, ILaunch launch) {
    String pushedMessageUrl;//from  w  w w  . java  2 s  .co  m
    int loopCount = 0;
    int maxLoops = 10; //should be configurable
    int waitInterval = 60000; //should be configurable
    HttpClient client;
    GetMethod method;
    int statusCode = 404;

    try {
        pushedMessageUrl = GetPushedMessageUrl(project, messageId);
        if (pushedMessageUrl != null) {
            client = new HttpClient();

            method = new GetMethod(pushedMessageUrl);

            while (monitor.isCanceled() == false && statusCode == 404 && loopCount < maxLoops) {
                statusCode = client.executeMethod(method);
                if (statusCode == 404)
                    Thread.sleep(checkEach);

                if (monitor.isCanceled())
                    return null;
            }

            return method.getResponseBodyAsStream();
        }

        return null;
    } catch (Exception e) {
        MessageDialog.openError(null, "Retrieving pushed message",
                "An error has occurred while trying to retrieve the pushed message");
        return null;
    }
}