Example usage for org.apache.commons.httpclient.methods GetMethod GetMethod

List of usage examples for org.apache.commons.httpclient.methods GetMethod GetMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods GetMethod GetMethod.

Prototype

public GetMethod(String uri) 

Source Link

Usage

From source file:com.cloud.maint.UpgradeManagerImpl.java

public String deployNewAgent(String url) {
    s_logger.info("Updating agent with binary from " + url);

    final HttpClient client = new HttpClient(s_httpClientManager);
    final GetMethod method = new GetMethod(url);
    int response;
    File file = null;// ww  w  .ja  v a  2  s.  c  o m
    try {
        response = client.executeMethod(method);
        if (response != HttpURLConnection.HTTP_OK) {
            s_logger.warn("Retrieving the agent gives response code: " + response);
            return "Retrieving the file from " + url + " got response code: " + response;
        }

        final InputStream is = method.getResponseBodyAsStream();
        file = File.createTempFile("agent-", "-" + Long.toString(new Date().getTime()));
        file.deleteOnExit();

        s_logger.debug("Retrieving new agent into " + file.getAbsolutePath());

        final FileOutputStream fos = new FileOutputStream(file);

        final ByteBuffer buffer = ByteBuffer.allocate(2048);
        final ReadableByteChannel in = Channels.newChannel(is);
        final WritableByteChannel out = fos.getChannel();

        while (in.read(buffer) != -1) {
            buffer.flip();
            out.write(buffer);
            buffer.clear();
        }

        in.close();
        out.close();

        s_logger.debug("New Agent zip file is now retrieved");
    } catch (final HttpException e) {
        return "Unable to retrieve the file from " + url;
    } catch (final IOException e) {
        return "Unable to retrieve the file from " + url;
    } finally {
        method.releaseConnection();
    }

    file.delete();

    return "File will be deployed.";
}

From source file:io.fabric8.quickstarts.fabric.rest.secure.CrmSecureTest.java

/**
 * HTTP GET http://localhost:8181/cxf/crm/customerservice/customers/123
 * returns the XML document representing customer 123
 * <p/>// w  w  w  .j  a v a 2 s  . c o  m
 * On the server side, it matches the CustomerService's getCustomer() method
 *
 * @throws Exception
 */
@Test
public void getCustomerTest() throws Exception {
    String res = "";

    LOG.info("============================================");
    LOG.info("Sent HTTP GET request to query customer info");

    GetMethod get = new GetMethod(CUSTOMER_TEST_URL);
    get.getHostAuthState().setAuthScheme(scheme);
    try {
        httpClient.executeMethod(get);
        res = get.getResponseBodyAsString();
        LOG.info(res);
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'rest' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'rest' quick start root");
        Assert.fail("Connection error");
    } finally {
        get.releaseConnection();
    }
    Assert.assertTrue(res.contains("123"));
}

From source file:att.jaxrs.client.Tag.java

public static Tag[] getALLTags() {
    GetMethod get = new GetMethod(Constants.SELECT_ALL_TAG_OPERATION);
    TagCollection tag = new TagCollection();

    HttpClient httpClient = new HttpClient();
    try {//from w  w w. j av  a2 s  .  c  om
        int result = httpClient.executeMethod(get);
        System.out.println(Constants.RESPONSE_STATUS_CODE + result);
        tag = Marshal.unmarshal(TagCollection.class, get.getResponseBodyAsStream());

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        get.releaseConnection();

    }
    if (null != tag.getTag() && tag.getTag().length > 0) {
        return tag.getTag();
    } else {
        System.out.println("unmarshalling returned empty collection");
    }
    return null;

}

From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java

