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.owncloud.android.lib.resources.shares.GetRemoteSharesOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;

    // Get Method        
    GetMethod get = null;//w  ww .  jav a 2  s.c  om

    // Get the response
    try {
        get = new GetMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH);
        get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        status = client.executeMethod(get);
        if (isSuccess(status)) {
            String response = get.getResponseBodyAsString();

            // Parse xml response --> obtain the response in ShareFiles ArrayList
            // convert String into InputStream
            InputStream is = new ByteArrayInputStream(response.getBytes());
            ShareXMLParser xmlParser = new ShareXMLParser();
            mShares = xmlParser.parseXMLResponse(is);
            if (mShares != null) {
                Log_OC.d(TAG, "Got " + mShares.size() + " shares");
                result = new RemoteOperationResult(ResultCode.OK);
                ArrayList<Object> sharesObjects = new ArrayList<Object>();
                for (OCShare share : mShares) {
                    sharesObjects.add(share);
                }
                result.setData(sharesObjects);
            }
        } else {
            result = new RemoteOperationResult(false, status, get.getResponseHeaders());
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while getting remote shares ", e);

    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }
    return result;
}

From source file:de.mpg.escidoc.services.tools.scripts.person_grants.Util.java

/**
 * Queries an eSciDoc instance//  w  ww .ja  v  a 2s  .  c om
 * 
 * @param url
 * @param query
 * @param adminUserName
 * @param adminPassword
 * @param frameworkUrl
 * @return
 */
