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:edu.du.penrose.systems.fedoraApp.tests.sendEctdRestResults.java

public void testRun() {

    try {/*  w  w  w .  j  ava  2 s.  co m*/
        HttpClient client = new HttpClient();
        client.getParams().setParameter("http.useragent", "fedoraProxy Client");

        final String HOST = "130.253.33.105";
        final String PORT = "8085";
        final String CMD = "/library/updatePid";
        final String KEY = "6b476c7e50726949347162353c7e3d7271336e6f3e3e4c2d703d762d24";

        String objid = "du_174_1793_primary_1999_kelly";
        String pid = "178";

        StringBuffer ectdResultsUrl = new StringBuffer("http://");
        ectdResultsUrl.append(HOST);
        ectdResultsUrl.append(":");
        ectdResultsUrl.append(PORT);
        ectdResultsUrl.append(CMD);

        GetMethod method = new GetMethod(ectdResultsUrl.toString());
        HttpMethodParams params = new HttpClientParams();
        params.setParameter("id", objid);
        params.setParameter("pid", pid);

        method.setParams(params);

        try {
            int returnCode = client.executeMethod(method);

            if (returnCode != HttpStatus.SC_OK) {
                System.err.println("ERROR");
            }
        } catch (Exception e) {
            System.err.println(e);
        } finally {
            method.releaseConnection();
        }

    } catch (Exception e) {
        System.out.println("Exception: " + e.getMessage());
    }

}

From source file:fr.aliasource.webmail.server.calendar.CalendarProxyImpl.java

@SuppressWarnings("unchecked")
@Override/*from  ww w . ja  v  a2 s. c o  m*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    IAccount ac = (IAccount) req.getSession().getAttribute("account");

    if (ac == null) {
        GWT.log("Account not found in session", null);
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    PostMethod pm = new PostMethod(backendUrl);
    if (req.getQueryString() != null) {
        pm.setQueryString(req.getQueryString());
    }
    Map<String, String[]> params = req.getParameterMap();
    for (String p : params.keySet()) {
        String[] val = params.get(p);
        pm.setParameter(p, val[0]);
    }

    synchronized (hc) {
        try {
            int ret = hc.executeMethod(pm);
            if (ret != HttpStatus.SC_OK) {
                log("method failed:\n" + pm.getStatusLine() + "\n" + pm.getResponseBodyAsString());
                resp.setStatus(ret);
            } else {
                InputStream is = pm.getResponseBodyAsStream();
                transfer(is, resp.getOutputStream(), false);
            }
        } catch (Exception e) {
            log("error occured on call proxyfication", e);
        } finally {
            pm.releaseConnection();
        }
    }
}

From source file:com.cyberway.issue.crawler.datamodel.CrawlSubstats.java

/**
 * Examing the CrawlURI and based on its status and internal values,
 * update tallies. /*from ww  w.jav a  2 s.c  o m*/
 * 
 * @param curi
 * @deprecated
 */
public synchronized void tally(CrawlURI curi) {
    if (curi.getFetchStatus() <= 0) {
        fetchNonResponses++;
        return;
    }
    fetchResponses++;
    totalBytes += curi.getContentSize();
    if (curi.getFetchStatus() >= HttpStatus.SC_OK && curi.getFetchStatus() < 300) {
        fetchSuccesses++;
        successBytes += curi.getContentSize();
    }
}

From source file:edu.unc.lib.dl.ui.service.DjatokaContentService.java

public void getMetadata(String simplepid, String datastream, OutputStream outStream,
        HttpServletResponse response, int retryServerError) {
    HttpClientParams params = new HttpClientParams();
    params.setContentCharset("UTF-8");
    HttpClient client = new HttpClient();
    client.setParams(params);//from ww  w  .ja v a 2  s.c  o m

    StringBuilder path = new StringBuilder(applicationPathSettings.getDjatokaPath());
    path.append("resolver?url_ver=Z39.88-2004&rft_id=")
            .append(applicationPathSettings.getFedoraPathWithoutDefaultPort()).append("/objects/")
            .append(simplepid).append("/datastreams/").append(datastream).append("/content")
            .append("&svc_id=info:lanl-repo/svc/getMetadata");

    GetMethod method = new GetMethod(path.toString());
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            if (response != null) {
                response.setHeader("Content-Type", "application/json");
                response.setHeader("content-disposition", "inline");

                FileIOUtil.stream(outStream, method);
            }
        } else {
            if ((method.getStatusCode() == 500 || method.getStatusCode() == 404) && retryServerError > 0) {
                this.getMetadata(simplepid, datastream, outStream, response, retryServerError - 1);
            } else {
                LOG.error("Unexpected failure: " + method.getStatusLine().toString());
                LOG.error("Path was: " + method.getURI().getURI());
            }
        }
    } catch (ClientAbortException e) {
        if (LOG.isDebugEnabled())
            LOG.debug("User client aborted request to stream jp2 metadata for " + simplepid, e);
    } catch (Exception e) {
        LOG.error("Problem retrieving metadata for " + path, e);
    } finally {
        method.releaseConnection();
    }
}

