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:edu.stanford.epad.epadws.xnat.XNATSessionOperations.java

public static boolean hasValidXNATSessionID(String jsessionID) {
    String xnatSessionURL = XNATUtil.buildXNATSessionURL();
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(xnatSessionURL);
    int xnatStatusCode;

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

    try {//from ww w .j  a  va  2 s . c o m
        xnatStatusCode = client.executeMethod(method);
    } catch (IOException e) {
        log.warning("Error calling XNAT", e);
        xnatStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    } finally {
        method.releaseConnection();
    }
    return (xnatStatusCode == HttpServletResponse.SC_OK);
}

From source file:edu.unc.lib.dl.ui.service.XMLRetrievalService.java

public static Document getXMLDocument(String url) throws HttpException, IOException, JDOMException {
    SAXBuilder builder = new SAXBuilder();

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    method.getParams().setParameter("http.socket.timeout", new Integer(2000));
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.getParams().setParameter("http.useragent", "");

    InputStream responseStream = null;
    Document document = null;//from  w ww .j  ava2 s.c o m

    try {
        client.executeMethod(method);
        responseStream = method.getResponseBodyAsStream();
        document = builder.build(responseStream);
    } finally {
        if (responseStream != null)
            responseStream.close();
        method.releaseConnection();
    }

    return document;
}

From source file:com.openkm.openmeetings.service.RestService.java

/**
 * call/* w  w w . jav  a  2s  .  co  m*/
 * 
 * @param request
 * @param param
 * @return
 * @throws Exception
 */
