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:de.sainth.recipe.backend.rest.controller.UnitController.java

@Secured("ROLE_ADMIN")
@RequestMapping(value = "{shortname}", method = RequestMethod.PUT)
HttpEntity<Unit> update(@PathVariable("shortname") String shortname, @Valid @RequestBody Unit unit) {
    if (shortname.equals(unit.getShortname())) {
        if (repository.findOne(unit.getShortname()) != null) {
            repository.save(unit);/*from   w  w  w  .  ja v  a2  s  .  c  om*/
            return new ResponseEntity<>(unit, HttpStatus.OK);
        }
    }
    return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}

From source file:alfio.controller.api.admin.UtilsApiController.java

@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<String> handleMissingServletRequestParameterException(Exception e) {
    log.warn("missing parameters", e);
    return new ResponseEntity<>("missing parameters", HttpStatus.BAD_REQUEST);
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.cms.CMSPageUrlResolvingController.java

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody/*from www  .  java 2 s  . c  o  m*/
@ExceptionHandler(Exception.class)
public String handleExceptions(final Exception exception) {
    LOG.error(exception.getMessage());
    return "Reason [" + exception.getMessage() + "]";
}

From source file:com.miserablemind.butter.apps.butterApp.controller.ControllerExceptionHandler.java

/**
 * Handles "Bad Request" scenario and renders a 400 page.
 *
 * @param request   http request used for getting the URL and wiring config into model
 * @param exception exception that was thrown, in this case {@link com.miserablemind.butter.apps.butterApp.exception.HTTPBadRequestException}
 * @return logical name of a view to render
 *//*from   www .j  a  va2 s .c  o m*/
@ResponseStatus(HttpStatus.BAD_REQUEST) // 400
@ExceptionHandler(HTTPBadRequestException.class)
public String handleBadRequest(HttpServletRequest request, Exception exception) {
    logger.error("[400] Request: " + request.getRequestURL() + " raised " + exception, exception);
    request.setAttribute("configApp", this.config);
    if (Utilities.getAuthUserId() == 0)
        return "guest/errors/400";
    return "errors/400";
}

From source file:com.ge.predix.acs.commons.web.RestErrorHandlerTest.java

@Test
public void testIllegalArgumentException() {
    RestErrorHandler errorHandler = new RestErrorHandler();

    HttpServletRequest request = new MockHttpServletRequest();
    HttpServletResponse response = new MockHttpServletResponse();
    Exception e = new IllegalArgumentException("Descriptive Error Message");

    ModelAndView errorResponse = errorHandler.createApiErrorResponse(e, request, response);

    // The default error status code for IllegalArgumentException is 400
    Assert.assertEquals(response.getStatus(), HttpStatus.BAD_REQUEST.value());

    Assert.assertNotNull(errorResponse);
    Assert.assertNotNull(errorResponse.getModel().get("ErrorDetails"));

    // Response payload with default error code and the
    // IllegalArgumentException's message
    assertRestApiErrorResponse(errorResponse, "FAILED", "Descriptive Error Message");
}

From source file:business.controllers.UserController.java

@RequestMapping(value = "/register/users/activate/{token}", method = RequestMethod.GET)
public ResponseEntity<Object> activateUser(@PathVariable String token) {
    ActivationLink link = activationLinkRepository.findByToken(token);

    if (link == null) {
        log.warn("Activation link not found.");
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    }/*  w w w  .  j a v  a  2 s. c  o m*/
    // Check that the link has been issued in the previous week
    log.info("Activation link: expiry hours = " + activationLinkExpiryHours);
    long linkAge = TimeUnit.MILLISECONDS.toHours(new Date().getTime() - link.getCreationDate().getTime()); // hours
    log.info("Activation link age in hours: " + linkAge);
    if (linkAge <= activationLinkExpiryHours) {
        User user = link.getUser();
        user.setEmailValidated(true);
        userService.save(user);
        activationLinkRepository.delete(link);
        log.info("User validated.");
        return new ResponseEntity<Object>(HttpStatus.OK);
    } else {
        // The activation link doesn't exist or is outdated!
        log.warn("Activation link expired.");
        return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
    }
}

From source file:de.hska.ld.oidc.controller.DocumentSSSInfoController.java

@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.GET, value = "/document/{documentId}/episode")
@Transactional/*from  w w w  .  j a  v  a2 s . c om*/
public Callable getEpisodeId(@PathVariable Long documentId) {
    return () -> {
        Document document = documentService.findById(documentId);
        if (document == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        DocumentSSSInfo documentSSSInfo = documentSSSInfoService.getDocumentSSSInfo(document);
        if (documentSSSInfo == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<>(documentSSSInfo, HttpStatus.OK);
    };
}

From source file:org.bonitasoft.web.designer.controller.ResourceControllerAdvice.java

@ExceptionHandler(ConstraintValidationException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ResponseEntity<ErrorMessage> handleConstraintValidationException(
        ConstraintValidationException exception) {
    logger.error("Constraint Validation Exception", exception);
    return new ResponseEntity<>(new ErrorMessage(exception), HttpStatus.BAD_REQUEST);
}

From source file:csns.web.controller.CourseMappingControllerS.java

@RequestMapping("/department/{dept}/course/mapping/addCourse")
@ResponseBody//from  ww w.j  av  a2  s . co m
public ResponseEntity<String> addCourse(@ModelAttribute("mapping") CourseMapping mapping,
        @RequestParam Long courseId, @RequestParam String group) {
    Course course = courseDao.getCourse(courseId);
    if (mapping.contains(course))
        return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);

    if (group.equalsIgnoreCase("group1"))
        mapping.getGroup1().add(course);
    else
        mapping.getGroup2().add(course);

    logger.info(SecurityUtils.getUser().getUsername() + " added course " + courseId + " to mapping "
            + mapping.getId());

    return new ResponseEntity<String>(HttpStatus.OK);
}

From source file:eu.freme.common.exception.ExceptionHandlerService.java

public ResponseEntity<String> handleError(HttpServletRequest req, Throwable exception) {
    logger.error("Request: " + req.getRequestURL() + " raised ", exception);

    HttpStatus statusCode = null;/* ww  w . j  a  va2  s  .com*/
    if (exception instanceof MissingServletRequestParameterException) {
        // create response for spring exceptions
        statusCode = HttpStatus.BAD_REQUEST;
    } else if (exception instanceof FREMEHttpException
            && ((FREMEHttpException) exception).getHttpStatusCode() != null) {
        // get response code from FREMEHttpException
        statusCode = ((FREMEHttpException) exception).getHttpStatusCode();
    } else if (exception instanceof AccessDeniedException) {
        statusCode = HttpStatus.UNAUTHORIZED;
    } else if (exception instanceof HttpMessageNotReadableException) {
        statusCode = HttpStatus.BAD_REQUEST;
    } else {
        // get status code from exception class annotation
        Annotation responseStatusAnnotation = exception.getClass().getAnnotation(ResponseStatus.class);
        if (responseStatusAnnotation instanceof ResponseStatus) {
            statusCode = ((ResponseStatus) responseStatusAnnotation).value();
        } else {
            // set default status code 500
            statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
    JSONObject json = new JSONObject();
    json.put("status", statusCode.value());
    json.put("message", exception.getMessage());
    json.put("error", statusCode.getReasonPhrase());
    json.put("timestamp", new Date().getTime());
    json.put("exception", exception.getClass().getName());
    json.put("path", req.getRequestURI());

    if (exception instanceof AdditionalFieldsException) {
        Map<String, JSONObject> additionalFields = ((AdditionalFieldsException) exception)
                .getAdditionalFields();
        for (String key : additionalFields.keySet()) {
            json.put(key, additionalFields.get(key));
        }
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/json");

    return new ResponseEntity<String>(json.toString(2), responseHeaders, statusCode);
}