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.zimbra.qa.unittest.TestCookieReuse.java

/**
 * Verify that we can use the cookie for REST session if the session is valid
 *///from w ww  . j  a va2  s. c om
@Test
public void testValidCookie() throws ServiceException, IOException {
    ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
    URI uri = mbox.getRestURI("Inbox?fmt=rss");

    HttpClient client = mbox.getHttpClient(uri);
    GetMethod get = new GetMethod(uri.toString());
    int statusCode = HttpClientUtil.executeMethod(client, get);
    Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK,
            statusCode);
}

From source file:com.apatar.ui.JHelpDialog.java

private void addListeners() {
    sendButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent arg0) {

            PostMethod filePost = new PostMethod(getUrl());

            // filePost.getParameters().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            try {
                List<File> targetFiles = getAttachFiles();
                Part[] parts;//  w  w  w  .  j ava 2  s.  c o m
                if (targetFiles != null) {
                    parts = new Part[targetFiles.size() + 1];
                    int i = 1;
                    for (File targetFile : targetFiles) {
                        parts[i++] = new FilePart("file" + i, targetFile);
                    }
                    ;
                } else
                    parts = new Part[1];

                parts[0] = new StringPart("FeatureRequest", text.getText());

                filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                HttpClient client = new HttpClient();
                client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                int status = client.executeMethod(filePost);
                if (status != HttpStatus.SC_OK) {
                    JOptionPane.showMessageDialog(ApatarUiMain.MAIN_FRAME,
                            "Upload failed, response=" + HttpStatus.getStatusText(status));
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                filePost.releaseConnection();
            }

        }

    });
}

From source file:com.lp.client.frame.component.phone.HttpPhoneDialer.java

