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

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

Introduction

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

Prototype

int SC_BAD_REQUEST

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

Click Source Link

Document

<tt>400 Bad Request</tt> (HTTP/1.1 - RFC 2616)

Usage

From source file:org.projectforge.web.calendar.CalendarFeed.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    PFUserDO user = null;//from  w  w  w . j a  va  2  s . com
    String logMessage = null;
    try {
        MDC.put("ip", req.getRemoteAddr());
        MDC.put("session", req.getSession().getId());
        if (StringUtils.isBlank(req.getParameter("user")) || StringUtils.isBlank(req.getParameter("q"))) {
            resp.sendError(HttpStatus.SC_BAD_REQUEST);
            log.error("Bad request, parameters user and q not given. Query string is: " + req.getQueryString());
            return;
        }
        final String encryptedParams = req.getParameter("q");
        final Integer userId = NumberHelper.parseInteger(req.getParameter("user"));
        if (userId == null) {
            log.error("Bad request, parameter user is not an integer: " + req.getQueryString());
            return;
        }
        final Registry registry = Registry.instance();
        user = registry.getUserGroupCache().getUser(userId);
        if (user == null) {
            log.error("Bad request, user not found: " + req.getQueryString());
            return;
        }
        PFUserContext.setUser(user);
        MDC.put("user", user.getUsername());
        final String decryptedParams = registry.getDao(UserDao.class).decrypt(userId, encryptedParams);
        if (decryptedParams == null) {
            log.error(
                    "Bad request, can't decrypt parameter q (may-be the user's authentication token was changed): "
                            + req.getQueryString());
            return;
        }
        final Map<String, String> params = StringHelper.getKeyValues(decryptedParams, "&");
        final Calendar calendar = createCal(params, userId, params.get("token"),
                params.get(PARAM_NAME_TIMESHEET_USER));
        final StringBuffer buf = new StringBuffer();
        boolean first = true;
        for (final Map.Entry<String, String> entry : params.entrySet()) {
            if ("token".equals(entry.getKey()) == true) {
                continue;
            }
            first = StringHelper.append(buf, first, entry.getKey(), ", ");
            buf.append("=").append(entry.getValue());
        }
        logMessage = buf.toString();
        log.info("Getting calendar entries for: " + logMessage);

        if (calendar == null) {
            resp.sendError(HttpStatus.SC_BAD_REQUEST);
            log.error("Bad request, can't find calendar.");
            return;
        }

        resp.setContentType("text/calendar");
        final CalendarOutputter output = new CalendarOutputter(false);
        try {
            output.output(calendar, resp.getOutputStream());
        } catch (final ValidationException ex) {
            ex.printStackTrace();
        }
    } finally {
        log.info("Finished request: " + logMessage);
        PFUserContext.setUser(null);
        MDC.remove("ip");
        MDC.remove("session");
        if (user != null) {
            MDC.remove("user");
        }
    }
}

From source file:org.red5.server.net.servlet.AMFTunnelServlet.java

/**
 * Redirect to HTTP port./*from w  ww .j a  v  a  2 s .  co m*/
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    PostMethod get = new PostMethod("http://localhost:8080/gateway");

    try {
        // copy all the headers
        // Enumeration headerNames = req.getHeaderNames();
        // while (headerNames.hasMoreElements()) {
        // String headerName = (String) headerNames.nextElement();
        // logger.debug("Adding received header to tunnel request: "
        // + headerName);
        // get.addRequestHeader(headerName, req.getHeader(headerName));
        // }
        // Enumeration parameterNames = req.getParameterNames();
        // while (parameterNames.hasMoreElements()) {
        // String parameterName = (String) parameterNames.nextElement();
        // logger.debug("Adding received parameter to tunnel request: "
        // + parameterName);
        // get.getParams().setParameter(parameterName,
        // req.getParameter(parameterName));
        // }
        // Enumeration attributeNames = req.getAttributeNames();
        // while (attributeNames.hasMoreElements()) {
        // String attributeName = (String) attributeNames.nextElement();
        // logger.debug("Adding received attribute to tunnel request: "
        // + attributeName);
        // }

        String path = req.getContextPath();
        if (path == null) {
            path = "";
        }
        // System.out.println("Path: " + path);
        if (req.getPathInfo() != null) {
            path += req.getPathInfo();
        }
        // System.out.println("Path: " + path);

        int reqContentLength = req.getContentLength();
        if (reqContentLength > 0) {
            // System.out.println("Request content length: " +
            // reqContentLength);

            ByteBuffer reqBuffer = ByteBuffer.allocate(reqContentLength);
            ServletUtils.copy(req.getInputStream(), reqBuffer.asOutputStream());
            reqBuffer.flip();
            get.setRequestEntity(new InputStreamRequestEntity(reqBuffer.asInputStream(), reqContentLength,
                    "application/x-amf"));
            // get.setPath(path);
            get.addRequestHeader("Tunnel-request", path);

            client.executeMethod(get);
            // System.out.println("Response code: " + get.getStatusCode());

            if (get.getStatusCode() == HttpStatus.SC_OK) {
                resp.setContentType("application/x-amf");
                int responseLength = ((Long) get.getResponseContentLength()).intValue();
                ByteBuffer respBuffer = ByteBuffer.allocate(responseLength);
                ServletUtils.copy(get.getResponseBodyAsStream(), respBuffer.asOutputStream());
                respBuffer.flip();
                ServletUtils.copy(respBuffer.asInputStream(), resp.getOutputStream());
                resp.flushBuffer();
            } else {
                resp.sendError(get.getStatusCode());
            }

        } else {
            resp.sendError(HttpStatus.SC_BAD_REQUEST);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        get.releaseConnection();
    }
}

