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:fr.lepellerin.ecole.web.controller.cantine.DetaillerReservationRepasController.java

@RequestMapping(value = "/reserver")
@ResponseBody/*from  w w  w .  j  a v  a  2 s.  c o m*/
public ResponseEntity<String> reserver(@RequestParam final String date, @RequestParam final int individuId)
        throws TechnicalException {
    final CurrentUser user = (CurrentUser) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();
    final LocalDate localDate = LocalDate.parse(date,
            DateTimeFormatter.ofPattern(GeDateUtils.DATE_FORMAT_YYYYMMDD, Locale.ROOT));
    String result;
    try {
        result = this.cantineService.reserver(localDate, individuId, user.getUser().getFamille(), null);
        return ResponseEntity.ok(result);
    } catch (FunctionalException e) {
        LOGGER.error("Une erreur fonctionnelle s'est produite : " + e.getMessage(), e);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
    }
}

From source file:org.easyj.rest.controller.AbstractController.java

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(TypeMismatchException.class)
public ModelAndView handleTypeMismatch(TypeMismatchException e) {
    BindingResult result = createBindingResult(getClass());

    result.addError(new FieldError("param.bind", e.getRequiredType().getSimpleName(), e.getValue(), true, null,
            null, "error.param.bind.type"));

    return configMAV(null, result, "errors/badrequest");
}

From source file:org.openlmis.fulfillment.web.errorhandler.ServiceErrorHandling.java

/**
 * Handles data integrity violation exception.
 *
 * @param ex the data integrity exception
 * @return the user-oriented error message.
 *//*from  w w  w . ja  v  a 2s.co m*/
@ExceptionHandler(DataIntegrityViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<Message.LocalizedMessage> handleDataIntegrityViolation(
        DataIntegrityViolationException ex) {
    if (ex.getCause() instanceof ConstraintViolationException) {
        ConstraintViolationException cause = (ConstraintViolationException) ex.getCause();
        String messageKey = CONSTRAINT_MAP.get(cause.getConstraintName());
        if (messageKey != null) {
            logger.error(CONSTRAINT_VIOLATION, ex);
            return new ResponseEntity<>(getLocalizedMessage(new Message(messageKey)), HttpStatus.BAD_REQUEST);
        } else {
            return new ResponseEntity<>(
                    logErrorAndRespond(CONSTRAINT_VIOLATION, MessageKeys.CONSTRAINT_VIOLATION, ex.getMessage()),
                    HttpStatus.BAD_REQUEST);
        }
    }

    return new ResponseEntity<>(
            logErrorAndRespond("Data integrity violation", DATA_INTEGRITY_VIOLATION, ex.getMessage()),
            CONFLICT);
}

From source file:com.chevres.rss.restapi.controller.ArticleController.java

@CrossOrigin
@RequestMapping(path = "/feed/{feedId}/articles/{pageNumber}", method = RequestMethod.GET)
@ResponseBody/*www. j a v a  2  s  .  co  m*/
public ResponseEntity<String> getFeedArticles(@RequestHeader(value = "User-token") String userToken,
        @PathVariable int feedId, @PathVariable int pageNumber) {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
    UserAuthDAO userAuthDAO = context.getBean(UserAuthDAO.class);
    FeedDAO feedDAO = context.getBean(FeedDAO.class);
    ArticleDAO articleDAO = context.getBean(ArticleDAO.class);

    UserAuth userAuth = userAuthDAO.findByToken(userToken);
    if (userAuth == null) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("invalid_token"), HttpStatus.BAD_REQUEST);
    }

    Feed feed = feedDAO.findById(userAuth, feedId);
    if (feed == null) {
        context.close();
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }

    List<Article> articles = articleDAO.findArticlesByFeedAndPageId(feed, pageNumber);

    List<SuccessGetArticleWithIdResponse> finalList = new ArrayList<>();
    for (Article article : articles) {
        finalList.add(new SuccessGetArticleWithIdResponse(article.getId(), article.getFeed().getId(),
                article.getStatus().getLabel(), article.getLink(), article.getTitle(),
                article.getPreviewContent(), article.getFullContent()));
    }

    context.close();
    return new ResponseEntity(new SuccessGetFeedArticlesResponse(finalList), HttpStatus.OK);
}

From source file:io.kamax.mxisd.controller.DefaultExceptionHandler.java

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(InvalidResponseJsonException.class)
public String handle(HttpServletRequest req, InvalidResponseJsonException e) {
    return handle(req, "M_INVALID_JSON", e.getMessage());
}

