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.owncloud.android.lib.resources.files.CheckEtagOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    try {//w  w w.  j a v a  2  s  .  c  om
        DavPropertyNameSet propSet = new DavPropertyNameSet();
        propSet.add(DavPropertyName.GETETAG);

        PropFindMethod propfind = new PropFindMethod(client.getWebdavUri() + WebdavUtils.encodePath(path),
                propSet, 0);
        int status = client.executeMethod(propfind, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);

        if (status == HttpStatus.SC_MULTI_STATUS || status == HttpStatus.SC_OK) {
            MultiStatusResponse resp = propfind.getResponseBodyAsMultiStatus().getResponses()[0];

            String etag = WebdavUtils.parseEtag(
                    (String) resp.getProperties(HttpStatus.SC_OK).get(DavPropertyName.GETETAG).getValue());

            if (etag.equals(expectedEtag)) {
                return new RemoteOperationResult(RemoteOperationResult.ResultCode.ETAG_UNCHANGED);
            } else {
                RemoteOperationResult result = new RemoteOperationResult(
                        RemoteOperationResult.ResultCode.ETAG_CHANGED);

                ArrayList<Object> list = new ArrayList<>();
                list.add(etag);
                result.setData(list);

                return result;
            }
        }

        if (status == HttpStatus.SC_NOT_FOUND) {
            return new RemoteOperationResult(RemoteOperationResult.ResultCode.FILE_NOT_FOUND);
        }
    } catch (Exception e) {
        Log_OC.e(TAG, "Error while retrieving eTag");
    }

    return new RemoteOperationResult(RemoteOperationResult.ResultCode.ETAG_CHANGED);
}

From source file:com.calclab.emite.xtesting.services.HttpConnector.java

private Runnable createResponseAction(final String xml, final ConnectorCallback callback, final String id,
        final int status, final String response) {
    final Runnable runnable = new Runnable() {
        public void run() {
            if (status == HttpStatus.SC_OK) {
                System.out.println("RECEIVED: " + response);
                debug("Connector [{0}] receive: {1}", id, response);
                callback.onResponseReceived(status, response, xml);
            } else {
                debug("Connector [{0}] bad status: {1}", id, status);
                callback.onError(xml, new Exception("bad http status " + status));
            }/*from w  ww  .j av a 2 s.c  o m*/

        }

    };
    return runnable;
}

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 .j a va  2  s . 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.owncloud.android.lib.resources.files.UnlockFileOperation.java

/**
 * @param client Client object//from w w w.  jav  a  2 s. co  m
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result;
    DeleteMethod deleteMethod = null;

    try {
        // remote request
        deleteMethod = new DeleteMethod(client.getBaseUri() + LOCK_FILE_URL + localId);
        deleteMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        deleteMethod.addRequestHeader(CONTENT_TYPE, FORM_URLENCODED);
        deleteMethod.addRequestHeader(TOKEN, token);

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

        result = new RemoteOperationResult(status == HttpStatus.SC_OK, deleteMethod);

        client.exhaustResponse(deleteMethod.getResponseBodyAsStream());
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Unlock file with id " + localId + " failed: " + result.getLogMessage(),
                result.getException());
    } finally {
        if (deleteMethod != null)
            deleteMethod.releaseConnection();
    }
    return result;
}

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 w  w. ja v a2  s.c  o m*/
    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:fr.aliasource.webmail.server.proxy.client.http.AbstractClientMethod.java

protected InputStream executeStream(Map<String, String> parameters) {
    InputStream is = null;//from   w  w w  .  j ava 2  s. c  om
    PostMethod pm = new PostMethod(url);
    pm.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    for (String p : parameters.keySet()) {
        pm.setParameter(p, parameters.get(p));
    }
    int ret = 0;
    synchronized (hc) {
        try {
            ret = hc.executeMethod(pm);
            if (ret == HttpStatus.SC_NOT_MODIFIED) {
                logger.info("backend wants us to use cached data");
            } else if (ret != HttpStatus.SC_OK) {
                logger.error("method failed:\n" + pm.getStatusLine() + "\n" + pm.getResponseBodyAsString());
            } else {
                is = pm.getResponseBodyAsStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                transfer(is, out, true);
                return new ByteArrayInputStream(out.toByteArray());
            }
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        } finally {
            pm.releaseConnection();
        }
    }
    return is;
}