From source file:org.sakaiproject.nakamura.grouper.changelog.util.NakamuraHttpUtils.java

/**
 * Prepare an HTTP request to Sakai OAE and parse the response (if JSON).
 * @param client an {@link HttpClient} to execute the request.
 * @param method an HTTP method to send//from  www.ja va 2 s. co m
 * @return a JSONObject of the response if the request returns JSON
 * @throws GroupModificationException if there was an error updating the group information.
 */
public static JSONObject http(HttpClient client, HttpMethod method) throws GroupModificationException {

    method.setRequestHeader("User-Agent", HTTP_USER_AGENT);
    method.setRequestHeader("Referer", HTTP_REFERER);

    String errorMessage = null;
    String responseString = null;
    JSONObject responseJSON = null;

    boolean isJSONRequest = !method.getPath().toString().endsWith(".html");

    if (log.isDebugEnabled() && method instanceof PostMethod) {
        log.debug(method.getName() + " " + method.getPath() + " params:");
        for (NameValuePair nvp : ((PostMethod) method).getParameters()) {
            log.debug(nvp.getName() + " = " + nvp.getValue());
        }
    }

    int responseCode = -1;
    try {
        responseCode = client.executeMethod(method);
        responseString = StringUtils.trimToNull(IOUtils.toString(method.getResponseBodyAsStream()));

        if (isJSONRequest) {
            responseJSON = parseJSONResponse(responseString);
        }

        if (log.isDebugEnabled()) {
            log.debug(responseCode + " " + method.getName() + " " + method.getPath());
        }
        if (log.isTraceEnabled()) {
            log.trace("reponse: " + responseString);
        }

        switch (responseCode) {

        case HttpStatus.SC_OK: // 200
        case HttpStatus.SC_CREATED: // 201
            break;
        case HttpStatus.SC_BAD_REQUEST: // 400
        case HttpStatus.SC_UNAUTHORIZED: // 401
        case HttpStatus.SC_NOT_FOUND: // 404
        case HttpStatus.SC_INTERNAL_SERVER_ERROR: // 500
            if (isJSONRequest && responseJSON != null) {
                errorMessage = responseJSON.getString("status.message");
            }
            if (errorMessage == null) {
                errorMessage = "Empty " + responseCode + " error. Check the logs on the Sakai OAE server.";
            }
            break;
        default:
            errorMessage = "Unknown HTTP response " + responseCode;
            break;
        }
    } catch (Exception e) {
        errorMessage = "An exception occurred communicatingSakai OAE. " + e.toString();
    } finally {
        method.releaseConnection();
    }

    if (errorMessage != null) {
        log.error(errorMessage);
        errorToException(responseCode, errorMessage);
    }
    return responseJSON;
}

From source file:org.sonatype.nexus.integrationtests.nexus167.Nexus167ReleaseToSnapshotIT.java

@Test
public void deployUsingRest() throws HttpException, Exception {

    Gav gav = new Gav(this.getTestId(), "uploadWithGav", "1.0.0", null, "xml", 0, new Date().getTime(),
            "Simple Test Artifact", false, null, false, null);

    // file to deploy
    File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension());

    // the Restlet Client does not support multipart forms: http://restlet.tigris.org/issues/show_bug.cgi?id=71

    // url to upload to
    String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content";

    // the method we are calling
    PostMethod filePost = new PostMethod(uploadURL);
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    int status = getDeployUtils().deployUsingGavWithRest(uploadURL, TEST_SNAPSHOT_REPO, gav, fileToDeploy);

    if (status != HttpStatus.SC_BAD_REQUEST) {
        Assert.fail("Upload attempt should have returned a 400, it returned:  " + status);
    }/*  ww  w .  j a v a 2  s .com*/

    boolean fileWasUploaded = true;
    try {
        // download it
        downloadArtifact(gav, "./target/downloaded-jars");
    } catch (FileNotFoundException e) {
        fileWasUploaded = false;
    }

    Assert.assertFalse("The file was uploaded and it should not have been.", fileWasUploaded);
}

