Example usage for org.apache.commons.httpclient HttpMethod getStatusCode

List of usage examples for org.apache.commons.httpclient HttpMethod getStatusCode

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getStatusCode.

Prototype

public abstract int getStatusCode();

Source Link

Usage

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * Send the specified request payload to the specified HTTP endpoint using the method specified.
 * @param endpointURL The HTTP endpoint URL.
 * @param request The request payload./*from  w ww . jav a 2  s.  com*/
 * @param method The request method.
 * @return The HTTP response code.
 */
public int sendStringAndGetStatus(String endpointURL, String request, String method) {
    HttpMethod httpMethod = sendStringAndGetMethod(endpointURL, request, method);
    int status = httpMethod.getStatusCode();
    httpMethod.releaseConnection();
    return status;
}

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * POST the specified classpath resource to the specified HTTP endpoint.
 * @param endpointURL The HTTP endpoint URL.
 * @param requestResource The classpath resource to be posted to the endpoint.
 * @return The HTTP status code./*from w w w .jav  a 2s.  c  o m*/
 */
public int postResourceAndGetStatus(String endpointURL, String requestResource) {
    HttpMethod httpMethod = postResourceAndGetMethod(endpointURL, requestResource);
    int status = httpMethod.getStatusCode();
    httpMethod.releaseConnection();
    return status;
}

From source file:org.tuckey.web.filters.urlrewrite.RequestProxy.java

private static void setupResponseHeaders(HttpMethod httpMethod, HttpServletResponse hsResponse) {
    if (log.isInfoEnabled()) {
        log.info("setupResponseHeaders");
        log.info("status text: " + httpMethod.getStatusText());
        log.info("status line: " + httpMethod.getStatusLine());
    }/*from   ww  w.  j a v a 2s. c  om*/

    //filter the headers, which are copied from the proxy response. The http lib handles those itself.
    //Filtered out: the content encoding, the content length and cookies
    for (int i = 0; i < httpMethod.getResponseHeaders().length; i++) {
        Header h = httpMethod.getResponseHeaders()[i];
        if ("content-encoding".equalsIgnoreCase(h.getName())) {
            continue;
        } else if ("content-length".equalsIgnoreCase(h.getName())) {
            continue;
        } else if ("transfer-encoding".equalsIgnoreCase(h.getName())) {
            continue;
        } else if (h.getName().toLowerCase().startsWith("cookie")) {
            //retrieving a cookie which sets the session id will change the calling session: bad! So we skip this header.
            continue;
        } else if (h.getName().toLowerCase().startsWith("set-cookie")) {
            //retrieving a cookie which sets the session id will change the calling session: bad! So we skip this header.
            continue;
        }

        hsResponse.addHeader(h.getName(), h.getValue());
        if (log.isInfoEnabled())
            log.info("setting response parameter:" + h.getName() + ", value: " + h.getValue());
    }
    //fixme what about the response footers? (httpMethod.getResponseFooters())

    if (httpMethod.getStatusCode() != 200) {
        hsResponse.setStatus(httpMethod.getStatusCode());
    }
}

From source file:org.tuleap.mylyn.task.core.internal.client.rest.TuleapRestConnector.java

/**
 * Logs a debug message of the REST request/response.
 *
 * @param method/*from   w  w w .  ja v a 2  s. com*/
 *            The method executed
 * @param bodyReceived
 *            The response body received
 */
private void debugRestCall(HttpMethod method, String bodyReceived) {
    int responseStatus = method.getStatusCode();
    StringBuilder b = new StringBuilder();
    b.append(method.getName());
    b.append(" ").append(method.getPath()); //$NON-NLS-1$
    String qs = method.getQueryString();
    if (qs != null && !qs.isEmpty()) {
        b.append('?').append(method.getQueryString());
    }
    if (method instanceof EntityEnclosingMethod) {
        RequestEntity requestEntity = ((EntityEnclosingMethod) method).getRequestEntity();
        String body = ""; //$NON-NLS-1$
        if (requestEntity.isRepeatable()) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            try {
                requestEntity.writeRequest(os);
                body = os.toString("UTF-8"); //$NON-NLS-1$
            } catch (UnsupportedEncodingException e) {
                // Nothing to do
            } catch (IOException e) {
                // Nothing to do
            }
        }
        b.append("\nbody:\n").append(body.replaceAll(//$NON-NLS-1$
                "\"password\" *: *\".*\"", "\"password\":\"(hidden in debug)\"")); //$NON-NLS-1$ //$NON-NLS-2$
    }
    b.append("\n__________\nresponse:\n"); //$NON-NLS-1$
    b.append(method.getStatusLine()).append("\n"); //$NON-NLS-1$
    b.append("body:\n"); //$NON-NLS-1$
    b.append(bodyReceived);
    int status = IStatus.INFO;
    if (responseStatus != HttpURLConnection.HTTP_OK) {
        status = IStatus.ERROR;
    }
    this.logger.log(new Status(status, TuleapCoreActivator.PLUGIN_ID, b.toString()));
}