public static InputStream getURLBody(final String url, StringBuffer charset,
        Map<String, String> additionalHeaders) throws IOException {
    HttpClient client = getClient();//  w ww  .  j a v  a 2 s.c o m
    System.err.println("Connecting to: " + url);
    final GetMethod get = new GetMethod(url);

    addHeaders(additionalHeaders, get);

    try {
        client.executeMethod(get);
        charset.append(get.getResponseCharSet());

        final InputStream in = get.getResponseBodyAsStream();
        return new InputStream() {

            @Override
            public int read() throws IOException {
                return in.read();
            }

            @Override
            public void close() {
                get.releaseConnection();
            }

        };
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:fr.jayasoft.ivy.url.HttpClientDownloader.java

private GetMethod doGet(URL url) throws IOException, HttpException {
    HttpClient client = new HttpClient();

    if (useAuthentication()) {
        client.getState().setCredentials(_realm, _host, new UsernamePasswordCredentials(_userName, _passwd));
    }// w  ww .  j a  v a 2s  . c  om

    GetMethod get = new GetMethod(url.toExternalForm());
    get.setDoAuthentication(useAuthentication());
    client.executeMethod(get);
    return get;
}

From source file:eu.impact_project.iif.t2.client.WorkflowUploader.java

/**
 * Gets the groups and workflow infos from myExperiment
 *//*from   w  w  w.  ja v a  2s.c om*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // to find out own userID
    String urlStringWhoami = "http://www.myexperiment.org/whoami.xml";

    if (request.getParameter("myexp_user") != null && request.getParameter("myexp_password") != null) {

        HttpSession session = request.getSession(true);

        String user = request.getParameter("myexp_user");
        String password = request.getParameter("myexp_password");

        // WorkflowParser also needs the credentials
        session.setAttribute("user", user);
        session.setAttribute("password", password);

        // session.setAttribute("selectedGroupName", null);

        // the client will be used to query myexperiment's REST api
        HttpClient client = Helper.createAuthenticatingClient("www.myexperiment.org", user, password);

        // GET method for retrieving the xml with the userID
        GetMethod get = new GetMethod(urlStringWhoami);
        // api needs basic authentication
        get.setDoAuthentication(true);

        try {
            int status = client.executeMethod(get);

            if (status == 200) {
                session.setAttribute("logged_in", "true");
                request.setAttribute("login_error", null);

                InputStream xmlResponse = get.getResponseBodyAsStream();

                // get the user uri which contains the userID,
                // userID does not need to be extracted,
                // the uri can be used directly to query the api for infos
                // about the user
                Attribute attr = (Attribute) Helper.applyXPathSingleNode(xmlResponse, "//user/@uri");
                String userUri = attr.getValue();

                // GET method to retrieve all groups of the user
                get = new GetMethod(userUri + "&elements=groups");
                client.executeMethod(get);
                xmlResponse = get.getResponseBodyAsStream();
                // get all groups from received xml
                List<Element> groupElements = Helper.applyXPathSeveralNodes(xmlResponse, "//group");

                // will be used in the jsp to construct selection lists
                Map<String, List<WorkflowInfo>> allWfInfos = new LinkedHashMap<String, List<WorkflowInfo>>();

                // if the user is in the impact group, then it will be the
                // default selection in the jsp, or else it will be the
                // first group
                boolean isFirstGroup = true;

                for (Element group : groupElements) {
                    String groupUri = group.getAttributeValue("uri");
                    String groupName = group.getTextTrim();

                    // set the default selection
                    if (isFirstGroup || groupName.startsWith("IMPACT")) {
                        session.setAttribute("selectedGroupName0", groupName);
                        session.setAttribute("selectedGroupName1", groupName);
                        isFirstGroup = false;
                    }

                    // GET method for retrieving all workflow infos of a
                    // group
                    get = new GetMethod(groupUri + "&elements=shared-items");
                    client.executeMethod(get);
                    xmlResponse = get.getResponseBodyAsStream();

                    // extract the necessary information from received xml
                    List<WorkflowInfo> wfInfos = createWfInfos(xmlResponse);

                    // map for jsp
                    allWfInfos.put(groupName, wfInfos);

                }

                // GET method for retrieving all workflow infos of the user
                get = new GetMethod(userUri + "&elements=workflows");
                client.executeMethod(get);
                xmlResponse = get.getResponseBodyAsStream();

                // extract the necessary information from received xml
                List<WorkflowInfo> wfInfosUser = createWfInfos(xmlResponse);

                if (wfInfosUser != null && wfInfosUser.size() > 0) {
                    // the select will show this under the other groups
                    allWfInfos.put("Own workflows", wfInfosUser);
                }
                session.setAttribute("allWfInfos", allWfInfos);
                session.setAttribute("currentTab0", "remote");
                session.setAttribute("currentTab1", "remote");
            } else {
                session.setAttribute("logged_in", "false");
                request.setAttribute("login_error", "Login error");
                session.setAttribute("currentTab0", "local");
                session.setAttribute("currentTab1", "local");
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JDOMException e) {
            e.printStackTrace();
        } finally {
            // release any connection resources used by the method
            get.releaseConnection();
        }
    }
    RequestDispatcher rd = getServletContext().getRequestDispatcher(redirect);
    rd.forward(request, response);
}

From source file:net.jadler.junit.rule.JadlerRuleIntegrationTest.java

private GetMethod createAndExecute() throws IOException {
    final GetMethod req = new GetMethod("http://localhost:" + port());
    this.client.executeMethod(req);

    return req;//from   w w w.  j a  v  a2s. c  om
}

From source file:com.ms.commons.utilities.HttpClientUtils.java

/**
 * byte[]?? uri ???getResponseBodyAsStream
 * //from   www .  j  a v a  2s  . co  m
 * @param method
 * @return
 */
public static byte[] getResponseBodyAsByte(String uri) {
    return getResponseBodyAsByte(new GetMethod(uri));
}

From source file:com.shelrick.openamplify.client.OpenAmplifyClientImpl.java

@Override
public OpenAmplifyResponse analyzeUrl(String url, Analysis analysis, Integer maxTopicResults)
        throws OpenAmplifyClientException {
    List<NameValuePair> params = getBaseParams();
    params.add(new NameValuePair("sourceurl", url));
    params.add(new NameValuePair("analysis", analysis.type()));
    params.add(new NameValuePair("maxtopicresult", maxTopicResults.toString()));

    GetMethod getMethod = new GetMethod(apiUrl);
    getMethod.setQueryString(params.toArray(new NameValuePair[1]));

    String responseText = doRequest(getMethod);
    return parseResponse(responseText, analysis);
}

From source file:eu.learnpad.core.impl.sim.XwikiBridgeInterfaceRestResource.java

@Override
public Collection<String> getProcessDefinitions() throws LpRestException {
    HttpClient httpClient = this.getAnonymousClient();
    String uri = String.format("%s/learnpad/sim/bridge/processes", this.restPrefix);

    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader("Content-Type", "application/json");

    try {/*from   w  ww .j  av  a  2s . c om*/

        httpClient.executeMethod(getMethod);

        // Not fully tested, but is looks working for our purposes -- Gulyx
        return this.objectReaderCollection.readValue(getMethod.getResponseBodyAsStream());
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}