protected void dialImpl(String number) throws ExceptionLP {
    myLogger.info("Dialing <" + number + "> ...");

    GetMethod method = getHttpMethod(number);

    try {//from ww  w.  ja  v a2s. c  o m
        prepareClient(client, method);
        int status = client.executeMethod(method);

        myLogger.info("Dialing done with HTTP Status: <" + status + ">");
        if (status != HttpStatus.SC_OK) {
            byte[] responseBody = method.getResponseBody();
            String s = new String(responseBody);

            myLogger.debug("Done dialing with response <" + s + ">");
        }
    } catch (HttpException ex) {
        myLogger.debug("Got HttpException <" + ex.getMessage() + ">");
        throw new ExceptionLP(EJBExceptionLP.FEHLER_TELEFON_WAHLVORGANG, ex.getMessage(), ex);
    } catch (IOException ex) {
        myLogger.debug("Got IOException <" + ex.getMessage() + ">");
        throw new ExceptionLP(EJBExceptionLP.FEHLER_TELEFON_WAHLVORGANG, ex.getMessage(), ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java

public InputStream sendMessage(String url, Map<String, String> parameters)
        throws IOException, SlideShareErrorException {
    HttpClient client = createHttpClient();
    PostMethod method = new PostMethod(url);
    method.addParameter("api_key", this.apiKey);
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        method.addParameter(entry.getKey(), entry.getValue());
    }/*from  www.ja  v a  2 s .  c o m*/
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    method.addParameter("ts", ts);
    method.addParameter("hash", hash);
    logger.debug("Sending POST message to " + method.getURI().getURI() + " with parameters "
            + Arrays.toString(method.getParameters()));
    int statusCode = client.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}

From source file:com.serena.rlc.provider.jenkins.client.JenkinsClient.java

/**
 * Send a POST and returns the Location header which contains the url to the queued item
 *
 * @param jenkinsUrl/*www . j a v a 2s  .  com*/
 * @param postPath
 * @param postData
 * @return Response body
 * @throws JenkinsClientException
 */
public String processBuildPost(String jenkinsUrl, String postPath, String postData)
        throws JenkinsClientException {
    String uri = createUrl(jenkinsUrl, postPath);

    logger.debug("Start executing Jenkins POST request to url=\"{}\" with payload={}", uri);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(uri);

    if (getJenkinsUsername() != null && !StringUtils.isEmpty(getJenkinsUsername())) {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getJenkinsUsername(),
                getJenkinsPassword());
        postRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    }

    postRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    postRequest.addHeader(HttpHeaders.ACCEPT, "application/json");
    String result = "";

    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("json", postData));

    try {

        postRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        HttpResponse response = httpClient.execute(postRequest);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK
                && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            throw createHttpError(response);
        }

        result = response.getFirstHeader("Location").getValue();

        logger.debug("End executing Jenkins POST request to url=\"{}\" and receive this result={}", uri,
                result);

    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new JenkinsClientException("Server not available", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return result;
}

From source file:fr.cls.atoll.motu.library.misc.cas.TestCASRest.java

public static Cookie[] validateFromCAS2(String username, String password) throws Exception {

    String url = casServerUrlPrefix + "/v1/tickets?";

    String s = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
    s += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

    HttpState initialState = new HttpState();
    // Initial set of cookies can be retrieved from persistent storage and
    // re-created, using a persistence mechanism of choice,
    // Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false);

    // Create an instance of HttpClient.
    // HttpClient client = new HttpClient();
    HttpClient client = new HttpClient();

    Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 8443);

    URI uri = new URI(url + s, true);
    // use relative url only
    PostMethod httpget = new PostMethod(url);
    httpget.addParameter("username", username);
    httpget.addParameter("password", password);

    HostConfiguration hc = new HostConfiguration();
    hc.setHost("atoll-dev.cls.fr", 8443, easyhttps);
    // client.executeMethod(hc, httpget);

    client.setState(initialState);//from   ww  w. jav a  2  s  .  com

    // Create a method instance.
    System.out.println(url + s);

    GetMethod method = new GetMethod(url + s);
    // GetMethod method = new GetMethod(url );

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setProxy("proxy.cls.fr", 8080);
    client.setHostConfiguration(hostConfiguration);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    // String username = "xxx";
    // String password = "xxx";
    // Credentials credentials = new UsernamePasswordCredentials(username, password);
    // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080);
    //           
    // client.getState().setProxyCredentials(authScope, credentials);
    Cookie[] cookies = null;

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

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        for (Header header : method.getRequestHeaders()) {
            System.out.println(header.getName());
            System.out.println(header.getValue());
        }
        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

        System.out.println("Response status code: " + statusCode);
        // Get all the cookies
        cookies = client.getState().getCookies();
        // Display the cookies
        System.out.println("Present cookies: ");
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(" - " + cookies[i].toExternalForm());
        }

        Assertion assertion = AssertionHolder.getAssertion();
        if (assertion == null) {
            System.out.println("<p>Assertion is null</p>");
        }

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return cookies;

}

From source file:com.hp.mercury.ci.jenkins.plugins.oo.core.OOAccessibilityLayer.java

public static OORunResponse run(OORunRequest request) throws IOException, URISyntaxException {

    String urlString = StringUtils.slashify(request.getServer().getUrl()) + REST_SERVICES_URL_PATH
            + RUN_OPERATION_URL_PATH + StringUtils.unslashifyPrefix(request.getFlow().getId());

    final URI uri = OOBuildStep.URI(urlString);
    final HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(new JaxbEntity(request));
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml");
    //        if (OOBuildStep.getEncodedCredentials()!=null) {
    //            httpPost.addHeader("Authorization", "Basic " + new String(OOBuildStep.getEncodedCredentials()));
    //        }/*from ww  w.  j av a 2  s  .  c o  m*/

    HttpResponse response;

    response = client.execute(httpPost);
    final int statusCode = response.getStatusLine().getStatusCode();
    final HttpEntity entity = response.getEntity();

    try {
        if (statusCode == HttpStatus.SC_OK) {

            return JAXB.unmarshal(entity.getContent(), OORunResponse.class);

        } else {

            throw new RuntimeException("unable to get run result from " + uri + ", response code: " + statusCode
                    + "(" + HttpStatus.getStatusText(statusCode) + ")");
        }
    } finally {
        EntityUtils.consume(entity);
    }
}

