Example usage for org.apache.commons.httpclient HttpStatus SC_OK

List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_OK.

Prototype

int SC_OK

To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.

Click Source Link

Document

<tt>200 OK</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:com.buzzcoders.yasw.widgets.map.support.GMapUtils.java

/**
 * Returns the coordinates of the specified address.
 * /*from   w w  w  .  j  a  v a 2  s .c om*/
 * @param addressText the address to look
 * @return the latitude and longitude information
 */
public static LatLng getAddressCoordinates(String addressText) {
    LatLng coordinates = null;
    GetMethod locateAddressGET = null;
    HttpClient client = null;
    try {
        String addressUrlEncoded = URLEncoder.encode(addressText, "UTF-8");
        String locationFindURL = "http://maps.google.com/maps/api/geocode/json?sensor=false&address="
                + addressUrlEncoded;
        client = new HttpClient();
        locateAddressGET = new GetMethod(locationFindURL);
        int httpRetCode = client.executeMethod(locateAddressGET);
        if (httpRetCode == HttpStatus.SC_OK) {
            String responseBodyAsString = locateAddressGET.getResponseBodyAsString();
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            JsonNode location = jsonRoot.path("results").get(0).path("geometry").path("location");
            JsonNode lat = location.get("lat");
            JsonNode lng = location.get("lng");
            coordinates = new LatLng(lat.asDouble(), lng.asDouble());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (locateAddressGET != null)
            locateAddressGET.releaseConnection();
        if (client != null)
            client.getState().clear();
    }
    return coordinates;
}

From source file:com.owncloud.android.lib.resources.files.ReadFileVersionsOperation.java

/**
 * Performs the read operation./*  w  w w  .  j  a va2  s .  co  m*/
 *
 * @param client Client object to communicate with the remote ownCloud server.
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    PropFindMethod query = null;

    try {
        // remote request
        if (userId.isEmpty()) {
            throw new IllegalArgumentException("UserId may not be empty!");
        }

        String uri = client.getNewWebdavUri() + "/versions/" + userId + "/versions/" + fileId;
        DavPropertyNameSet propSet = WebdavUtils.getFileVersionPropSet();

        query = new PropFindMethod(uri, propSet, DavConstants.DEPTH_1);
        int status = client.executeMethod(query);

        // check and process response
        boolean isSuccess = (status == HttpStatus.SC_MULTI_STATUS || status == HttpStatus.SC_OK);

        if (isSuccess) {
            // get data from remote folder
            MultiStatus dataInServer = query.getResponseBodyAsMultiStatus();
            readData(dataInServer, client);

            // Result of the operation
            result = new RemoteOperationResult(true, query);
            // Add data to the result
            if (result.isSuccess()) {
                result.setData(versions);
            }
        } else {
            // synchronization failed
            client.exhaustResponse(query.getResponseBodyAsStream());
            result = new RemoteOperationResult(false, query);
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
    } finally {
        if (query != null)
            query.releaseConnection(); // let the connection available for other methods

        if (result == null) {
            result = new RemoteOperationResult(new Exception("unknown error"));
            Log_OC.e(TAG, "Synchronized file with id " + fileId + ": failed");
        } else {
            if (result.isSuccess()) {
                Log_OC.i(TAG, "Synchronized file with id " + fileId + ": " + result.getLogMessage());
            } else {
                if (result.isException()) {
                    Log_OC.e(TAG, "Synchronized with id " + fileId + ": " + result.getLogMessage(),
                            result.getException());
                } else {
                    Log_OC.w(TAG, "Synchronized with id " + fileId + ": " + result.getLogMessage());
                }
            }
        }
    }

    return result;
}

From source file:com.owncloud.android.lib.resources.files.UpdateMetadataOperation.java

/**
 * @param client Client object//from   w w  w.j ava2 s  .  c om
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    PutMethod putMethod = null;
    RemoteOperationResult result;

    try {
        // remote request
        putMethod = new PutMethod(client.getBaseUri() + METADATA_URL + fileId);
        putMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        putMethod.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED);

        NameValuePair[] putParams = new NameValuePair[2];
        putParams[0] = new NameValuePair(TOKEN, token);
        putParams[1] = new NameValuePair(FORMAT, "json");
        putMethod.setQueryString(putParams);

        StringRequestEntity data = new StringRequestEntity("metaData=" + encryptedMetadataJson,
                "application/json", "UTF-8");
        putMethod.setRequestEntity(data);

        int status = client.executeMethod(putMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        if (status == HttpStatus.SC_OK) {
            String response = putMethod.getResponseBodyAsString();

            // Parse the response
            JSONObject respJSON = new JSONObject(response);
            String metadata = (String) respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA)
                    .get(NODE_META_DATA);

            result = new RemoteOperationResult(true, putMethod);
            ArrayList<Object> keys = new ArrayList<>();
            keys.add(metadata);
            result.setData(keys);
        } else {
            result = new RemoteOperationResult(false, putMethod);
            client.exhaustResponse(putMethod.getResponseBodyAsStream());
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Storing of metadata for folder " + fileId + " failed: " + result.getLogMessage(),
                result.getException());
    } finally {
        if (putMethod != null)
            putMethod.releaseConnection();
    }
    return result;
}

From source file:massbank.CallCgi.java

public void run() {
    String progName = "CallCgi";
    String msg = "";

    HttpClient client = new HttpClient();
    // ^CAEgl(msec)Zbg
    client.setTimeout(m_timeout * 1000);
    PostMethod method = new PostMethod(this.m_url);
    String strParam = "";
    if (m_params != null && m_params.size() > 0) {
        for (Enumeration keys = m_params.keys(); keys.hasMoreElements();) {
            String key = (String) keys.nextElement();
            if (!key.equals("inst_grp") && !key.equals("inst") && !key.equals("ms")
                    && !key.equals("inst_grp_adv") && !key.equals("inst_adv") && !key.equals("ms_adv")) {
                // L?[InstrumentType,MSTypeO??Stringp??[^
                String val = (String) m_params.get(key);
                strParam += key + "=" + val + "&";
                method.addParameter(key, val);
            } else {
                // L?[InstrumentType,MSType??Stringzp??[^
                String[] vals = (String[]) m_params.get(key);
                for (int i = 0; i < vals.length; i++) {
                    strParam += key + "=" + vals[i] + "&";
                    method.addParameter(key, vals[i]);
                }/*  w  w  w  .  j  av  a  2 s . c  om*/
            }
        }
        strParam = strParam.substring(0, strParam.length() - 1);
    }

    try {
        // ?s
        int statusCode = client.executeMethod(method);
        // Xe?[^XR?[h`FbN
        if (statusCode != HttpStatus.SC_OK) {
            // G?[
            msg = method.getStatusLine().toString() + "\n" + "URL  : " + this.m_url;
            msg += "\nPARAM : " + strParam;
            MassBankLog.ErrorLog(progName, msg, m_context);
            return;
        }
        // X|X
        //         this.result = method.getResponseBodyAsString();

        /**
         * modification start
         * Use method.getResponseBodyAsStream() rather 
         * than method.getResponseBodyAsString() (marked as deprecated) for updated HttpClient library.
         * Prevents logging of message:
         * "Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended."
         */

        String charset = method.getResponseCharSet();
        InputStream is = method.getResponseBodyAsStream();
        StringBuilder sb = new StringBuilder();
        String line = "";
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
            while ((line = reader.readLine()) != null) {
                reader.mark(2000);
                String forward = reader.readLine();
                if ((line.equals("") || line.equals("\n") || line.equals("OK")) && forward == null)
                    sb.append(line); // append last line to StringBuilder
                else if (forward != null)
                    sb.append(line).append("\n"); // append current line with explicit line break
                else
                    sb.append(line);

                reader.reset();
            }
            reader.close();
            is.close();

            //            this.result = sb.toString().trim();
            this.result = sb.toString(); // trim() deleted. because the last [\t] and [\n] are removed.
            if (this.result.endsWith("\n")) // remove trailing line break
            {
                int pos = this.result.lastIndexOf("\n");
                this.result = this.result.substring(0, pos);
            }
        } else {
            this.result = "";
        }

        /**
         * modification end
         */
    } catch (Exception e) {
        // G?[
        msg = e.toString() + "\n" + "URL  : " + this.m_url;
        msg += "\nPARAM : " + strParam;
        MassBankLog.ErrorLog(progName, msg, m_context);
    } finally {
        // RlNV
        method.releaseConnection();
    }
}

