Example usage for org.springframework.http HttpStatus BAD_REQUEST

List of usage examples for org.springframework.http HttpStatus BAD_REQUEST

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus BAD_REQUEST.

Prototype

HttpStatus BAD_REQUEST

To view the source code for org.springframework.http HttpStatus BAD_REQUEST.

Click Source Link

Document

400 Bad Request .

Usage

From source file:org.apigw.authserver.web.admin.DefaultAdminExceptionHandler.java

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody/*from   w w w .  j a  v a  2  s  .  com*/
public ValidationErrorDTO processValidationError(MethodArgumentNotValidException e) {
    log.debug("Handling form validation error");

    BindingResult result = e.getBindingResult();
    List<FieldError> fieldErrors = result.getFieldErrors();

    return processFieldErrors(fieldErrors);
}

From source file:org.mitre.openid.connect.web.BlacklistAPI.java

/**
 * Create a new blacklisted site/* w  w w . j a  va  2  s .  c  o  m*/
 * @param jsonString
 * @param m
 * @param p
 * @return
 */
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String addNewBlacklistedSite(@RequestBody String jsonString, ModelMap m, Principal p) {

    JsonObject json;

    BlacklistedSite blacklist = null;

    try {

        json = parser.parse(jsonString).getAsJsonObject();
        blacklist = gson.fromJson(json, BlacklistedSite.class);
        BlacklistedSite newBlacklist = blacklistService.saveNew(blacklist);
        m.put(JsonEntityView.ENTITY, newBlacklist);

    } catch (JsonSyntaxException e) {
        logger.error("addNewBlacklistedSite failed due to JsonSyntaxException: ", e);
        m.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        m.put(JsonErrorView.ERROR_MESSAGE,
                "Could not save new blacklisted site. The server encountered a JSON syntax exception. Contact a system administrator for assistance.");
        return JsonErrorView.VIEWNAME;
    } catch (IllegalStateException e) {
        logger.error("addNewBlacklistedSite failed due to IllegalStateException", e);
        m.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST);
        m.put(JsonErrorView.ERROR_MESSAGE,
                "Could not save new blacklisted site. The server encountered an IllegalStateException. Refresh and try again - if the problem persists, contact a system administrator for assistance.");
        return JsonErrorView.VIEWNAME;
    }

    return JsonEntityView.VIEWNAME;

}

From source file:$.TaskRestFT.java

@Test
    public void invalidInput() {

        // create
        Task titleBlankTask = new Task();
        try {/*  w  w  w .  jav a2 s  .com*/
            restTemplate.postForLocation(resourceUrl, titleBlankTask);
            fail("Create should fail while title is blank");
        } catch (HttpStatusCodeException e) {
            assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
            Map messages = jsonMapper.fromJson(e.getResponseBodyAsString(), Map.class);
            assertThat(messages).hasSize(1);
            assertThat(messages.get("title")).isIn("may not be empty", "?");
        }

        // update
        titleBlankTask.setId(1L);
        try {
            restTemplate.put(resourceUrl + "/1", titleBlankTask);
            fail("Update should fail while title is blank");
        } catch (HttpStatusCodeException e) {
            assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
            Map messages = jsonMapper.fromJson(e.getResponseBodyAsString(), Map.class);
            assertThat(messages).hasSize(1);
            assertThat(messages.get("title")).isIn("may not be empty", "?");
        }
    }

From source file:org.openwms.core.http.AbstractWebController.java

/**
 * All general exceptions thrown by services are caught here and translated into http conform responses with a status code {@code 500
 * Internal Server Error}./*from   w  w  w . j a  v  a  2 s .com*/
 *
 * @param ex The exception occurred
 * @return A response object wraps the server result
 */