From source file:ch.algotrader.starter.GoogleIntradayDownloader.java

private void retrieve(HttpClient httpclient, String symbol, int interval, int tradingDays)
        throws IOException, HttpException, FileNotFoundException {

    GetMethod fileGet = new GetMethod("http://www.google.com/finance/getprices?" + "q=" + symbol + "&i="
            + interval + "&p=" + tradingDays + "d" + "&f=d,o,h,l,c,v");

    fileGet.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    try {//  ww  w  .  j  a  v a 2s . co  m
        int status = httpclient.executeMethod(fileGet);

        if (status == HttpStatus.SC_OK) {

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(fileGet.getResponseBodyAsStream()));

            File parent = new File("files" + File.separator + "google");
            if (!parent.exists()) {
                FileUtils.forceMkdir(parent);
            }

            Writer writer = new OutputStreamWriter(
                    new FileOutputStream(new File(parent, symbol + "-" + (interval / 60) + "min.csv")));

            writer.write("dateTime,open,high,low,close,vol,barSize,security\n");

            try {

                reader.readLine();
                reader.readLine();
                reader.readLine();
                reader.readLine();
                reader.readLine();
                reader.readLine();
                reader.readLine();

                String line;
                long timestamp = 0;
                while ((line = reader.readLine()) != null) {
                    String tokens[] = line.split(",");

                    long time;
                    String timeStampString = tokens[0];
                    if (timeStampString.startsWith("a")) {
                        timestamp = Long.parseLong(timeStampString.substring(1)) * 1000;
                        time = timestamp;
                    } else {
                        time = timestamp + Integer.parseInt(timeStampString) * interval * 1000;
                    }

                    writer.write(Long.toString(time));
                    writer.write(",");
                    writer.write(tokens[1]);
                    writer.write(",");
                    writer.write(tokens[2]);
                    writer.write(",");
                    writer.write(tokens[3]);
                    writer.write(",");
                    writer.write(tokens[4]);
                    writer.write(",");
                    writer.write(tokens[5]);
                    writer.write(",");
                    writer.write("MIN_" + interval / 60);
                    writer.write(",");
                    writer.write(symbol);
                    writer.write("\n");
                }

            } finally {
                reader.close();
                writer.close();
            }
        }
    } finally {
        fileGet.releaseConnection();
    }
}

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

/**
 * @param client Client object/*  w ww. j  a va 2s .  com*/
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    PostMethod postMethod = null;
    RemoteOperationResult result;

    try {
        // remote request
        postMethod = new PostMethod(client.getBaseUri() + PUBLIC_KEY_URL + JSON_FORMAT);
        postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
        postMethod.setParameter(CSR, csr);

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

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

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

            result = new RemoteOperationResult(true, postMethod);
            ArrayList<Object> keys = new ArrayList<>();
            keys.add(key);
            result.setData(keys);
        } else {
            result = new RemoteOperationResult(false, postMethod);
            client.exhaustResponse(postMethod.getResponseBodyAsStream());
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Fetching of signing CSR failed: " + result.getLogMessage(), result.getException());
    } finally {
        if (postMethod != null)
            postMethod.releaseConnection();
    }
    return result;
}

From source file:fr.aliasource.webmail.server.invitation.GoingInvitationProxyImpl.java