From source file:net.sf.sail.webapp.dao.sds.impl.SdsWorkgroupGetCommandHttpRestImpl.java

protected HttpGetRequest generateSessionBundleRequest(Long sdsWorkgroupId, Long sdsOfferingId) {
    final String url = "/offering/" + sdsOfferingId + "/bundle/" + sdsWorkgroupId + "/0";

    return new HttpGetRequest(REQUEST_HEADERS_ACCEPT, EMPTY_STRING_MAP, url, HttpStatus.SC_OK);
}

From source file:com.comcast.cats.service.util.HttpClientUtil.java

public static synchronized Object postForObject(String uri, Map<String, String> paramMap) {
    Object responseObject = new Object();

    HttpMethod httpMethod = new PostMethod(uri);

    if ((null != paramMap) && (!paramMap.isEmpty())) {
        httpMethod.setQueryString(getNameValuePair(paramMap));
    }/*from   w  ww  . j ava  2 s  .  c o  m*/

    Yaml yaml = new Yaml();

    HttpClient client = new HttpClient();
    InputStream responseStream = null;
    Reader inputStreamReader = null;

    try {
        int responseCode = client.executeMethod(httpMethod);

        if (HttpStatus.SC_OK != responseCode) {
            logger.error("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.error("[ METHOD   ] " + httpMethod.getName());
            logger.error("[ STATUS   ] " + responseCode);
        } else {
            logger.trace("[ REQUEST  ] " + httpMethod.getURI().toString());
            logger.trace("[ METHOD   ] " + httpMethod.getName());
            logger.trace("[ STATUS   ] " + responseCode);
        }

        responseStream = httpMethod.getResponseBodyAsStream();
        inputStreamReader = new InputStreamReader(responseStream, VideoRecorderServiceConstants.UTF);
        responseObject = yaml.load(inputStreamReader);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        cleanUp(inputStreamReader, responseStream, httpMethod);
    }

    return responseObject;
}

From source file:com.ikanow.infinit.e.harvest.enrichment.legacy.HttpClientPost.java

private void doRequest(File file, PostMethod method) {
    try {//from www.  j a  v  a  2  s  . c o  m
        int returnCode = client.executeMethod(method);
        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.err.println("The Post method is not implemented by this URI");
            // still consume the response body
            method.getResponseBodyAsString();
        } else if (returnCode == HttpStatus.SC_OK) {
            System.out.println("File post succeeded: " + file);
            saveResponse(file, method);
        } else {
            System.err.println("File post failed: " + file);
            System.err.println("Got code: " + returnCode);
            System.err.println("response: " + method.getResponseBodyAsString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        method.releaseConnection();
    }
}

From source file:com.owncloud.android.lib.resources.files.ReadRemoteTrashbinFolderOperation.java

/**
 * Performs the read operation.//from w  w  w  .  ja va 2 s . co m
 *
 * @param client Client object to communicate with the remote ownCloud server.
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    PropFindMethod query = null;

    try {
        // remote request
        if (userId.isEmpty()) {
            throw new IllegalArgumentException("UserId may not be empty!");
        }

        String baseUri = client.getNewWebdavUri() + "/trashbin/" + userId + "/trash/";
        DavPropertyNameSet propSet = WebdavUtils.getTrashbinPropSet();

        query = new PropFindMethod(baseUri + WebdavUtils.encodePath(remotePath), propSet, DavConstants.DEPTH_1);
        int status = client.executeMethod(query);

        // check and process response
        boolean isSuccess = (status == HttpStatus.SC_MULTI_STATUS || status == HttpStatus.SC_OK);

        if (isSuccess) {
            // get data from remote folder
            MultiStatus dataInServer = query.getResponseBodyAsMultiStatus();
            readData(dataInServer, client);

            // Result of the operation
            result = new RemoteOperationResult(true, query);
            // Add data to the result
            if (result.isSuccess()) {
                result.setData(folderAndFiles);
            }
        } else {
            // synchronization failed
            client.exhaustResponse(query.getResponseBodyAsStream());
            result = new RemoteOperationResult(false, query);
        }
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
    } finally {
        if (query != null)
            query.releaseConnection(); // let the connection available for other methods

        if (result == null) {
            result = new RemoteOperationResult(new Exception("unknown error"));
            Log_OC.e(TAG, "Synchronized " + remotePath + ": failed");
        } else {
            if (result.isSuccess()) {
                Log_OC.i(TAG, "Synchronized " + remotePath + ": " + result.getLogMessage());
            } else {
                if (result.isException()) {
                    Log_OC.e(TAG, "Synchronized " + remotePath + ": " + result.getLogMessage(),
                            result.getException());
                } else {
                    Log_OC.e(TAG, "Synchronized " + remotePath + ": " + result.getLogMessage());
                }
            }
        }
    }

    return result;
}

From source file:eu.eco2clouds.accounting.bonfire.BFClientAccountingImpl.java

private String getMethod(String url, Boolean exception) {
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    GetMethod method = new GetMethod(url);
    setHeaders(method);//w  w  w .  j  a va2s. com

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

    String response = "";

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) { //TODO test for this case... 
            logger.warn(
                    "get managed experiments information... : " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:com.zimbra.qa.unittest.TestWsdlServlet.java

public void testWsdlServletZimbraUserServicesWsdl() throws Exception {
    String body = doWsdlServletRequest(wsdlUrlBase + "ZimbraUserService.wsdl", false, HttpStatus.SC_OK);
    assertTrue("Body contains expected string", body.contains("wsdl:service name="));
}