From source file:org.wso2.carbon.mashup.javascript.hostobjects.pooledhttpclient.HttpCommand.java

private SimpleHttpResponse toResponse(HttpMethod method) {
    SimpleHttpResponse response;//  ww w. jav a2 s  .  com
    Header[] headers = method.getResponseHeaders();
    String headersString = "";
    for (Header header : headers) {
        headersString += header.toString();
    }
    try {
        response = new SimpleHttpResponse(method.getStatusCode(), method.getStatusText(), headersString,
                method.getResponseBodyAsString());
    } catch (Exception e) {
        throw new RuntimeException("", e);
    }
    return response;
}

From source file:org.xwiki.test.rest.framework.AbstractHttpTest.java

protected String getHttpMethodInfo(HttpMethod method) throws Exception {
    return String.format("\nName: %s\nURI: %s\nStatus code: %d\nStatus text: %s", method.getName(),
            method.getURI(), method.getStatusCode(), method.getStatusText());
}

From source file:org.xwiki.test.storage.AttachmentTest.java

/**
 * Tests that XWIKI-5405 remains fixed./*from   ww w. ja  va  2 s  . c o m*/
 * This test proves that when an attachment is saved using Document.addAttachment and
 * then Document.save() the attachment is actually persisted to the database.
 */
@Test
public void testDocumentAddAttachment() throws Exception {
    final String test = "{{groovy}}\n"
            // First the attacher.
            + "doc.addAttachment('" + FILENAME + "', '" + ATTACHMENT_CONTENT + "'.getBytes('UTF-8'));\n"
            + "doc.saveAsAuthor();"
            // then the validator.
            + "println(xwiki.getDocument(doc.getDocumentReference()).getAttachment('" + FILENAME
            + "').getContentAsString());" + "{{/groovy}}";

    // Delete the document if it exists.
    doPostAsAdmin("Test", "Attachment", null, "delete", "confirm=1", null);

    // Create a document.
    doPostAsAdmin("Test", "Attachment", null, "save", null, new HashMap<String, String>() {
        {
            put("content", test);
        }
    });

    HttpMethod ret = null;

    // Test getAttachment()
    ret = doPostAsAdmin("Test", "Attachment", null, "view", "xpage=plain", null);
    Assert.assertEquals("<p>" + ATTACHMENT_CONTENT + "</p>", ret.getResponseBodyAsString());

    // Test downloadAction.
    ret = doPostAsAdmin("Test", "Attachment", FILENAME, "download", null, null);
    Assert.assertEquals(ATTACHMENT_CONTENT, new String(ret.getResponseBody(), "UTF-8"));
    Assert.assertEquals(200, ret.getStatusCode());

    // Make sure there is exactly 1 version of this attachment.
    ret = doPostAsAdmin("Test", "Attachment", null, "preview", "xpage=plain", new HashMap<String, String>() {
        {
            put("content",
                    "{{velocity}}$doc.getAttachment('" + FILENAME + "').getVersions().size(){{/velocity}}");
        }
    });
    Assert.assertEquals("<p>1</p>", ret.getResponseBodyAsString());

    // Make sure that version contains the correct content.
    ret = doPostAsAdmin("Test", "Attachment", null, "preview", "xpage=plain", new HashMap<String, String>() {
        {
            put("content", "{{velocity}}$doc.getAttachment('" + FILENAME
                    + "').getAttachmentRevision('1.1').getContentAsString(){{/velocity}}");
        }
    });
    Assert.assertEquals("<p>" + ATTACHMENT_CONTENT + "</p>", ret.getResponseBodyAsString());
}

From source file:org.xwiki.test.storage.AttachmentTest.java

