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.linkage.utils.wsdl.support.UrlWsdlLoader.java

/**
 * function   building XmlObject/*from  w w w. j  a v a2  s .  c om*/
 */
public XmlObject load(String url, XmlOptions option) throws XmlException, IOException, Exception {
    XmlObject object = null;
    if (!PathUtils.isHttpPath(url)) {
        try {
            File file = new File(url.replace('/', File.separatorChar));
            if (file.exists())
                url = file.toURI().toURL().toString();
        } catch (Exception e) {
        }
    }

    if (wsdlcache.containsKey(url)) {
        return wsdlcache.get(url);
    }

    if (url.startsWith("file:")) {
        object = load(handleFile(url), option);
        wsdlcache.put(url, object);
        return object;
    } else if (url.startsWith("http:")) {
        log.debug("Getting wsdl component from [" + url + "]");
        //
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        getMethod = new GetMethod(url);
        client.executeMethod(getMethod);
        byte[] content = getMethod.getResponseBody();
        getMethod.releaseConnection();
        object = load(new ByteArrayInputStream(content), option);
        wsdlcache.put(url, object);
        return object;
    } else {
        return object;
    }
}

From source file:com.zimbra.cs.index.elasticsearch.ElasticSearchConnector.java

public int executeMethod(HttpMethod method) throws IndexStoreException, IOException {
    String reqBody = "";
    if (ZimbraLog.elasticsearch.isTraceEnabled() && method instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod eem = (EntityEnclosingMethod) method;
        RequestEntity re = eem.getRequestEntity();
        if (re instanceof StringRequestEntity) {
            StringRequestEntity sre = (StringRequestEntity) re;
            reqBody = Strings.nullToEmpty(sre.getContent());
            if (reqBody.length() > 0) {
                reqBody = String.format("\nREQUEST BODY=%s", reqBody);
            }/*from   w ww.  ja v a 2  s. c  o m*/
        }
    }
    try {
        HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
        statusCode = client.executeMethod(method);
    } catch (ConnectException ce) {
        throw new ZimbraElasticSearchDownException(ce);
    } catch (NoHttpResponseException nhre) {
        // managed to connect to the ElasticSearch service but it either crashed or timed out before
        // we got sent back the response.
        // Could be a temporary problem or a problem with this particular request.
        // In the longer term we need to track failures related to particular items at a higher level and discard
        // them after retrying a number of times.
        throw new ZimbraElasticSearchNoResponseException(nhre);
    }
    body = method.getResponseBodyAsString();
    ZimbraLog.elasticsearch.trace("ElasticSearch request:%s %s - statusCode=%d%s\nRESPONSE BODY=%s",
            method.getName(), method.getURI(), statusCode, reqBody, body);
    return statusCode;
}

From source file:datasoul.util.OnlineUpdateCheck.java

