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.apereo.openlrs.controllers.xapi.XAPIExceptionHandlerAdvice.java

@ExceptionHandler(InvalidXAPIRequestException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody// w  w  w  .j a  v a 2  s  .com
public XAPIErrorInfo handleInvalidRestRequestException(final HttpServletRequest request,
        final InvalidXAPIRequestException e) {
    final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, e.getLocalizedMessage());
    this.logException(e);
    this.logError(result);
    return result;
}

From source file:com.wolkabout.hexiwear.activity.SignUpActivity.java

@Background
void startSignUp() {
    final SignUpDto signUpDto = parseUserInput();
    try {//from  www  .  ja va  2  s . c  om
        authenticationService.signUp(signUpDto);
        onSignUpSuccess();
    } catch (HttpStatusCodeException e) {
        if (e.getStatusCode() == HttpStatus.BAD_REQUEST
                && e.getResponseBodyAsString().contains("USER_EMAIL_IS_NOT_UNIQUE")) {
            onSignUpError(R.string.registration_error_email_already_exists);
            return;
        }

        onSignUpError(R.string.registration_failed);
    } catch (Exception e) {
        onSignUpError(R.string.registration_failed);
    } finally {
        dismissSigningUpLabel();
    }
}

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

/**
 * This function gathers all dates where an event takes place within a specific month and year. The function is invoked by GETting the URI /api/admin/event/month and specifying the month and year via the request parameters.
 * @param month The selected month.//from w  w  w . j  a  va  2s.c  o m
 * @param year The selected year.
 * @return An HTTP response with a status code. If the function succeeds, a list of dates, during the month, that contain an event, is returned, otherwise an error code is returned.
 */
