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.gots.server.auth.TempTokenAuthenticationServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Get request parameters
    String applicationName = req.getParameter(APPLICATION_NAME_PARAM);
    String deviceId = req.getParameter(DEVICE_ID_PARAM);
    String deviceDescription = req.getParameter(DEVICE_DESCRIPTION_PARAM);
    String permission = req.getParameter(PERMISSION_PARAM);
    String revokeParam = req.getParameter(REVOKE_PARAM);
    boolean revoke = Boolean.valueOf(revokeParam);

    // If one of the required parameters is null or empty, send an
    // error with the 400 status
    if (!revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId)
            || StringUtils.isEmpty(permission))) {
        log.error(//  ww w .  ja va  2  s.  c o m
                "The following request parameters are mandatory to acquire an authentication token: applicationName, deviceId, permission.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }
    if (revoke && (StringUtils.isEmpty(applicationName) || StringUtils.isEmpty(deviceId))) {
        log.error(
                "The following request parameters are mandatory to revoke an authentication token: applicationName, deviceId.");
        resp.sendError(HttpStatus.SC_BAD_REQUEST);
        return;
    }

    // Decode parameters
    applicationName = URIUtil.decode(applicationName);
    deviceId = URIUtil.decode(deviceId);
    if (!StringUtils.isEmpty(deviceDescription)) {
        deviceDescription = URIUtil.decode(deviceDescription);
    }
    if (!StringUtils.isEmpty(permission)) {
        permission = URIUtil.decode(permission);
    }

    // Get user name from request Principal
    Principal principal = req.getUserPrincipal();
    if (principal == null) {
        resp.sendError(HttpStatus.SC_UNAUTHORIZED);
        return;
    }
    String userName = principal.getName();
    log.error("The principal user is " + userName);
    // Write response
    String response = null;
    TokenAuthenticationService tokenAuthService = Framework.getLocalService(TokenAuthenticationService.class);
    try {
        // Token acquisition: acquire token and write it to the response
        // body
        if (!revoke) {
            response = tokenAuthService.acquireToken(userName, applicationName, deviceId, deviceDescription,
                    permission);
        }
        // Token revocation
        else {
            String token = tokenAuthService.getToken(userName, applicationName, deviceId);
            if (token == null) {
                response = String.format(
                        "No token found for userName %s, applicationName %s and deviceId %s; nothing to do.",
                        userName, applicationName, deviceId);
            } else {
                tokenAuthService.revokeToken(token);
                response = String.format("Token revoked for userName %s, applicationName %s and deviceId %s.",
                        userName, applicationName, deviceId);
            }
        }
        sendTextResponse(resp, response);
    } catch (Exception e) {
        // Should never happen as parameters have already been checked
        resp.sendError(HttpStatus.SC_NOT_FOUND);
    }
}

From source file:org.homeautomation.doormanager.manager.api.DoorManagerManagerService.java

/**
 * This will give link to generated agent
 *
 * @param deviceName name of the device which is to be created
 * @param sketchType name of sketch type
 * @return link to generated agent/*from   w  w w .  j  a v a 2 s. com*/
 */
@Path("manager/device/{sketch_type}/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName,
        @PathParam("sketch_type") String sketchType) {
    try {
        ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
        ResponsePayload responsePayload = new ResponsePayload();
        responsePayload.setStatusCode(HttpStatus.SC_OK);
        responsePayload.setMessageFromServer(
                "Sending Requested sketch by type: " + sketchType + " and id: " + zipFile.getDeviceId() + ".");
        responsePayload.setResponseContent(zipFile.getDeviceId());
        return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
    } catch (IllegalArgumentException ex) {
        return Response.status(HttpStatus.SC_BAD_REQUEST).entity(ex.getMessage()).build();
    } catch (DeviceManagementException ex) {
        log.error("Error occurred while creating device with name " + deviceName + "\n", ex);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    } catch (AccessTokenException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    } catch (DeviceControllerException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    }
}

From source file:org.homeautomation.firealarm.manager.api.ManagerService.java

/**
 * This will give link to generated agent
 *
 * @param deviceName name of the device which is to be created
 * @param sketchType name of sketch type
 * @return link to generated agent/*  www  .  j  av  a2  s  .c om*/
 */
@Path("manager/device/{sketch_type}/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName,
        @PathParam("sketch_type") String sketchType) {

    try {
        ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
        ResponsePayload responsePayload = new ResponsePayload();
        responsePayload.setStatusCode(HttpStatus.SC_OK);
        responsePayload.setMessageFromServer(
                "Sending Requested sketch by type: " + sketchType + " and id: " + zipFile.getDeviceId() + ".");
        responsePayload.setResponseContent(zipFile.getDeviceId());
        return Response.status(HttpStatus.SC_OK).entity(responsePayload).build();
    } catch (IllegalArgumentException ex) {
        return Response.status(HttpStatus.SC_BAD_REQUEST).entity(ex.getMessage()).build();
    } catch (DeviceManagementException ex) {
        log.error("Error occurred while creating device with name " + deviceName + "\n", ex);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    } catch (AccessTokenException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    } catch (DeviceControllerException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    }
}

From source file:org.jetbrains.plugins.github.api.GithubApiUtil.java

private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
    int code = method.getStatusCode();
    switch (code) {
    case HttpStatus.SC_OK:
    case HttpStatus.SC_CREATED:
    case HttpStatus.SC_ACCEPTED:
    case HttpStatus.SC_NO_CONTENT:
        return;/*from w  w  w  .ja va  2 s . co m*/
    case HttpStatus.SC_BAD_REQUEST:
    case HttpStatus.SC_UNAUTHORIZED:
    case HttpStatus.SC_PAYMENT_REQUIRED:
    case HttpStatus.SC_FORBIDDEN:
        throw new GithubAuthenticationException("Request response: " + getErrorMessage(method));
    default:
        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
    }
}