@ExceptionHandler(Exception.class)
public ResponseEntity<Response<Serializable>> handleException(Exception ex) {
    EXC_LOGGER.error("[P] Presentation Layer Exception: " + ex.getLocalizedMessage(), ex);
    if (ex instanceof BehaviorAwareException) {
        BehaviorAwareException bae = (BehaviorAwareException) ex;
        return bae.toResponse(bae.getData());
    }
    if (ex instanceof BusinessRuntimeException) {
        BusinessRuntimeException bre = (BusinessRuntimeException) ex;
        return new ResponseEntity<>(new Response<>(ex.getMessage(), bre.getMsgKey(),
                HttpStatus.INTERNAL_SERVER_ERROR.toString(), new String[] { bre.getMsgKey() }),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
    if (ex instanceof HttpBusinessException) {
        HttpBusinessException e = (HttpBusinessException) ex;
        return new ResponseEntity<>(new Response<>(ex.getMessage(), e.getHttpStatus().toString()),
                e.getHttpStatus());
    }
    if (ex instanceof ValidationException) {
        return new ResponseEntity<>(new Response<>(ex.getMessage(), HttpStatus.BAD_REQUEST.toString()),
                HttpStatus.BAD_REQUEST);
    }
    if (ex instanceof TechnicalRuntimeException) {
        TechnicalRuntimeException be = (TechnicalRuntimeException) ex;
        return new ResponseEntity<>(new Response<>(ex.getMessage(), HttpStatus.BAD_GATEWAY.toString()),
                HttpStatus.BAD_GATEWAY);
    }
    return new ResponseEntity<>(new Response<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.toString()),
            HttpStatus.INTERNAL_SERVER_ERROR);
}

From source file:org.osiam.security.controller.TokenController.java

@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody//w w w.  j  av a2  s. c  o m
public AuthenticationError handleClientAuthenticationException(InvalidTokenException ex,
        HttpServletRequest request) {
    return new AuthenticationError("invalid_token", ex.getMessage());
}

From source file:com.envision.envservice.rest.EvaluationResource.java

/**
 * ?/*from  w  w  w . ja  v  a  2 s.  c  o m*/
 * 
 * */
@POST
@Path("/addNullEvaluationForUser")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addNullEvaluationForUser(EvaluationBo evaluationBo) throws Exception {
    HttpStatus status = HttpStatus.CREATED;
    String response = StringUtils.EMPTY;
    if (!checkParamForUser(evaluationBo)) {
        status = HttpStatus.BAD_REQUEST;
        response = FailResult.toJson(Code.PARAM_ERROR, "?");
    } else {
        response = evaluationService.addNullEvaluationForUser(evaluationBo).toJSONString();
    }
    return Response.status(status.value()).entity(response).build();
}

From source file:org.syncope.core.rest.controller.ResourceController.java

@PreAuthorize("hasRole('RESOURCE_CREATE')")
@RequestMapping(method = RequestMethod.POST, value = "/create")
public ResourceTO create(final HttpServletResponse response, final @RequestBody ResourceTO resourceTO)
        throws SyncopeClientCompositeErrorException, NotFoundException {

    LOG.debug("Resource creation: {}", resourceTO);

    if (resourceTO == null) {
        LOG.error("Missing resource");

        throw new NotFoundException("Missing resource");
    }//from   w  w w.jav a2  s  .  co m

    SyncopeClientCompositeErrorException scce = new SyncopeClientCompositeErrorException(
            HttpStatus.BAD_REQUEST);

    LOG.debug("Verify that resource doesn't exist yet");
    if (resourceTO.getName() != null && resourceDAO.find(resourceTO.getName()) != null) {
        SyncopeClientException ex = new SyncopeClientException(
                SyncopeClientExceptionType.DataIntegrityViolation);

        ex.addElement("Existing " + resourceTO.getName());
        scce.addException(ex);

        throw scce;
    }

    ExternalResource resource = binder.create(resourceTO);
    if (resource == null) {
        LOG.error("Resource creation failed");

        SyncopeClientException ex = new SyncopeClientException(SyncopeClientExceptionType.Unknown);

        scce.addException(ex);

        throw scce;
    }

    resource = resourceDAO.save(resource);

    response.setStatus(HttpServletResponse.SC_CREATED);
    return binder.getResourceTO(resource);
}

From source file:org.magnum.mobilecloud.video.AssignmentController.java

@RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH + "/{id}/like", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<Void> likeVideo(@PathVariable("id") long id, Principal p) {
    if (videos.exists(id)) {
        Video video = videos.findOne(id);
        if (video.userAlreadyLikes(p.getName())) {
            return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST);
        } else {/*w ww  .  j a va2  s.  co  m*/
            video.addUserLike(p.getName());
            videos.save(video);
            return new ResponseEntity<Void>(HttpStatus.OK);
        }
    } else {
        return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
    }
}

From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandlerTest.java

/**
 * Tests {@link ApiResponseErrorHandler#hasError} in the case where the response has an HTTP status code in the client
 * error (4xx) series, specifically HTTP 400 Bad Request.
 * /* w  w  w . j a  v a 2 s.com*/
 * @throws Exception If an unexpected error occurs.
 */
@Test
public void testHasErrorWhenHttpStatusBadRequest() throws Exception {
    byte[] body = null;
    ClientHttpResponse response = new MockClientHttpResponse(body, HttpStatus.BAD_REQUEST);
    assertThat(this.errorHandler.hasError(response), CoreMatchers.is(true));
}