From source file:com.frequentis.maritime.mcsr.web.rest.AccountResource.java

/**
 * POST  /register : register the user./*w  w w .j a  v  a 2  s.  co  m*/
 *
 * @param managedUserDTO the managed user DTO
 * @param request the HTTP request
 * @return the ResponseEntity with status 201 (Created) if the user is registered or 400 (Bad Request) if the login or e-mail is already in use
 */
@RequestMapping(value = "/register", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE,
        MediaType.TEXT_PLAIN_VALUE })
@Timed
public ResponseEntity<?> registerAccount(@Valid @RequestBody ManagedUserDTO managedUserDTO,
        HttpServletRequest request) {

    HttpHeaders textPlainHeaders = new HttpHeaders();
    textPlainHeaders.setContentType(MediaType.TEXT_PLAIN);

    return userRepository.findFirstByLogin(managedUserDTO.getLogin().toLowerCase())
            .map(user -> new ResponseEntity<>("login already in use", textPlainHeaders, HttpStatus.BAD_REQUEST))
            .orElseGet(() -> userRepository.findFirstByEmail(managedUserDTO.getEmail())
                    .map(user -> new ResponseEntity<>("e-mail address already in use", textPlainHeaders,
                            HttpStatus.BAD_REQUEST))
                    .orElseGet(() -> {
                        User user = userService.createUserInformation(managedUserDTO.getLogin(),
                                managedUserDTO.getPassword(), managedUserDTO.getFirstName(),
                                managedUserDTO.getLastName(), managedUserDTO.getEmail().toLowerCase(),
                                managedUserDTO.getLangKey());
                        String baseUrl = request.getScheme() + // "http"
                        "://" + // "://"
                        request.getServerName() + // "myhost"
                        ":" + // ":"
                        request.getServerPort() + // "80"
                        request.getContextPath(); // "/myContextPath" or "" if deployed in root context

                        mailService.sendActivationEmail(user, baseUrl);
                        return new ResponseEntity<>(HttpStatus.CREATED);
                    }));
}

From source file:de.steilerdev.myVerein.server.controller.admin.DivisionManagementController.java

/**
 * This function is saving changes on an exisiting division. If the division needs to be created see {@link DivisionManagementController#createDivision}. This function is invoked by POSTing the parameters to the URI /api/admin/division.
 * @param name The new name of the division.
 * @param oldName The old name of the division (might be equal to new name)
 * @param description The description of the division (may be empty)
 * @param admin The name of the administrating user (may be empty)
 * @param currentUser The currently logged in user.
 * @return An HTTP response with a status code. If an error occurred an error message is bundled into the response, otherwise a success message is available.
 *///from  w  w w . j a v  a2  s . c o  m
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> saveDivision(@RequestParam String name, @RequestParam String oldName,
        @RequestParam String description, @RequestParam String admin, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "]  Saving division");
    //String successMessage = "Successfully saved division";
    if (currentUser.isAdmin()) {
        Division division;
        Division oldDivision = null;

        if (oldName.isEmpty()) {
            logger.warn("[" + currentUser + "]  The original name of the division is missing");
            return new ResponseEntity<>("The original name of the division is missing", HttpStatus.BAD_REQUEST);
        } else if (oldName.equals(name) && (division = divisionRepository.findByName(oldName)) != null) {
            //A division is changed, name stays.
            logger.debug("[" + currentUser + "]  An existing division is changed (" + oldName
                    + "). The name is unchanged.");
        } else if ((oldDivision = division = divisionRepository.findByName(oldName)) != null
                && divisionRepository.findByName(name) == null) {
            //An existing divisions name is changed and the name is unique
            logger.debug("[" + currentUser
                    + "]  An existing division is changed (including its name). The name changed from "
                    + oldName + " to " + name);
        } else if (division.getParent() == null) {
            logger.debug(
                    "[" + currentUser + "]  The root division is not allowed to be modified through this API");
            return new ResponseEntity<>("The root division is not allowed to be modified through this API",
                    HttpStatus.FORBIDDEN);
        } else {
            logger.warn("[" + currentUser + "]  Problem finding existing division (" + oldName
                    + "), either the existing division could not be located or the new name is already taken");
            return new ResponseEntity<>(
                    "Problem finding existing division, either the existing division could not be located or the new name is already taken",
                    HttpStatus.BAD_REQUEST);
        }

        if (currentUser.isAllowedToAdministrate(division, divisionRepository)) //Check if user is allowed to change the division (if he administrates one of the parent divisions)
        {
            User adminUser = null;
            if (admin != null && !admin.isEmpty()) {
                adminUser = userRepository.findByEmail(admin);
                if (adminUser == null) {
                    logger.warn("[" + currentUser + "]  Unable to find specified admin user: " + admin);
                    return new ResponseEntity<>("Unable to find specified admin user.", HttpStatus.BAD_REQUEST);
                }
            } else {
                logger.warn("[" + currentUser + "]  No admin stated for division " + division.getName());
            }
            division.setAdminUser(adminUser);
            division.setName(name);
            division.setDesc(description);

            try {
                if (oldDivision != null) {
                    logger.debug("[" + currentUser + "]  Deleting old division " + oldDivision.getName());
                    divisionRepository.delete(oldDivision);
                }
                divisionRepository.save(division);
                logger.info("[" + currentUser + "]  Successfully saved division " + division.getName());
                return new ResponseEntity<>("Successfully saved division", HttpStatus.OK);
            } catch (ConstraintViolationException e) {
                logger.warn("[" + currentUser
                        + "]  A database constraint was violated while saving the division: " + e.getMessage());
                return new ResponseEntity<>("A database constraint was violated while saving the division.",
                        HttpStatus.BAD_REQUEST);
            }
        } else {
            logger.warn("[" + currentUser + "]  The user is not allowed to change the division ("
                    + division.getName() + ")");
            return new ResponseEntity<>("You are not allowed to change this division.", HttpStatus.FORBIDDEN);
        }
    } else {
        logger.warn("[" + currentUser + "]  The user not allowed to create a new division.");
        return new ResponseEntity<>("You are not allowed to create a new division", HttpStatus.FORBIDDEN);
    }
}