public static List<Element> callList(String request, Object param) throws Exception {
    HttpClient client = new HttpClient();
    GetMethod method = null;
    try {
        method = new GetMethod(getEncodetURI(request).toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    int statusCode = 0;
    try {
        statusCode = client.executeMethod(method);
    } catch (HttpException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    } catch (IOException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    }

    switch (statusCode) {
    case 200: // OK
        break;
    case 400:
        throw new Exception(
                "Bad request. The parameters passed to the service did not match as expected. The Message should tell you what was missing or incorrect.");
    case 403:
        throw new Exception(
                "Forbidden. You do not have permission to access this resource, or are over your rate limit.");
    case 503:
        throw new Exception(
                "Service unavailable. An internal problem prevented us from returning data to you.");
    default:
        throw new Exception("Your call to OpenMeetings! Web Services returned an unexpected  HTTP status of: "
                + statusCode);
    }

    InputStream rstream = null;
    try {
        rstream = method.getResponseBodyAsStream();
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("No Response Body");
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    SAXReader reader = new SAXReader();
    Document document = null;
    String line;
    try {
        while ((line = br.readLine()) != null) {
            document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new Exception("UnsupportedEncodingException by SAXReader");
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("IOException by SAXReader in REST Service");
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new Exception("DocumentException by SAXReader in REST Service");
    } finally {
        br.close();
    }

    Element root = document.getRootElement();
    List<Element> elementList = new ArrayList<Element>();

    for (@SuppressWarnings("unchecked")
    Iterator<Element> it = root.elementIterator(); it.hasNext();) {
        Element item = it.next();
        if (item.getNamespacePrefix() == "soapenv") {
            throw new Exception(item.getData().toString());
        }
        elementList.add(item);
    }

    return elementList;
}

From source file:com.openkm.openmeetings.service.RestService.java

/**
 * call//from  w w w.j av a2  s . c  o m
 * 
 * @param request
 * @param param
 * @return
 * @throws Exception
 */
public static Map<String, Element> callMap(String request, Object param) throws Exception {
    HttpClient client = new HttpClient();
    GetMethod method = null;
    try {
        method = new GetMethod(getEncodetURI(request).toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    int statusCode = 0;
    try {
        statusCode = client.executeMethod(method);
    } catch (HttpException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    } catch (IOException e) {
        throw new Exception(
                "Connection to OpenMeetings refused. Please check your OpenMeetings configuration.");
    }

    switch (statusCode) {
    case 200: // OK
        break;
    case 400:
        throw new Exception(
                "Bad request. The parameters passed to the service did not match as expected. The Message should tell you what was missing or incorrect.");
    case 403:
        throw new Exception(
                "Forbidden. You do not have permission to access this resource, or are over your rate limit.");
    case 503:
        throw new Exception(
                "Service unavailable. An internal problem prevented us from returning data to you.");
    default:
        throw new Exception("Your call to OpenMeetings! Web Services returned an unexpected  HTTP status of: "
                + statusCode);
    }

    InputStream rstream = null;
    try {
        rstream = method.getResponseBodyAsStream();
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("No Response Body");
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
    SAXReader reader = new SAXReader();
    Document document = null;
    String line;
    try {
        while ((line = br.readLine()) != null) {
            document = reader.read(new ByteArrayInputStream(line.getBytes("UTF-8")));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new Exception("UnsupportedEncodingException by SAXReader");
    } catch (IOException e) {
        e.printStackTrace();
        throw new Exception("IOException by SAXReader in REST Service");
    } catch (DocumentException e) {
        e.printStackTrace();
        throw new Exception("DocumentException by SAXReader in REST Service");
    } finally {
        br.close();
    }

    Element root = document.getRootElement();
    Map<String, Element> elementMap = new LinkedHashMap<String, Element>();

    for (@SuppressWarnings("unchecked")
    Iterator<Element> it = root.elementIterator(); it.hasNext();) {
        Element item = it.next();
        if (item.getNamespacePrefix() == "soapenv") {
            throw new Exception(item.getData().toString());
        }
        String nodeVal = item.getName();
        elementMap.put(nodeVal, item);
    }

    return elementMap;
}

From source file:com.intellij.openapi.paths.WebReferencesAnnotatorBase.java

private static MyFetchResult doCheckUrl(String url) {
    final HttpClient client = new HttpClient();
    client.setTimeout(3000);// w  ww .ja v  a 2 s  .c o  m
    client.setConnectionTimeout(3000);
    // see http://hc.apache.org/httpclient-3.x/cookies.html
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    try {
        final GetMethod method = new GetMethod(url);
        final int code = client.executeMethod(method);

        return code == HttpStatus.SC_OK || code == HttpStatus.SC_REQUEST_TIMEOUT ? MyFetchResult.OK
                : MyFetchResult.NONEXISTENCE;
    } catch (UnknownHostException e) {
        LOG.info(e);
        return MyFetchResult.UNKNOWN_HOST;
    } catch (IOException e) {
        LOG.info(e);
        return MyFetchResult.OK;
    } catch (IllegalArgumentException e) {
        LOG.debug(e);
        return MyFetchResult.OK;
    }
}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

protected static boolean executeMethod(HttpClient client, HttpMethod method, StringBuffer response) {
    boolean success = true;
    try {/*w w w.  j av a2  s . com*/
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        if (response != null)
            response.append(new String(responseBody));
        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

    } catch (HttpException e) {
        //  System.err.println("Fatal protocol violation: " + e.getMessage());
        // e.printStackTrace();
        success = false;
    } catch (IOException e) {
        //  System.err.println("Fatal transport error: " + e.getMessage());
        //  e.printStackTrace();
        success = false;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return success;
}

From source file:de.mpg.imeji.presentation.util.LoginHelper.java

/**
 * Get handle of System administrator of eSciDoc instance.
 * /*from   ww w.j  a va 2 s  . c om*/
 * @return
 */
//    public static String loginSystemAdmin()
//    {
//        String handle = null;
//        try
//        {
//            handle = login(PropertyReader.getProperty("framework.admin.username"),
//                    PropertyReader.getProperty("framework.admin.password"));
//        }
//        catch (Exception e)
//        {
//            sessionBean = (SessionBean)BeanHelper.getSessionBean(SessionBean.class);
//            BeanHelper
//                    .info(sessionBean.getLabel("error") + ", wrong administrator user. Check config file or FW: " + e);
//            logger.error("Error escidoc admin login", e);
//        }
//        return handle;
//    }

public static String login(String userName, String password) throws Exception {
    String frameworkUrl = PropertyReader.getProperty("escidoc.framework_access.framework.url");
    StringTokenizer tokens = new StringTokenizer(frameworkUrl, "//");
    tokens.nextToken();
    StringTokenizer hostPort = new StringTokenizer(tokens.nextToken(), ":");
    String host = hostPort.nextToken();
    int port = 80;
    if (hostPort.hasMoreTokens()) {
        port = Integer.parseInt(hostPort.nextToken());
    }
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().closeIdleConnections(1000);
    client.getHostConfiguration().setHost(host, port, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    PostMethod login = new PostMethod(frameworkUrl + "/aa/j_spring_security_check");
    login.addParameter("j_username", userName);
    login.addParameter("j_password", password);
    try {
        client.executeMethod(login);
    } catch (Exception e) {
        throw new RuntimeException("Error login in " + frameworkUrl + "  status: " + login.getStatusCode()
                + " - " + login.getStatusText());
    }
    login.releaseConnection();
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] logoncookies = cookiespec.match(host, port, "/", false, client.getState().getCookies());
    Cookie sessionCookie = logoncookies[0];
    PostMethod postMethod = new PostMethod("/aa/login");
    postMethod.addParameter("target", frameworkUrl);
    client.getState().addCookie(sessionCookie);
    client.executeMethod(postMethod);
    if (HttpServletResponse.SC_SEE_OTHER != postMethod.getStatusCode()) {
        throw new HttpException("Wrong status code: " + postMethod.getStatusCode());
    }
    String userHandle = null;
    Header headers[] = postMethod.getResponseHeaders();
    for (int i = 0; i < headers.length; ++i) {
        if ("Location".equals(headers[i].getName())) {
            String location = headers[i].getValue();
            int index = location.indexOf('=');
            userHandle = new String(Base64.decode(location.substring(index + 1, location.length())));
        }
    }
    if (userHandle == null) {
        throw new ServiceException("User not logged in.");
    }
    return userHandle;
}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

private static byte[] executePost(PostMethod xmlPost) {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    int status = -1;
    try {/*from   w w  w.  ja va2  s .  c  o  m*/
        status = client.executeMethod(xmlPost);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    byte[] bytes = null;
    if (status == HttpStatus.SC_OK) {
        try {
            bytes = xmlPost.getResponseBody();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    } else {
        try {
            throw new RuntimeException("bad status is: " + status);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        return null;
    }
    return bytes;
}

From source file:com.mindquarry.desktop.util.HttpUtilities.java

public static String putAsXML(String login, String pwd, String address, byte[] content)
        throws NotAuthorizedException {
    try {/*from   w  w w  .  ja  va 2s  . c o m*/
        HttpClient client = createHttpClient(login, pwd, address);
        PutMethod put = new PutMethod(address);
        put.setDoAuthentication(true);
        put.addRequestHeader("accept", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$
        put.setRequestEntity(new ByteArrayRequestEntity(content, "text/xml; charset=utf-8"));

        log.info("Executing HTTP PUT on " + address); //$NON-NLS-1$
        client.executeMethod(put);
        log.info("Finished HTTP PUT with status code: "//$NON-NLS-1$
                + put.getStatusCode());

        String id = null;
        if (put.getStatusCode() == 401) {
            throw new NotAuthorizedException(AUTH_REFUSED, address, login, pwd);
        } else if (put.getStatusCode() == 302) {
            Header locationHeader = put.getResponseHeader("location");
            if (locationHeader != null) {
                // we received a redirect to the URL of the putted document,
                // so
                // everything seems right and we just use the new ID:
                id = locationHeader.getValue();
            } else {
                throw new RuntimeException(CONNECTION_ERROR + put.getStatusCode());
            }
        } else {
            throw new RuntimeException(CONNECTION_ERROR + put.getStatusCode());
        }
        put.releaseConnection();
        return id;
    } catch (NotAuthorizedException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:com.pari.nm.modules.imgmgmt.ImagePropertyCCOHelper.java

private static void populateImagePropertiesFromCCOInternal(SoftwareImage image, String imageName, String url,
        boolean populateVersion, boolean populatePforms) throws PariException {
    HttpClient httpClient = new HttpClient();
    GetMethod method = new GetMethod(url);
    method.setFollowRedirects(true);/*from   w  ww  .  j  a  v  a2 s  .  co m*/
    try {
        httpClient.executeMethod(method);

        int statuscode = method.getStatusCode();
        if (statuscode != HttpStatus.SC_OK) {
            throw new PariException(-1, "Unable to connect to cisco.com to get image properites for image: "
                    + imageName + " Status: " + method.getStatusText());
        }
        populateImagePropertiesFromHTTPOutput(method.getResponseBodyAsStream(), image, imageName,
                populateVersion, populatePforms);
    } catch (PariException pex) {
        logger.error("Pari Exception while getting image properties for image: " + imageName, pex);
        throw pex;
    } catch (Exception ex) {
        logger.error("Exception while getting image properties for image: " + imageName, ex);
        throw new PariException(-1,
                "Error while getting image properties from www.cisco.com for image: " + imageName);
    }
}