From source file:ai.grakn.engine.controller.ConceptController.java

@GET
@Path("concept/{id}")
@ApiOperation(value = "Return the HAL representation of a given concept.")
@ApiImplicitParams({/*from   www  .  j  a  va2 s.co  m*/
        @ApiImplicitParam(name = IDENTIFIER, value = "Identifier of the concept", required = true, dataType = "string", paramType = "path"),
        @ApiImplicitParam(name = KEYSPACE, value = "Name of graph to use", required = true, dataType = "string", paramType = "query"),
        @ApiImplicitParam(name = OFFSET_EMBEDDED, value = "Offset to begin at for embedded HAL concepts", required = true, dataType = "boolean", paramType = "query"),
        @ApiImplicitParam(name = LIMIT_EMBEDDED, value = "Limit on the number of embedded HAL concepts", required = true, dataType = "boolean", paramType = "query") })
private Json conceptByIdentifier(Request request, Response response) {
    validateRequest(request, APPLICATION_ALL, APPLICATION_HAL);

    String keyspace = mandatoryQueryParameter(request, KEYSPACE);
    ConceptId conceptId = ConceptId.of(mandatoryRequestParameter(request, ID_PARAMETER));
    int offset = queryParameter(request, OFFSET_EMBEDDED).map(Integer::parseInt).orElse(0);
    int limit = queryParameter(request, LIMIT_EMBEDDED).map(Integer::parseInt).orElse(-1);
    try (GraknGraph graph = factory.getGraph(keyspace, READ); Context context = conceptIdGetTimer.time()) {
        Concept concept = retrieveExistingConcept(graph, conceptId);

        response.type(APPLICATION_HAL);
        response.status(HttpStatus.SC_OK);

        return Json.read(renderHALConceptData(concept, separationDegree, keyspace, offset, limit));
    }
}

From source file:com.sittinglittleduck.DirBuster.Worker.java