From source file:org.ow2.proactive.procci.rest.MixinRest.java

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<MixinRendering> createMixin(@RequestBody MixinRendering mixinRendering) {
    logger.debug("Creating Mixin " + mixinRendering.toString());
    try {// w w  w .j  a va  2 s  . c  o  m
        Mixin mixin = new MixinBuilder(mixinService, instanceService, mixinRendering).build();
        mixinService.addMixin(mixin);

        return new ResponseEntity(mixin.getRendering(), HttpStatus.OK);
    } catch (ServerException ex) {
        logger.error(this.getClass().getName(), ex);
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (ClientException ex) {
        return new ResponseEntity(ex.getJsonError(), HttpStatus.BAD_REQUEST);
    }
}

From source file:hr.foi.sis.controllers.PersonController.java

/**
 * inserts new user to database/*  w  w w . ja  va2s .  c o  m*/
 * @param person user to insert
 * @return person info and HTTP 200 on success or HTTP BAD REQUEST on fail
 */
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public ResponseEntity<Person> signup(@RequestBody Person person)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    Logger.getLogger("PersonController.java").log(Level.INFO, "POST on /person/signup -- " + person.toString());

    Role role = new Role();
    role.setId(2);
    role.setName("ROLE_USER");
    person.setRole(role);

    String salt = PBKDF2.generateSalt();
    person.setSalt(salt);

    String passwordHash = PBKDF2.getEncryptedPassword(person.getCredentials().getPassword(), salt);

    person.getCredentials().setPassword(passwordHash);

    Logger.getLogger("PersonController.java").log(Level.INFO, "Password -- " + passwordHash);

    Person signed = this.personRepository.save(person);

    if (signed != null) {

        Logger.getLogger("PersonController.java").log(Level.INFO,
                "Registration success for " + signed.toString());

        return new ResponseEntity(signed, HttpStatus.OK);

    } else {

        Logger.getLogger("PersonController.java").log(Level.WARN,
                "Registration failed for " + person.toString());

        return new ResponseEntity(HttpStatus.BAD_REQUEST);
    }
}

From source file:se.sawano.scala.examples.scalaspringmvc.ValidationTestIT.java

@Test
public void scalaPostWithInvalidAge() {
    try {/*from w  ww .  j a  va2 s. co m*/
        ScalaIndata indata = new ScalaIndata("Daniel", -1);
        restTemplate.postForObject(baseUrl + "scala/indata", indata, Void.class, (Object) null);
        fail("Expected JSR-303 validation to fail");
    } catch (HttpClientErrorException e) {
        assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode());
    }
}