@SuppressWarnings("unchecked")
@Override// w  w  w . jav a2  s  . com
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    IAccount ac = (IAccount) req.getSession().getAttribute("account");

    if (ac == null) {
        GWT.log("Account not found in session", null);
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    PostMethod pm = new PostMethod(backendUrl);
    if (req.getQueryString() != null) {
        pm.setQueryString(req.getQueryString());
    }
    Map<String, String[]> params = req.getParameterMap();
    for (String p : params.keySet()) {
        String[] val = params.get(p);
        pm.setParameter(p, val[0]);
    }

    synchronized (hc) {
        try {
            int ret = hc.executeMethod(pm);
            if (ret != HttpStatus.SC_OK) {
                log("method failed:\n" + pm.getStatusLine() + "\n" + pm.getResponseBodyAsString());
                resp.setStatus(ret);
            } else {
                InputStream is = pm.getResponseBodyAsStream();
                transfer(is, resp.getOutputStream(), false);
            }
        } catch (Exception e) {
            log("error occured on call proxyfication", e);
        } finally {
            pm.releaseConnection();
        }
    }
}

From source file:com.googlecode.fascinator.indexer.SolrSearcher.java

public InputStream get(String query, Map<String, Set<String>> extras, boolean escape) throws IOException {
    if (query == null) {
        query = "*:*";
    } else if (!QUERY_ALL.equals(query) && escape) {
        query = query.replaceAll(":", "\\\\:");
    }//from  w  ww .ja  v  a 2 s  .  c om
    String selectUrl = baseUrl + "/select";
    NameValuePair[] postData = getPostData(query, extras);
    log.debug("URL:{}, POSTDATA:{}", selectUrl, postData);
    PostMethod method = new PostMethod(selectUrl);
    method.addRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    method.setRequestBody(postData);
    int status = client.executeMethod(method, true);
    if (status == HttpStatus.SC_OK) {
        return method.getResponseBodyAsStream();
    }
    return null;
}

From source file:com.discogs.api.webservice.impl.HttpClientWebService.java

@Override
public Resp doGet(String url) throws WebServiceException {
    HttpMethod method = new GZipCapableGetMethod(url);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    method.setDoAuthentication(true);/*  w  w  w .j  a  v  a 2  s  .co m*/

    try {
        // execute the method
        int statusCode = this.httpClient.executeMethod(method);

        if (logger.isDebugEnabled()) {
            logger.debug(method.getResponseBodyAsString());
        }

        switch (statusCode) {
        case HttpStatus.SC_OK:
            return createResp(method.getResponseBodyAsStream());

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceNotFoundException("Resource not found.", method.getResponseBodyAsString());

        case HttpStatus.SC_BAD_REQUEST:
            throw new RequestException(method.getResponseBodyAsString());

        case HttpStatus.SC_FORBIDDEN:
            throw new AuthorizationException(method.getResponseBodyAsString());

        case HttpStatus.SC_UNAUTHORIZED:
            throw new AuthorizationException(method.getResponseBodyAsString());

        default:
            String em = "web service returned unknown status '" + statusCode + "', response was: "
                    + method.getResponseBodyAsString();
            logger.error(em);
            throw new WebServiceException(em);
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } catch (IOException e) {
        logger.error("Fatal transport error: " + e.getMessage());
        throw new WebServiceException(e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.googlecode.gmail4j.http.HttpProxyAwareSslSocketFactory.java

@Override
public Socket createSocket() throws IOException {
    //FIXME won't work..
    log.debug("Creating socket! with proxy: " + proxy.address());
    InetSocketAddress addr = (InetSocketAddress) proxy.address();
    ProxyClient proxyClient = new ProxyClient();
    proxyClient.getHostConfiguration().setHost("imap.gmail.com", 993);
    proxyClient.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
    if (proxyCredentials != null) {
        proxyClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                proxyCredentials.getUsername(), new String(proxyCredentials.getPasword())));
    }/*w  w  w  . ja va2s  . com*/
    log.debug("Trying to connect to proxy");
    ProxyClient.ConnectResponse resp = proxyClient.connect();
    if (resp.getConnectMethod().getStatusCode() != HttpStatus.SC_OK) {
        log.error("Failed to connect. " + resp.getConnectMethod().getStatusLine());
        throw new GmailException(
                "Failed connecting to IMAP through proxy: " + resp.getConnectMethod().getStatusLine());
    }
    log.debug("Connected, returning socket");
    return resp.getSocket();
}