From source file:ixa.pipe.ned.DBpediaSpotlightClient.java

public String request(HttpMethod method) throws AnnotationException {

    String response = null;//  w  w  w . jav a  2s  .c  o  m

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

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

        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        // // Deal with the response.
        // // Use caution: ensure correct character encoding and is not binary data
        InputStream responseBody = method.getResponseBodyAsStream();
        response = StreamUtils.copyToString(responseBody, Charset.forName("UTF-8"));

    } catch (HttpException e) {
        LOG.error("Fatal protocol violation: " + e.getMessage());
        throw new AnnotationException("Protocol error executing HTTP request.", e);
    } catch (IOException e) {
        LOG.error("Fatal transport error: " + e.getMessage());
        LOG.error(method.getQueryString());
        throw new AnnotationException("Transport error executing HTTP request.", e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return response;

}

From source file:com.thoughtworks.go.util.TimeReportingUtil.java

public void report() throws IOException {
    long difference = new Date().getTime() - begin.getTime();
    HttpClient httpClient = new HttpClient();
    HttpService.HttpClientFactory factory = new HttpService.HttpClientFactory(httpClient);
    PostMethod post = factory.createPost("http://host:3000/properties");
    post.addParameter("property[key]", key);
    post.addParameter("property[value]", String.valueOf(difference));
    try {//from   ww w  .  j  av  a  2  s .co  m
        httpClient.executeMethod(post);
    } finally {
        begin = null;
    }
    if (shouldThrowUp()) {
        if (post.getStatusCode() != HttpStatus.SC_OK) {
            throw new RuntimeException(
                    String.format("[Error] Posting [Key: %s] [Value: %s] failed.with status code %s", key,
                            difference, post.getStatusCode()));
        }
    }
}

From source file:com.owncloud.android.lib.resources.users.GetPublicKeyOperation.java

/**
 * @param client Client object/* w w w.j a  va2  s  .c o m*/
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    GetMethod getMethod = null;
    RemoteOperationResult result;

    try {
        // remote request
        getMethod = new GetMethod(client.getBaseUri() + PUBLIC_KEY_URL + JSON_FORMAT);
        getMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

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

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

            // Parse the response
            JSONObject respJSON = new JSONObject(response);
            String key = (String) respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA)
                    .getJSONObject(NODE_PUBLIC_KEYS).get(userID);

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

From source file:com.bigrocksoftware.metarparser.MetarFetcher.java

public static String fetch(String station, int timeout) {
    metarData = null;/*w  w  w . ja  va 2s .c  o m*/

    // create the http client
    HttpClient client = new HttpClient();

    // set the timeout is specified
    if (timeout != 0) {
        log.debug("MetarFetch: setting timeout to '" + timeout + "' milliseconds");
        long start = System.currentTimeMillis();
        client.setConnectionTimeout(timeout);
        long end = System.currentTimeMillis();
        if (end - start < timeout) {
            client.setTimeout((int) (end - start));
        } else {
            return null;
        }
    }

    // create the http method we will use
    HttpMethod method = new GetMethod(httpMetarURL + station + ".TXT");

    // connect to the NOAA site, retrying up to the specified num
    int statusCode = -1;
    //for (int attempt = 0; statusCode == -1 && attempt < 3; attempt++) {
    try {
        // execute the get method
        log.debug("MetarFetcher: downloading data for station '" + station + "'");
        statusCode = client.executeMethod(method);
    } catch (HttpRecoverableException e) {
        log.error("a recoverable exception occurred, " + "retrying." + e.getMessage());
    } catch (IOException e) {
        log.error("failed to download file: " + e);
    }
    //}

    // check that we didn't run out of retries
    if (statusCode != HttpStatus.SC_OK) {
        log.error("failed to download station data for '" + station + "'");
        return null;
    } else {
        // read the response body
        byte[] responseBody = method.getResponseBody();

        // release the connection
        method.releaseConnection();

        // deal with the response.
        // FIXME - ensure we use the correct character encoding here
        metarData = new String(responseBody) + "\n";
        log.debug("MetarFetcher: metar data: " + metarData);
    }

    return metarData;
}