@Test
public void testRollbackAfterNewAttachment() throws Exception {
    final String spaceName = "Test";
    final String pageName = "testRollbackAfterNewAttachment";

    final String attachURL = this.getAddressPrefix() + "download/" + spaceName + "/" + pageName + "/"
            + FILENAME;//from   www.j ava  2 s. c  o m

    // Delete the document if it exists.
    doPostAsAdmin(spaceName, pageName, null, "delete", "?confirm=1", null);

    // Create a document.
    doPostAsAdmin(spaceName, pageName, null, "save", null, null);

    HttpMethod ret;

    // Upload the attachment
    ret = doUploadAsAdmin(spaceName, pageName, new HashMap<String, byte[]>() {
        {
            put(FILENAME, ATTACHMENT_CONTENT.getBytes());
        }
    });

    // Make sure it's there.
    Assert.assertEquals(ATTACHMENT_CONTENT, StoreTestUtils.getPageAsString(attachURL));

    // Do a rollback.
    doPostAsAdmin(spaceName, pageName, null, "rollback", "?rev=1.1&confirm=1", null);

    // Make sure it's nolonger there.
    ret = doPostAsAdmin(spaceName, pageName, FILENAME, "download", null, null);
    Assert.assertFalse(ATTACHMENT_CONTENT.equals(new String(ret.getResponseBody(), "UTF-8")));
    Assert.assertEquals(404, ret.getStatusCode());
}

From source file:org.xwiki.test.storage.DocumentTest.java

/**
 * check that http://jira.xwiki.org/browse/XWIKI-7943 has not regressed.
 * Jetty prevents saving of large documents unless you specify max form size on the command line.
 *
 * @since 4.1.1/*from   w  ww  . ja v  a 2 s .c  o m*/
 * @since 4.0.1
 */
@Test
public void testSaveOfThreeHundredKilobyteDocument() throws Exception {
    final String content = RandomStringUtils.randomAlphanumeric(300000);
    final HttpMethod ret = this.doPostAsAdmin(this.spaceName, this.pageName, null, "save", null,
            new HashMap<String, String>() {
                {
                    put("content", content);
                }
            });
    // save forwards the user to view, if it's too big, jetty gives you a 500
    Assert.assertEquals(302, ret.getStatusCode());
}

From source file:org.yccheok.jstock.gui.UtilsRef.java

public static String getResponseBodyAsStringBasedOnProxyAuthOption(String request) {
    ///org.yccheok.jstock.engine.Utils.setHttpClientProxyFromSystemProperties(httpClient);
    if (!mytest)//w ww. j  a v a2  s  . c o  m
        org.yccheok.jstock.gui.UtilsRef.setHttpClientProxyCredentialsFromJStockOptions(httpClient);

    final HttpMethod method = new GetMethod(request);
    ///final JStockOptions jStockOptions = MainFrame.getInstance().getJStockOptions();
    String respond = null;
    try {
        if (true/*!mytest&&jStockOptions.isProxyAuthEnabled()*/) {
            method.setFollowRedirects(false);
            httpClient.executeMethod(method);

            int statuscode = method.getStatusCode();
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
                //Make new Request with new URL
                Header header = method.getResponseHeader("location");
                HttpMethod RedirectMethod = new GetMethod(header.getValue());
                // I assume it is OK to release method for twice. (The second
                // release will happen in finally block). We shouldn't have an
                // unreleased method, before executing another new method.
                method.releaseConnection();
                // Do RedirectMethod within try-catch-finally, so that we can have a
                // exception free way to release RedirectMethod connection.
                // #2836422
                try {
                    httpClient.executeMethod(RedirectMethod);
                    respond = RedirectMethod.getResponseBodyAsString();
                } catch (HttpException exp) {
                    log.error(null, exp);
                    return null;
                } catch (IOException exp) {
                    log.error(null, exp);
                    return null;
                } finally {
                    RedirectMethod.releaseConnection();
                }
            } else {
                respond = method.getResponseBodyAsString();
            } // if statuscode = Redirect
        } else {
            httpClient.executeMethod(method);
            respond = method.getResponseBodyAsString();
        } //  if jStockOptions.isProxyAuthEnabled()
    } catch (HttpException exp) {
        log.error(null, exp);
        return null;
    } catch (IOException exp) {
        log.error(null, exp);
        return null;
    } finally {
        method.releaseConnection();
    }
    return respond;
}