@RequestMapping(value = "month", produces = "application/json", method = RequestMethod.GET)
public ResponseEntity<List<LocalDate>> getEventDatesOfMonth(@RequestParam String month,
        @RequestParam String year, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Gathering events of month " + month + " and year " + year);
    ArrayList<LocalDate> dates = new ArrayList<>();
    int monthInt, yearInt;
    try {
        monthInt = Integer.parseInt(month);
        yearInt = Integer.parseInt(year);
    } catch (NumberFormatException e) {
        logger.warn("[" + currentUser + "] Unable to parse month or year.");
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    LocalDateTime start = LocalDate.of(yearInt, monthInt, 1).atStartOfDay();
    LocalDateTime end = start.plusMonths(1);

    logger.debug("Getting all single day events...");
    dates.addAll(eventRepository.findAllByEndDateTimeBetweenAndMultiDate(start, end, false).parallelStream()
            .map(Event::getStartDate).collect(Collectors.toList()));
    logger.debug("All single day events retrieved, got " + dates.size() + " dates so far");

    logger.debug("Getting all multi day events...");
    //Collecting all multi date events, that either start or end within the selected month (which means that events that are spanning over several months are not collected)
    Stream.concat(eventRepository.findAllByStartDateTimeBetweenAndMultiDate(start, end, true).stream(), //All multi date events starting within the month
            eventRepository.findAllByEndDateTimeBetweenAndMultiDate(start, end, true).stream()) //All multi date events ending within the month
            .distinct() //Removing all duplicated events
            .parallel().forEach(event -> { //Creating a local date for each occupied date of the event
                for (LocalDate date = event.getStartDate(); //Starting with the start date
                        !date.equals(event.getEndDateTime().toLocalDate()); //Until reaching the end date
                        date = date.plusDays(1)) //Adding a day within each iterations
                {
                    dates.add(date);
                }
                dates.add(event.getEndDateTime().toLocalDate()); //Finally adding the last date
            });
    logger.debug("All multi day events gathered, got " + dates.size() + " dates so far");

    if (dates.isEmpty()) {
        logger.warn("[" + currentUser + "] Returning empty dates list of " + month + "/" + year);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    } else {
        logger.debug("[" + currentUser + "] Returning dates list " + month + "/" + year);
        return new ResponseEntity<>(dates.stream().distinct().collect(Collectors.toList()), HttpStatus.OK); //Returning an optimized set of events
    }
}

From source file:app.api.swagger.SwaggerConfig.java

private List<ResponseMessage> defaultHttpResponses() {
    final List<ResponseMessage> results = new ArrayList<ResponseMessage>();
    results.add(response(HttpStatus.FORBIDDEN, null));
    results.add(response(HttpStatus.UNAUTHORIZED, null));
    results.add(response(HttpStatus.BAD_REQUEST, null));
    results.add(response(HttpStatus.UNPROCESSABLE_ENTITY, ERROR_MODEL));
    return results;
}

From source file:com.ecsteam.cloudlaunch.controller.RestServices.java

@RequestMapping(value = "/builds/trigger", method = RequestMethod.POST)
public ResponseEntity<QueuedBuildResponse> triggerBuild() {
    QueuedBuildResponse responseBody = null;
    ResponseEntity<QueuedBuildResponse> response = null;

    responseBody = jenkinsService.triggerBuild();
    if (responseBody != null) {
        response = new ResponseEntity<QueuedBuildResponse>(responseBody, HttpStatus.OK);
    } else {/*from w  w  w.ja  v a 2s. co  m*/
        response = new ResponseEntity<QueuedBuildResponse>(HttpStatus.BAD_REQUEST);
    }

    return response;
}

From source file:hr.softwarecity.osijek.controllers.PersonController.java

/**
 * Method for validating user login/* www. j  a va  2s.  c o m*/
 * @param username username input value
 * @param password password input value
 * @param request session inject object
 * @return person information in json format
 */
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<Person> checkLogin(@RequestParam("username") String username,
        @RequestParam("password") String password, ServletRequest request) {
    // log stuff
    Logger.getLogger("PersonController.java").log(Level.INFO, "Recognized request to /login path");
    Logger.getLogger("PersonController.java").log(Level.INFO,
            "Recieved username " + username + " with password " + password);
    Logger.getLogger("PersonController.java").log(Level.INFO, "Validating username and password");

    // username and password validation
    if (username == null || password == null || username.trim().isEmpty() || password.trim().isEmpty()) {
        Logger.getLogger("PersonController.java").log(Level.WARN, "Username and password validation failed");
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    // fetching person
    Person found = personRepository.findByUsernameAndPassword(username, password);

    if (found != null) {
        Logger.getLogger("PersonController.java").log(Level.INFO, "Returning " + found.toString());
        ((HttpServletRequest) request).getSession().setAttribute("person", found);
        Logger.getLogger("PersonController.java").log(Level.INFO, "Created session " + found.toString());
        return new ResponseEntity<>(found, HttpStatus.OK);
    } else {
        Logger.getLogger("PersonController.java").log(Level.WARN, "No person found");
        return new ResponseEntity<>(found, HttpStatus.NOT_FOUND);
    }
}

From source file:com.sms.server.controller.AdminController.java

@RequestMapping(value = "/user/role", method = RequestMethod.POST, headers = {
        "Content-type=application/json" })
@ResponseBody/*from   www .j a  va 2 s  . c  om*/
public ResponseEntity<String> createUserRole(@RequestBody UserRole userRole) {
    // Check mandatory fields.
    if (userRole.getUsername() == null || userRole.getRole() == null) {
        return new ResponseEntity<>("Missing required parameter.", HttpStatus.BAD_REQUEST);
    }

    // Check unique fields
    if (userDao.getUserByUsername(userRole.getUsername()) == null) {
        return new ResponseEntity<>("Username is not registered.", HttpStatus.NOT_ACCEPTABLE);
    }

    // Add user role to the database.
    if (!userDao.createUserRole(userRole)) {
        LogService.getInstance().addLogEntry(Level.ERROR, CLASS_NAME,
                "Error adding role'" + userRole.getRole() + "' to user '" + userRole.getUsername() + "'.",
                null);
        return new ResponseEntity<>("Error adding user role to database.", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    LogService.getInstance().addLogEntry(Level.INFO, CLASS_NAME,
            "Added role'" + userRole.getRole() + "' to user '" + userRole.getUsername() + "'.", null);
    return new ResponseEntity<>("User role added successfully.", HttpStatus.CREATED);
}

From source file:net.maritimecloud.identityregistry.controllers.LogoController.java

/**
 * Creates or updates a logo for an organization
 * @param request request to get servletPath
 * @param orgMrn resource location for organization
 * @param logo the log encoded as a MultipartFile
 * @throws McBasicRestException/*from  w  w  w. j a v  a 2  s. c o m*/
 */
@RequestMapping(value = "/api/org/{orgMrn}/logo", method = RequestMethod.POST)
@ResponseBody
@PreAuthorize("hasRole('ORG_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<?> createLogoPost(HttpServletRequest request, @PathVariable String orgMrn,
        @RequestParam("logo") MultipartFile logo) throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        try {
            this.updateLogo(org, logo.getInputStream());
            organizationService.save(org);
            return new ResponseEntity<>(HttpStatus.CREATED);
        } catch (IOException e) {
            log.error("Unable to create logo", e);
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.INVALID_IMAGE,
                    request.getServletPath());
        }
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:com.ccserver.digital.controller.AdminControllerTest.java

@Test
public void getAppListWithNullId() {

    PageRequest page = new PageRequest(1, 1);

    // when/*  ww w  .ja  v  a  2  s.  c  o  m*/
    ResponseEntity<?> application = controller.getAppList(null, page);

    // then
    Assert.assertEquals(HttpStatus.BAD_REQUEST, application.getStatusCode());
    Assert.assertEquals(Constants.APPLICATION_ID_REQUIRED, ((ErrorObject) application.getBody()).getId());
}

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

@RequestMapping(value = "/rubric/evaluation/{role}/set", params = { "index", "value" })
@ResponseBody/*from   w  ww  .j a  v a  2 s .  c  o m*/
public ResponseEntity<String> set(@RequestParam Long id, @RequestParam int index, @RequestParam int value) {
    RubricEvaluation evaluation = rubricEvaluationDao.getRubricEvaluation(id);
    // Ignore the request if the rubric assignment is already past due.
    if (evaluation.getSubmission().getAssignment().isPastDue())
        return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);

    evaluation.getRatings().set(index, value + 1);
    evaluation.setCompleted();
    rubricEvaluationDao.saveRubricEvaluation(evaluation);

    logger.info(SecurityUtils.getUser().getUsername() + " rated " + (value + 1) + " for indicator " + index
            + " in rubric evaluation " + id);

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