From source file:org.sonatype.nexus.integrationtests.nexus167.Nexus167ReleaseToSnapshotIT.java

@Test
public void deploywithPomUsingRest() throws HttpException, Exception {

    Gav gav = new Gav(this.getTestId(), "uploadWithPom", "1.0.0", null, "xml", 0, new Date().getTime(),
            "Simple Test Artifact", false, null, false, null);

    // file to deploy
    File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension());

    File pomFile = this.getTestFile("pom.xml");

    // the Restlet Client does not support multipart forms: http://restlet.tigris.org/issues/show_bug.cgi?id=71

    // url to upload to
    String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content";

    int status = getDeployUtils().deployUsingPomWithRest(uploadURL, TEST_SNAPSHOT_REPO, fileToDeploy, pomFile,
            null, null);/*w  w w . j  a  va 2s.  co m*/

    if (status != HttpStatus.SC_BAD_REQUEST) {
        Assert.fail("Upload attempt should have returned a 400, it returned:  " + status);
    }

    boolean fileWasUploaded = true;
    try {
        // download it
        downloadArtifact(gav, "./target/downloaded-jars");
    } catch (FileNotFoundException e) {
        fileWasUploaded = false;
    }

    Assert.assertFalse("The file was uploaded and it should not have been.", fileWasUploaded);
}

From source file:org.sonatype.nexus.integrationtests.nexus168.Nexus168SnapshotToReleaseIT.java

@Test
public void deployUsingRest() throws Exception {

    Gav gav = new Gav(this.getTestId(), "uploadWithGav", "1.0.0-SNAPSHOT", null, "xml", 0, new Date().getTime(),
            "Simple Test Artifact", false, null, false, null);

    // file to deploy
    File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension());

    // the Restlet Client does not support multipart forms: http://restlet.tigris.org/issues/show_bug.cgi?id=71

    // url to upload to
    String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content";

    // the method we are calling
    PostMethod filePost = new PostMethod(uploadURL);
    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    int status = getDeployUtils().deployUsingGavWithRest(uploadURL, TEST_RELEASE_REPO, gav, fileToDeploy);

    if (status != HttpStatus.SC_BAD_REQUEST) {
        Assert.fail("Snapshot repositories do not allow manual file upload: " + status);
    }/*from   w  ww .  j ava2  s.  c om*/

    boolean fileWasUploaded = true;
    try {
        // download it
        downloadArtifact(gav, "./target/downloaded-jars");
    } catch (FileNotFoundException e) {
        fileWasUploaded = false;
    }

    Assert.assertFalse("The file was uploaded and it should not have been.", fileWasUploaded);
}

From source file:org.sonatype.nexus.integrationtests.nexus168.Nexus168SnapshotToReleaseIT.java

@Test
public void deploywithPomUsingRest() throws Exception {

    Gav gav = new Gav(this.getTestId(), "uploadWithPom", "1.0.0-SNAPSHOT", null, "xml", 0, new Date().getTime(),
            "Simple Test Artifact", false, null, false, null);

    // file to deploy
    File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension());

    File pomFile = this.getTestFile("pom.xml");

    // the Restlet Client does not support multipart forms: http://restlet.tigris.org/issues/show_bug.cgi?id=71

    // url to upload to
    String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content";

    int status = getDeployUtils().deployUsingPomWithRest(uploadURL, TEST_RELEASE_REPO, fileToDeploy, pomFile,
            null, null);//from w w w. java 2 s.  c  om

    if (status != HttpStatus.SC_BAD_REQUEST) {
        Assert.fail("Upload attempt should have returned a 400, it returned:  " + status);
    }

    boolean fileWasUploaded = true;
    try {
        // download it
        downloadArtifact(gav, "./target/downloaded-jars");
    } catch (FileNotFoundException e) {
        fileWasUploaded = false;
    }

    Assert.assertFalse("The file was uploaded and it should not have been.", fileWasUploaded);

}

From source file:org.sonatype.nexus.integrationtests.nexus259.Nexus259SnapshotDeployIT.java