From source file:org.jfrog.bamboo.admin.ArtifactoryConfigServlet.java

/**
 * Requires to be provided with a server ID (param name is serverId).<br> If given with the parameter
 * "deployableRepos=true", it will return the list of deployable repositories for the server with the given ID.<br>
 * If no other parameter is provided, the server configuration of the given ID will be returned.<br> All successful
 * responses are returned in JSON format.
 *///from   www .j a  va 2  s.  c o  m
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String serverIdValue = req.getParameter("serverId");
    if (StringUtils.isBlank(serverIdValue)) {
        resp.sendError(HttpStatus.SC_BAD_REQUEST, "Please provide a server ID.");
        log.error("Unable to retrieve server configuration information. No server ID was provided.");
        return;
    }

    long serverId;
    try {
        serverId = Long.parseLong(serverIdValue);
    } catch (NumberFormatException e) {
        resp.sendError(HttpStatus.SC_BAD_REQUEST, "Please provide a valid long-type server ID.");
        log.error("Unable to retrieve server configuration information. An invalid server ID was provided ("
                + serverIdValue + ").");
        return;
    }

    ServerConfig serverConfig = serverConfigManager.getServerConfigById(serverId);
    if (serverConfig == null) {
        resp.sendError(HttpStatus.SC_NOT_FOUND,
                "Could not find an Artifactory server configuration with the ID " + serverId + ".");
        log.error("Unable to retrieve server configuration. No configuration was found with the ID " + serverId
                + ".");
        return;
    }

    String deployableReposValue = req.getParameter("deployableRepos");
    String resolvingReposValue = req.getParameter("resolvingRepos");
    if (StringUtils.isNotBlank(deployableReposValue) && Boolean.valueOf(deployableReposValue)) {
        List<String> deployableRepoList = serverConfigManager.getDeployableRepos(serverId, req, resp);
        returnJsonObject(resp, deployableRepoList);
    } else if (StringUtils.isNotBlank(resolvingReposValue) && Boolean.valueOf(resolvingReposValue)) {
        List<String> resolvingRepoList = serverConfigManager.getResolvingRepos(serverId, req, resp);
        returnJsonObject(resp, resolvingRepoList);
    } else {
        returnJsonObject(resp, serverConfig);
    }
}

From source file:org.jfrog.bamboo.admin.BuildServlet.java