/** Run method of the thread */
public void run() {

    queue = manager.workQueue;/*w w w. j a v a2 s .c o m*/
    while (manager.hasWorkLeft()) {

        working = false;
        // code to make the worker pause, if the pause button has been presed

        // if the stop signal has been given stop the thread
        if (stop) {
            return;
        }

        // this pauses the thread
        synchronized (this) {
            while (pleaseWait) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    return;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        HttpMethodBase httpMethod = null;

        try {

            work = (WorkUnit) queue.take();
            working = true;
            url = work.getWork();
            int code = 0;

            String response = "";
            String rawResponse = "";

            httpMethod = createHttpMethod(work.getMethod(), url.toString());

            // if the work is a head request
            if (work.getMethod().equalsIgnoreCase("HEAD")) {
                code = makeRequest(httpMethod);
                httpMethod.releaseConnection();

            }
            // if we are doing a get request
            else if (work.getMethod().equalsIgnoreCase("GET")) {
                code = makeRequest(httpMethod);

                String rawHeader = getHeadersAsString(httpMethod);
                response = getResponseAsString(httpMethod);

                rawResponse = rawHeader + response;
                // clean the response

                if (Config.parseHTML && !work.getBaseCaseObj().isUseRegexInstead()) {
                    parseHtml(httpMethod, response);
                }

                response = FilterResponce.CleanResponce(response, work);

                Thread.sleep(10);
                httpMethod.releaseConnection();
            }

            // if we need to check the against the base case
            if (work.getMethod().equalsIgnoreCase("GET") && work.getBaseCaseObj().useContentAnalysisMode()) {
                if (code == HttpStatus.SC_OK) {
                    verifyResponseForValidRequests(code, response, rawResponse);
                } else if (code == HttpStatus.SC_NOT_FOUND || code == HttpStatus.SC_BAD_REQUEST) {
                    if (Config.debug) {
                        System.out
                                .println("DEBUG Worker[" + threadId + "]: " + code + " for: " + url.toString());
                    }
                } else {
                    notifyItemFound(code, response, rawResponse, work.getBaseCaseObj().getBaseCase());
                }
            }
            /*
             * use the custom regex check instead
             */
            else if (work.getBaseCaseObj().isUseRegexInstead()) {
                Pattern regexFindFile = Pattern.compile(work.getBaseCaseObj().getRegex());

                Matcher m = regexFindFile.matcher(rawResponse);

                if (m.find()) {
                    // do nothing as we have a 404
                    if (Config.debug) {
                        System.out.println("DEBUG Worker[" + threadId + "]: Regex matched so it's a 404, "
                                + url.toString());
                    }

                } else {
                    if (Config.parseHTML) {
                        parseHtml(httpMethod, rawResponse);
                    }

                    notifyItemFound(code, response, rawResponse, work.getBaseCaseObj().getBaseCase());
                }

            }
            // just check the response code
            else {
                // if is not the fail code, a 404 or a 400 then we have a possible
                if (code != work.getBaseCaseObj().getFailCode() && verifyIfCodeIsValid(code)) {
                    if (work.getMethod().equalsIgnoreCase("HEAD")) {
                        httpMethod = createHttpMethod("GET", url.toString());
                        int newCode = makeRequest(httpMethod);

                        // in some cases the second get can return a different result, than the
                        // first head request!
                        if (newCode != code) {
                            manager.foundError(url,
                                    "Return code for first HEAD, is different to the second GET: " + code
                                            + " - " + newCode);
                        }

                        // build a string version of the headers
                        rawResponse = getHeadersAsString(httpMethod);

                        if (httpMethod.getResponseContentLength() > 0) {

                            String responseBodyAsString = getResponseAsString(httpMethod);
                            rawResponse = rawResponse + responseBodyAsString;

                            if (Config.parseHTML) {
                                parseHtml(httpMethod, responseBodyAsString);
                            }
                        }

                        httpMethod.releaseConnection();
                    }

                    if (work.isDir()) {
                        manager.foundDir(url, code, rawResponse, work.getBaseCaseObj());
                    } else {
                        manager.foundFile(url, code, rawResponse, work.getBaseCaseObj());
                    }
                }
            }

            manager.workDone();
            Thread.sleep(20);

        } catch (NoHttpResponseException e) {
            manager.foundError(url, "NoHttpResponseException " + e.getMessage());
            manager.workDone();
        } catch (ConnectTimeoutException e) {
            manager.foundError(url, "ConnectTimeoutException " + e.getMessage());
            manager.workDone();
        } catch (URIException e) {
            manager.foundError(url, "URIException " + e.getMessage());
            manager.workDone();
        } catch (IOException e) {

            manager.foundError(url, "IOException " + e.getMessage());
            manager.workDone();
        } catch (InterruptedException e) {
            // manager.foundError(url, "InterruptedException " + e.getMessage());
            manager.workDone();
            return;
        } catch (IllegalArgumentException e) {

            e.printStackTrace();
            manager.foundError(url, "IllegalArgumentException " + e.getMessage());
            manager.workDone();
        } finally {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        }
    }
}

From source file:net.sourceforge.jcctray.model.HTTPCruise.java

private int executeMethod(HttpMethod method, Host host) throws HTTPErrorException {
    try {/*from  w  w  w.  j  ava2 s .c om*/
        int httpStatus = getClient(host).executeMethod(method);
        if (httpStatus != HttpStatus.SC_OK)
            getLog().error("Method failed: " + method.getStatusLine());
        return httpStatus;
    } catch (Exception e) {
        getLog().error(
                "Could not force a build on project, either the webpage is not available, or there was a timeout in connecting to the cruise server.",
                e);
        throw new HTTPErrorException(
                "Could not force a build on project, either the webpage is not available, or there was a timeout in connecting to the cruise server.",
                e);
    }
}