@Test
public void deployUsingRest() throws Exception {

    Gav gav = new Gav(this.getTestId(), "uploadWithGav", "1.0.0-SNAPSHOT", null, "xml", 0, new Date().getTime(),
            "Simple Test Artifact", false, null, false, null);

    // file to deploy
    File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension());

    // the Restlet Client does not support multipart forms: http://restlet.tigris.org/issues/show_bug.cgi?id=71

    // url to upload to
    String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content";

    int status = getDeployUtils().deployUsingGavWithRest(uploadURL, TEST_SNAPSHOT_REPO, gav, fileToDeploy);

    if (status != HttpStatus.SC_BAD_REQUEST) {
        Assert.fail("Snapshot repositories do not allow manual file upload: " + status);
    }/* w  w w .j ava2 s  .  c  om*/

    boolean fileWasUploaded = true;
    try {
        // download it
        downloadArtifact(gav, "./target/downloaded-jars");
    } catch (FileNotFoundException e) {
        fileWasUploaded = false;
    }

    Assert.assertFalse("The file was uploaded and it should not have been.", fileWasUploaded);

}

From source file:org.sonatype.nexus.integrationtests.nexus259.Nexus259SnapshotDeployIT.java

@Test
public void deploywithPomUsingRest() throws Exception {

    Gav gav = new Gav(this.getTestId(), "uploadWithGav", "1.0.0-SNAPSHOT", null, "xml", 0, new Date().getTime(),
            "Simple Test Artifact", false, null, false, null);

    // file to deploy
    File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension());

    File pomFile = this.getTestFile("pom.xml");

    // the Restlet Client does not support multipart forms: http://restlet.tigris.org/issues/show_bug.cgi?id=71

    // url to upload to
    String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content";

    int status = getDeployUtils().deployUsingPomWithRest(uploadURL, TEST_SNAPSHOT_REPO, fileToDeploy, pomFile,
            null, null);//from   w w  w .ja va  2  s.  c o m

    if (status != HttpStatus.SC_BAD_REQUEST) {
        Assert.fail("Snapshot repositories do not allow manual file upload: " + status);
    }

    boolean fileWasUploaded = true;
    try {
        // download it
        downloadArtifact(gav, "./target/downloaded-jars");
    } catch (FileNotFoundException e) {
        fileWasUploaded = false;
    }

    Assert.assertFalse("The file was uploaded and it should not have been.", fileWasUploaded);
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

@Override
protected boolean checkRemoteAvailability(long newerThen, ProxyRepository repository,
        ResourceStoreRequest request, boolean isStrict) throws RemoteStorageException {
    URL remoteURL = getAbsoluteUrlFromBase(repository, request);

    HttpMethodBase method = new HeadMethod(remoteURL.toString());

    int response = HttpStatus.SC_BAD_REQUEST;

    // artifactory hack, it pukes on HEAD so we will try with GET if HEAD fails
    boolean doGet = false;

    try {//from  w  ww  . j av  a 2s  . c o  m
        response = executeMethod(repository, request, method, remoteURL);
    } catch (RemoteStorageException e) {
        // If HEAD failed, attempt a GET. Some repos may not support HEAD method
        doGet = true;

        getLogger().debug("HEAD method failed, will attempt GET.  Exception: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();

        // HEAD returned error, but not exception, try GET before failing
        if (!doGet && response != HttpStatus.SC_OK) {
            doGet = true;

            getLogger().debug("HEAD method failed, will attempt GET.  Status: " + response);
        }
    }

    if (doGet) {
        // create a GET
        method = new GetMethod(remoteURL.toString());

        try {
            // execute it
            response = executeMethod(repository, request, method, remoteURL);
        } finally {
            // and release it immediately
            method.releaseConnection();
        }
    }

    // if we are not strict and remote is S3
    if (!isStrict && isRemotePeerAmazonS3Storage(repository)) {
        // if we are relaxed, we will accept any HTTP response code below 500. This means anyway the HTTP
        // transaction succeeded. This method was never really detecting that the remoteUrl really denotes a root of
        // repository (how could we do that?)
        // this "relaxed" check will help us to "pass" S3 remote storage.
        return response >= HttpStatus.SC_OK && response <= HttpStatus.SC_INTERNAL_SERVER_ERROR;
    } else {
        // non relaxed check is strict, and will select only the OK response
        if (response == HttpStatus.SC_OK) {
            // we have it
            // we have newer if this below is true
            return makeDateFromHeader(method.getResponseHeader("last-modified")) > newerThen;
        } else if ((response >= HttpStatus.SC_MULTIPLE_CHOICES && response < HttpStatus.SC_BAD_REQUEST)
                || response == HttpStatus.SC_NOT_FOUND) {
            return false;
        } else {
            throw new RemoteStorageException("Unexpected response code while executing " + method.getName()
                    + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                    + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString()
                    + "\"]. Expected: \"SUCCESS (200)\". Received: " + response + " : "
                    + HttpStatus.getStatusText(response));
        }
    }
}