/**
 * Requires to be provided with a build key (param name is buildKey).<br> Returns the full name of the build with
 * the given key.//ww w  . j  a v a  2s. c om
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String buildKeyValue = req.getParameter(ConstantValues.BUILD_SERVLET_KEY_PARAM);
    if (StringUtils.isBlank(buildKeyValue)) {
        resp.sendError(HttpStatus.SC_BAD_REQUEST, "Please provide a build key.");
        log.error("Unable to retrieve build information. No build key was provided.");
        return;
    }

    Plan plan = planManager.getPlanByKey(buildKeyValue);

    if (plan == null) {
        resp.sendError(HttpStatus.SC_NOT_FOUND, "Could not find plan with the key " + buildKeyValue + ".");
        log.error(
                "Unable to retrieve build information. No plan was found with the key " + buildKeyValue + ".");
        return;
    }

    PrintWriter writer = null;
    try {
        writer = resp.getWriter();
        writer.write(plan.getName());
        writer.flush();
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:org.ldp4j.server.frontend.ServerFrontendITest.java

@Test
@Category({ LDP.class, ExceptionPath.class })
@OperateOnDeployment(DEPLOYMENT)/*from ww  w.jav  a  2  s .co  m*/
public void testUnsupportedCreationPreferences(@ArquillianResource final URL url) throws Exception {
    LOGGER.info("Started {}", testName.getMethodName());
    HELPER.base(url);
    HELPER.setLegacy(false);
    HttpPost post = HELPER.newRequest(MyApplication.ROOT_PERSON_CONTAINER_PATH, HttpPost.class);
    post.setEntity(new StringEntity(TEST_SUITE_BODY, ContentType.create("text/turtle", "UTF-8")));
    String interactionModel = Link.fromUri(InteractionModel.INDIRECT_CONTAINER.asURI()).rel("type").build()
            .toString();
    post.setHeader("Link", interactionModel);
    Metadata response = HELPER.httpRequest(post);
    assertThat(response.status, equalTo(HttpStatus.SC_BAD_REQUEST));
    LOGGER.info("Completed {}", testName.getMethodName());
}

From source file:org.ldp4j.server.frontend.ServerFrontendITest.java

@Test
@Category({ ExceptionPath.class })
@OperateOnDeployment(DEPLOYMENT)//from  w ww. ja v  a  2  s .co m
public void testMixedQueriesNotAllowed(@ArquillianResource final URL url) throws Exception {
    LOGGER.info("Started {}", testName.getMethodName());
    HELPER.base(url);
    HELPER.setLegacy(false);

    HttpGet get = HELPER.newRequest(
            MyApplication.ROOT_PERSON_CONTAINER_PATH
                    + "?ldp:constrainedBy=12312312321&param1=value1&param2=value2&param2=value3&param3",
            HttpGet.class);
    Metadata getResponse = HELPER.httpRequest(get);
    assertThat(getResponse.status, equalTo(HttpStatus.SC_BAD_REQUEST));
    assertThat(getResponse.body, equalTo(
            "Mixed queries not allowed (ldp:constrainedBy=12312312321&param1=value1&param2=value2&param2=value3&param3=)"));
    assertThat(getResponse.contentType, startsWith("text/plain"));
    assertThat(getResponse.language, equalTo(Locale.ENGLISH));
}

From source file:org.ldp4j.server.frontend.ServerFrontendITest.java

@Test
@Category({ ExceptionPath.class })
@OperateOnDeployment(DEPLOYMENT)/*from  w  ww  . ja  va  2 s. c o  m*/
public void testCannotSpecifyMultipleConstraintReports(@ArquillianResource final URL url) throws Exception {
    LOGGER.info("Started {}", testName.getMethodName());
    HELPER.base(url);
    HELPER.setLegacy(false);

    HttpGet get = HELPER.newRequest(MyApplication.ROOT_PERSON_CONTAINER_PATH
            + "?ldp:constrainedBy=12312312321&ldp:constrainedBy=asdasdasd", HttpGet.class);
    Metadata getResponse = HELPER.httpRequest(get);
    assertThat(getResponse.status, equalTo(HttpStatus.SC_BAD_REQUEST));
    assertThat(getResponse.body,
            equalTo("Only one constraint report identifier is allowed (12312312321, asdasdasd)"));
    assertThat(getResponse.contentType, startsWith("text/plain"));
    assertThat(getResponse.language, equalTo(Locale.ENGLISH));
}

From source file:org.ldp4j.server.frontend.ServerFrontendITest.java

@Test
@Category({ ExceptionPath.class })
@OperateOnDeployment(DEPLOYMENT)//from   www .  j  ava2 s  .  c  om
public void testQueryFailure(@ArquillianResource final URL url) throws Exception {
    LOGGER.info("Started {}", testName.getMethodName());
    HELPER.base(url);
    HELPER.setLegacy(false);

    HttpGet get = HELPER.newRequest(
            MyApplication.ROOT_QUERYABLE_RESOURCE_PATH + "?" + QueryableResourceHandler.FAILURE + "=true",
            HttpGet.class);
    Metadata getResponse = HELPER.httpRequest(get);
    assertThat(getResponse.status, equalTo(HttpStatus.SC_BAD_REQUEST));
    assertThat(getResponse.body, notNullValue());
    assertThat(getResponse.contentType, startsWith("text/plain"));
    assertThat(getResponse.language, equalTo(Locale.ENGLISH));
}