public static Document queryFramework(String url, String query, String adminUserName, String adminPassword,
        String frameworkUrl) {
    try {
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactoryImpl.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        HttpClient client = new HttpClient();
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        GetMethod getMethod = new GetMethod(url + "?query="
                + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle="
                + Base64.encode(
                        getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8")));
        System.out.println("Querying <" + url + "?query="
                + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle="
                + Base64.encode(
                        getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8")));
        client.executeMethod(getMethod);
        if (getMethod.getStatusCode() == 200) {
            document = documentBuilder.parse(getMethod.getResponseBodyAsStream());
        } else {
            System.out.println("Error querying: Status " + getMethod.getStatusCode() + "\n"
                    + getMethod.getResponseBodyAsString());
        }
        return document;
    } catch (Exception e) {
        try {
            System.out.println("Error querying Framework <" + url + "?query="
                    + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle="
                    + Base64.encode(
                            getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8"))
                    + ">");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        e.printStackTrace();
    }
    return null;
}

From source file:com.epam.wilma.service.http.WilmaHttpClient.java

/**
 * Calls the given URL via HTTP GET method and returns {@code String}
 * {@code Optional} of the response.//from   w w  w. ja  v  a  2s  .  c  o  m
 *
 * @param url the given URL
 * @return an {@code Optional} instance containing the HTTP method's
 *         response; otherwise returns {@link Optional#absent}.
 */
public Optional<String> sendGetterRequest(final String url) {
    String response = null;

    GetMethod method = new GetMethod(url);

    try {
        int statusCode = httpclient.executeMethod(method);
        if (HttpStatus.SC_OK == statusCode) {
            InputStream inputResponse = method.getResponseBodyAsStream();
            response = IOUtils.toString(inputResponse, "UTF-8");
        }
    } catch (HttpException e) {
        LOG.error("Protocol exception occurred when called: " + url, e);
    } catch (IOException e) {
        LOG.error("I/O (transport) error occurred when called: " + url, e);
    } finally {
        method.releaseConnection();
    }

    return Optional.fromNullable(response);
}

From source file:com.manning.blogapps.chapter10.atomclient.AtomBlogConnection.java

/**
 * Create Atom blog client instance for specified URL and user account.
 * @param url        End-point URL of Atom service
 * @param username   Username of account 
 * @param password   Password of account
 *///  w w  w .j  a va 2  s .  c  om
public AtomBlogConnection(String url, String username, String password) throws BlogClientException {

    Document doc = null;
    try {
        URL feedURL = new URL(url);
        Credentials creds = new UsernamePasswordCredentials(username, password);
        httpClient.getState().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(null, feedURL.getHost(), creds);
        GetMethod method = new GetMethod(url);
        addAuthentication(method, username, password);
        httpClient.executeMethod(method);
        SAXBuilder builder = new SAXBuilder();
        doc = builder.build(method.getResponseBodyAsStream());
    } catch (Throwable t) {
        throw new BlogClientException("Error connecting to blog server", t);
    }

    AtomService service = AtomService.documentToService(doc);
    Iterator iter = service.getWorkspaces().iterator();
    int count = 0;
    while (iter.hasNext()) {
        AtomService.Workspace workspace = (AtomService.Workspace) iter.next();
        Blog blog = new AtomBlog(httpClient, username, password, workspace);
        blogSites.put(blog.getToken(), blog);
    }
}

From source file:com.panoramagl.downloaders.PLHTTPFileDownloader.java

/**download methods*/

@Override//from w  w  w  .  ja  va 2 s.  com
protected byte[] downloadFile() {
    this.setRunning(true);
    byte[] result = null;
    InputStream is = null;
    ByteArrayOutputStream bas = null;
    String url = this.getURL();
    PLFileDownloaderListener listener = this.getListener();
    boolean hasListener = (listener != null);
    int responseCode = -1;
    long startTime = System.currentTimeMillis();
    // HttpClient instance
    HttpClient client = new HttpClient();
    // Method instance
    HttpMethod method = new GetMethod(url);
    // Method parameters
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.USER_AGENT, "PanoramaGL Android");
    methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(this.getMaxAttempts(), false));
    try {
        // Execute the method
        responseCode = client.executeMethod(method);
        if (responseCode != HttpStatus.SC_OK)
            throw new IOException(method.getStatusText());
        // Get content length
        Header header = method.getRequestHeader("Content-Length");
        long contentLength = (header != null ? Long.parseLong(header.getValue()) : 1);
        if (this.isRunning()) {
            if (hasListener)
                listener.didBeginDownload(url, startTime);
        } else
            throw new PLRequestInvalidatedException(url);
        // Get response body as stream
        is = method.getResponseBodyAsStream();
        bas = new ByteArrayOutputStream();
        byte[] buffer = new byte[256];
        int length = 0, total = 0;
        // Read stream
        while ((length = is.read(buffer)) != -1) {
            if (this.isRunning()) {
                bas.write(buffer, 0, length);
                total += length;
                if (hasListener)
                    listener.didProgressDownload(url, (int) (((float) total / (float) contentLength) * 100.0f));
            } else
                throw new PLRequestInvalidatedException(url);
        }
        if (total == 0)
            throw new IOException("Request data has invalid size (0)");
        // Get data
        if (this.isRunning()) {
            result = bas.toByteArray();
            if (hasListener)
                listener.didEndDownload(url, result, System.currentTimeMillis() - startTime);
        } else
            throw new PLRequestInvalidatedException(url);
    } catch (Throwable e) {
        if (this.isRunning()) {
            PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            if (hasListener)
                listener.didErrorDownload(url, e.toString(), responseCode, result);
        }
    } finally {
        if (bas != null) {
            try {
                bas.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                PLLog.error("PLHTTPFileDownloader::downloadFile", e);
            }
        }
        // Release the connection
        method.releaseConnection();
    }
    this.setRunning(false);
    return result;
}

From source file:it.intecs.pisa.openCatalogue.solr.SolrHandler.java

public SaxonDocument search(HashMap<String, String> request)
        throws UnsupportedEncodingException, IOException, SaxonApiException, Exception {
    HttpClient client = new HttpClient();
    HttpMethod method;//from   www  . j  av a  2 s .com
    String urlStr = prepareUrl(request);
    Log.debug("The following search is goint to be executed:" + urlStr);
    // Create a method instance.
    method = new GetMethod(urlStr);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    // Execute the method.
    int statusCode = client.executeMethod(method);
    SaxonDocument solrResponse = new SaxonDocument(method.getResponseBodyAsString());
    //Log.debug(solrResponse.getXMLDocumentString());

    if (statusCode != HttpStatus.SC_OK) {
        Log.error("Method failed: " + method.getStatusLine());
        String errorMessage = (String) solrResponse.evaluatePath("//lst[@name='error']/str[@name='msg']/text()",
                XPathConstants.STRING);
        throw new Exception(errorMessage);
    }

    return solrResponse;
}

From source file:com.qubole.rubix.hadoop1.Hadoop1ClusterManager.java

@Override
public void initialize(Configuration conf) {
    super.initialize(conf);
    nnPort = conf.getInt(nnPortConf, nnPort);

    nodesSupplier = Suppliers.memoizeWithExpiration(new Supplier<List<String>>() {
        @Override// w w w  .j av a 2s.c o  m
        public List<String> get() {
            if (!isMaster) {
                // First time all nodes start assuming themselves as master and down the line figure out their role
                // Next time onwards, only master will be fetching the list of nodes
                return ImmutableList.of();
            }

            HttpClient httpclient = new HttpClient();
            HttpMethod method = new GetMethod(
                    "http://localhost:" + nnPort + "/dfsnodelist.jsp?whatNodes=LIVE&status=NORMAL");
            int sc;
            try {
                sc = httpclient.executeMethod(method);
            } catch (IOException e) {
                // not reachable => worker
                sc = -1;
            }

            if (sc != 200) {
                LOG.debug("Could not reach dfsnodelist.jsp, setting worker role");
                isMaster = false;
                return ImmutableList.of();
            }

            LOG.debug("Reached dfsnodelist.jsp, setting master role");
            isMaster = true;
            String html;
            try {
                byte[] buf = method.getResponseBody();
                html = new String(buf);
            } catch (IOException e) {
                throw Throwables.propagate(e);
            }

            List<String> nodes = extractNodes(html);
            return nodes;
        }
    }, 10, TimeUnit.SECONDS);
    nodesSupplier.get();
}

From source file:com.cerema.cloud2.operations.UpdateOCVersionOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    AccountManager accountMngr = AccountManager.get(mContext);
    String statUrl = accountMngr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
    statUrl += AccountUtils.STATUS_PATH;
    RemoteOperationResult result = null;
    GetMethod get = null;/*from   w ww. j  a  v a2 s  . c om*/
    try {
        get = new GetMethod(statUrl);
        int status = client.executeMethod(get);
        if (status != HttpStatus.SC_OK) {
            client.exhaustResponse(get.getResponseBodyAsStream());
            result = new RemoteOperationResult(false, status, get.getResponseHeaders());

        } else {
            String response = get.getResponseBodyAsString();
            if (response != null) {
                JSONObject json = new JSONObject(response);
                if (json != null && json.getString("version") != null) {

                    String version = json.getString("version");
                    mOwnCloudVersion = new OwnCloudVersion(version);
                    if (mOwnCloudVersion.isVersionValid()) {
                        accountMngr.setUserData(mAccount, Constants.KEY_OC_VERSION,
                                mOwnCloudVersion.getVersion());
                        Log_OC.d(TAG, "Got new OC version " + mOwnCloudVersion.toString());

                        result = new RemoteOperationResult(ResultCode.OK);

                    } else {
                        Log_OC.w(TAG,
                                "Invalid version number received from server: " + json.getString("version"));
                        result = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);
                    }
                }
            }
            if (result == null) {
                result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
            }
        }
        Log_OC.i(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": "
                + result.getLogMessage());

    } catch (JSONException e) {
        result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
        Log_OC.e(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": "
                + result.getLogMessage(), e);

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": "
                + result.getLogMessage(), e);

    } finally {
        if (get != null)
            get.releaseConnection();
    }
    return result;
}

From source file:com.google.enterprise.connector.sharepoint.spiimpl.SPDocumentTest.java

protected void setUp() throws Exception {
    super.setUp();
    SharepointClientContext spContext = TestConfiguration.initContext();
    List<SPDocument> allDocs = TestConfiguration.initState(spContext)
            .lookupList(TestConfiguration.Site1_URL, TestConfiguration.Site1_List1_GUID).getCrawlQueue();
    assertTrue(allDocs.size() > 0);/*www  .j a  v a 2  s. c o m*/
    this.doc = allDocs.get(0);
    assertNotNull(this.doc);
    this.doc.setSharepointClientContext(spContext);
    this.doc.setContentDwnldURL(doc.getUrl());

    // TODO(jlacey): Replace this use of UrlUtil, which generates a
    // warning on Java 7 when not using a bootclasspath. Also, this
    // code is either pointless or it's a smoke test that belongs in a
    // test method.
    String str = UrlUtil.encode(doc.getUrl(), "UTF-8");
    String charset = new GetMethod(str).getParams().getUriCharset();
    URI uri = new URI(doc.getUrl(), true, charset);
}

From source file:com.zimbra.cs.util.WebClientServiceUtil.java

/**
 * send service request to every ui node
 * @param serviceUrl the url that should be matched and handled by ServiceServlet in ZimbraWebClient
 * @throws ServiceException//  www . ja va  2  s .c o m
 */
public static void sendServiceRequestToEveryUiNode(String serviceUrl) throws ServiceException {
    List<Server> servers = Provisioning.getInstance().getAllServers(Provisioning.SERVICE_WEBCLIENT);
    if (servers == null || servers.isEmpty()) {
        servers.add(Provisioning.getInstance().getLocalServer());
    }
    AuthToken authToken = AuthProvider.getAdminAuthToken();
    ZimbraLog.misc.debug("got admin auth token");
    //sequentially flush each node
    HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(client);
    for (Server server : servers) {
        if (isServerAtLeast8dot5(server)) {
            HttpMethod method = null;
            try {
                method = new GetMethod(URLUtil.getServiceURL(server, serviceUrl, false));
                ZimbraLog.misc.debug("connecting to ui node %s", server.getName());
                try {
                    method.addRequestHeader(PARAM_AUTHTOKEN, authToken.getEncoded());
                } catch (AuthTokenException e) {
                    ZimbraLog.misc.warn(e);
                }
                int respCode = HttpClientUtil.executeMethod(client, method);
                if (respCode != 200) {
                    ZimbraLog.misc.warn("service failed, return code: %d", respCode);
                }
            } catch (Exception e) {
                ZimbraLog.misc.warn("service failed for node %s", server.getName(), e);
            } finally {
                if (method != null) {
                    method.releaseConnection();
                }
            }
        }
    }
    if (authToken != null && authToken.isRegistered()) {
        try {
            authToken.deRegister();
            ZimbraLog.misc.debug("de-registered auth token, isRegistered?%s", authToken.isRegistered());
        } catch (AuthTokenException e) {
            ZimbraLog.misc.warn("failed to de-register auth token", e);
        }
    }
}