@Override
public void run() {

    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(ONLINE_BASE_URL + "latest-version");
    try {/* ww  w .  j a  v a 2  s.com*/
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            return;
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        String resp = new String(responseBody);

        // Expected format is: <NUMBER>;<NEW VERSION>;<URL>
        String toks[] = resp.split(";");

        if (toks.length != 3) {
            return;
        }

        int latestversion = Integer.parseInt(toks[0]);

        if (latestversion > VERSION) {
            String msg = java.util.ResourceBundle.getBundle("datasoul/internationalize")
                    .getString("NEW DATASOUL VERSION") + " " + toks[1] + " "
                    + java.util.ResourceBundle.getBundle("datasoul/internationalize")
                            .getString("IS AVAILABLE AT")
                    + " " + toks[2];

            ObjectManager.getInstance().getDatasoulMainForm().setInfoText(msg);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

}

From source file:eu.seaclouds.platform.planner.optimizerTest.discovererOutput.DiscovererOutputTest.java

private void executeAndCheck(HttpClient client, PostMethod method) {
    InputStream in = null;/*from   w ww .  j a va  2s.  c  om*/
    int numLines = 0;
    String outputLine;
    String completeOutput = "";
    try {
        int statusCode = client.executeMethod(method);

        if (statusCode != -1) {
            in = method.getResponseBodyAsStream();
        }
        Assert.assertNotNull(in);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        while ((outputLine = br.readLine()) != null) {
            completeOutput += NL + outputLine;
            log.info(outputLine);
            numLines++;

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    Assert.assertNotNull(completeOutput);

}

From source file:com.predic8.membrane.core.interceptor.rest.REST2SOAPInterceptorIntegrationTest.java

@Test
public void testRest() throws Exception {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    GetMethod get = new GetMethod("http://localhost:3004/bank/37050198");

    int status = client.executeMethod(get);
    //System.out.println(get.getResponseBodyAsString());

    assertEquals(200, status);//from  w  w  w .  jav  a  2s  .c  o m
}

From source file:de.mpg.escidoc.pubman.util.CommonUtils.java

public static String getConeLanguageName(String code, String locale) throws Exception {
    if (code != null && !"".equals(code.trim())) {
        //if (!(locale.equals("en") || locale.equals("de") || locale.equals("ja") || locale.equals("es")))
        if (!(locale.equals("en") || locale.equals("de") || locale.equals("ja"))) {
            locale = "en";
        }/*ww w  .  j a  v a  2 s  . co  m*/
        HttpClient client = new HttpClient();

        // check if there was a problem splitting the cone-autosuggest in javascript
        if (code.contains(" ")) {
            code = code.trim().split(" ")[0];
        }

        GetMethod getMethod = new GetMethod(PropertyReader.getProperty("escidoc.cone.service.url")
                + "iso639-3/resource/" + URLEncoder.encode(code, "UTF-8") + "?format=json&lang=" + locale);
        client.executeMethod(getMethod);
        String response = getMethod.getResponseBodyAsString();
        Pattern pattern = Pattern.compile("\"http_purl_org_dc_elements_1_1_title\" : \\[?\\s*\"(.+)\"");
        Matcher matcher = pattern.matcher(response);
        if (matcher.find()) {
            return matcher.group(1);
        } else if ("en".equals(locale)) {
            return null;
        } else {
            return getConeLanguageName(code, "en");
        }
    } else {
        return null;
    }
}

From source file:edu.scripps.fl.pubchem.EUtilsFactory.java

public Callable<InputStream> getInputStream(final String url, final Object... params) throws IOException {
    return new Callable<InputStream>() {
        public InputStream call() throws Exception {
            StringBuffer sb = new StringBuffer();
            sb.append(url).append("?");
            PostMethod post = new PostMethod(url);
            List<NameValuePair> data = new ArrayList<NameValuePair>();
            data.add(new NameValuePair("tool", EUtilsFactory.this.tool));
            data.add(new NameValuePair("email", EUtilsFactory.this.email));
            for (int ii = 0; ii < params.length; ii += 2) {
                String name = params[ii].toString();
                String value = "";
                if ((ii + 1) < params.length)
                    value = params[ii + 1].toString();
                data.add(new NameValuePair(name, value));
                sb.append(name).append("=").append(value).append("&");
            }//from   ww w .  ja va  2s  .  co m
            post.setRequestBody(data.toArray(new NameValuePair[0]));
            HttpClient httpclient = new HttpClient();
            int result = httpclient.executeMethod(post);
            //            log.debug("Fetching from: " + url + StringUtils.join(params, " "));
            log.debug("Fetching from: " + sb);
            InputStream in = post.getResponseBodyAsStream();
            return in;
        }
    };
}

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

private static EPADSessionResponse getEPADSessionID(String username, String password, String epadHost,
        int port) {
    String epadSessionURL = buildEPADSessionURL(epadHost, port);
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(epadSessionURL);
    String authString = buildAuthorizationString(username, password);
    EPADSessionResponse epadSessionResponse;
    int epadStatusCode;

    try {/*  ww  w.  jav a 2 s.  c  o  m*/
        log.info("Invoking EPAD session service for user " + username + " at " + epadSessionURL);
        method.setRequestHeader("Authorization", "Basic " + authString);
        epadStatusCode = client.executeMethod(method);
        log.info("Successfully invoked EPAD session service for user " + username + "; status code = "
                + epadStatusCode);
    } catch (IOException e) {
        log.warning("Error calling EPAD session service for user " + username, e);
        epadStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    try {
        if (epadStatusCode == HttpServletResponse.SC_OK || epadStatusCode == HttpServletResponse.SC_FOUND) {
            try {
                StringBuilder sb = new StringBuilder();
                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(method.getResponseBodyAsStream());
                    int read = 0;
                    char[] chars = new char[128];
                    while ((read = isr.read(chars)) > 0) {
                        sb.append(chars, 0, read);
                    }
                } finally {
                    IOUtils.closeQuietly(isr);
                }
                String jsessionID = sb.toString();
                epadSessionResponse = new EPADSessionResponse(HttpServletResponse.SC_OK, jsessionID, "");
                log.debug("Session ID " + jsessionID + " generated for user " + username); // TODO temp
            } catch (IOException e) {
                log.warning(LOGIN_EXCEPTION_MESSAGE, e);
                epadSessionResponse = new EPADSessionResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        null, LOGIN_EXCEPTION_MESSAGE + ": " + e.getMessage());
            }
        } else if (epadStatusCode == HttpServletResponse.SC_UNAUTHORIZED) {
            log.warning(EPAD_UNAUTHORIZED_MESSAGE);
            epadSessionResponse = new EPADSessionResponse(epadStatusCode, null, EPAD_UNAUTHORIZED_MESSAGE);
        } else {
            log.warning(EPAD_LOGIN_ERROR_MESSAGE + "; EPAD status code = " + epadStatusCode);
            epadSessionResponse = new EPADSessionResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null,
                    EPAD_LOGIN_ERROR_MESSAGE + "; EPAD status code = " + epadStatusCode);
        }
    } finally {
        method.releaseConnection();
    }
    return epadSessionResponse;
}

From source file:com.predic8.membrane.core.interceptor.rest.RESTBLZServiceIntegrationTest.java

@Test
public void testRest() throws Exception {
    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    GetMethod get = new GetMethod("http://localhost:3005/bank/37050198");

    int status = client.executeMethod(get);
    System.out.println(get.getResponseBodyAsString());

    assertEquals(200, status);/*w ww  .j  a v a  2 s.  com*/
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

/** pushes the given xml to the user's CSE configuration 
 * @throws IOException /*  ww w .j a  v a 2  s.c  om*/
 * @throws HttpException */
public static boolean pushAnnotations(String authtoken, String xml) throws HttpException, IOException {
    // see http://code.google.com/apis/customsearch/docs/api.html#create_annos

    HttpClient client = new HttpClient();
    PostMethod annotation_post = new PostMethod("http://www.google.com/coop/api/default/annotations/");

    log.debug("uploading annotations:\n" + xml);
    annotation_post.addRequestHeader("Content-type", "text/xml");
    annotation_post.addRequestHeader("Authorization", "GoogleLogin auth=" + authtoken);
    StringRequestEntity rq_en = new StringRequestEntity(xml, "text/xml", "UTF-8");
    annotation_post.setRequestEntity(rq_en);

    int astatusCode = client.executeMethod(annotation_post);
    if (astatusCode == HttpStatus.SC_OK)
        return true;
    else {
        String responseBody = IOUtils.toString(annotation_post.getResponseBodyAsStream(), "UTF-8");
        log.warn("Annotation update failed: " + responseBody);
        return false;
    }
}