List of usage examples for org.springframework.http HttpStatus BAD_REQUEST
HttpStatus BAD_REQUEST
To view the source code for org.springframework.http HttpStatus BAD_REQUEST.
Click Source Link
From source file:com.github.cherimojava.orchidae.controller.LayoutController.java
private ResponseEntity registerUser(HttpServletRequest request) { // TODO send messages out if something isn't right if (StringUtils.isEmpty(request.getParameter("username"))) { return new ResponseEntity(HttpStatus.BAD_REQUEST); }//from w ww . j a va2s . com if (factory.load(User.class, request.getParameter("username")) != null) { return new ResponseEntity(HttpStatus.BAD_REQUEST); } String pwd = request.getParameter("password"); if (StringUtils.isNotEmpty(pwd) && pwd.equals(request.getParameter("password2"))) { User newUser = factory.create(User.class); newUser.setMemberSince(DateTime.now()); newUser.setUsername(request.getParameter("username")); newUser.setPassword(pwEncoder.encode(pwd)); newUser.save(); } return new ResponseEntity(HttpStatus.NO_CONTENT); }
From source file:br.com.modoagil.asr.rest.support.GenericWebService.java
/** * Lista todos os objetos contantes na base de dados * * @return {@link Response} resposta do processamento *//*w w w . j av a 2 s . co m*/ @ResponseBody @RequestMapping(value = WebServicesURL.URL_LIST, method = { GET, POST }, produces = APPLICATION_JSON) public final Response<E> list() { Response<E> response; this.getLogger().debug("listando objetos"); try { final List<E> dataList = this.getRepository().findAll(); final Integer dataListSize = dataList.size(); final String message = dataListSize > 0 ? String.format(ResponseMessages.LIST_MESSAGE, dataListSize) : ResponseMessages.NOTFOUND_LIST_MESSAGE; response = new ResponseBuilder<E>().success(true).data(dataList).message(message).status(HttpStatus.OK) .build(); this.getLogger().debug(message); } catch (final Exception e) { final String message = ExceptionUtils.getRootCauseMessage(e); response = new ResponseBuilder<E>().success(false).message(message).status(HttpStatus.BAD_REQUEST) .build(); this.getLogger().error("erro ao listar objetos " + message, e); } return response; }
From source file:br.com.s2it.snakes.controllers.CarController.java
@CrossOrigin("*") @RequestMapping(value = "/reservation/{reservation}/cancel", method = RequestMethod.GET) public ResponseEntity<String> removePassengerToReservation( final @PathVariable(value = "reservation") String reservation) { if (reservation == null || reservation.isEmpty()) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); }//w w w.ja v a2 s. c o m try { service.cancelCarReservation(reservation); } catch (Exception e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } return ResponseEntity.status(HttpStatus.OK).body(null); }
From source file:jetbrains.buildServer.projectPush.PostProjectToSandboxController.java
@Nullable @Override/*from w ww. j av a2s .c o m*/ protected ModelAndView doHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response) throws Exception { if (!isPost(request)) { response.sendError(HttpStatus.METHOD_NOT_ALLOWED.value()); return null; } final StringBuilder stringBuffer = new StringBuilder(); try { String line; BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) stringBuffer.append(line); } catch (Exception e) { response.sendError(HttpStatus.BAD_REQUEST.value(), e.getMessage()); return null; } final String projectName = stringBuffer.toString(); if (projectName.isEmpty()) { response.sendError(HttpStatus.BAD_REQUEST.value(), "Project name is empty."); return null; } if (mySettings.isDisabled()) { response.sendError(HttpStatus.FORBIDDEN.value(), "Sandbox disabled."); return null; } SUser user; user = SessionUser.getUser(request); if (user == null) { user = myAuthHelper.getAuthenticatedUser(request, response); } if (user == null) return null; final Role projectAdminRole = myRolesHelper.findProjectAdminRole(); if (projectAdminRole == null) { response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Failed to locate Project Admin role on the server."); return null; } final SProject project; try { final String sandboxProjectId = mySettings.getSandboxProjectId(); final SProject sandboxProject = myProjectManager.findProjectByExternalId(sandboxProjectId); if (sandboxProject == null) { response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Failed to locate sandbox project by ID " + sandboxProjectId); return null; } if (sandboxProject.findProjectByName(projectName) != null) { response.sendError(HttpStatus.CONFLICT.value(), "Project with name " + projectName + " already exists."); return null; } project = sandboxProject.createProject( myProjectIdentifiersManager.generateNewExternalId(null, projectName, null), projectName); project.persist(); } catch (Exception e) { response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()); return null; } try { myRolesHelper.addRole(user, RoleScope.projectScope(project.getProjectId()), projectAdminRole); } catch (Throwable throwable) { response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), throwable.getMessage()); return null; } response.setStatus(HttpStatus.CREATED.value()); response.setHeader(HttpHeaders.LOCATION, RESTApiHelper.getProjectURI(project)); return null; }
From source file:com.ar.dev.tierra.api.controller.ReservaController.java
@RequestMapping(value = "/day/paged", method = RequestMethod.GET) public ResponseEntity<?> getDayPaged(OAuth2Authentication authentication, @RequestParam(value = "page", required = false, defaultValue = "0") Integer page, @RequestParam(value = "size", required = false, defaultValue = "10") Integer size) { Usuarios user = facadeService.getUsuariosDAO().findUsuarioByUsername(authentication.getName()); Page factura = facadeService.getFacturaService().getReservasDay(page, size, user.getUsuarioSucursal().getIdSucursal()); if (factura != null) { return new ResponseEntity<>(factura, HttpStatus.OK); } else {/*from w w w . j a v a2 s . c om*/ return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }
From source file:net.jkratz.igdb.controller.advice.ErrorController.java
@RequestMapping(produces = "application/json") @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) public @ResponseBody Map<String, Object> handleValidationException(MethodArgumentNotValidException ex) throws IOException { logger.warn(ex.getMessage());//from w w w . j av a2 s .c om Map<String, Object> map = Maps.newHashMap(); map.put("error", "Validation Failure"); map.put("violations", convertConstraintViolation(ex)); map.put("target", ex.getBindingResult().getTarget()); map.put("expectedType", ex.getBindingResult().getObjectName()); return map; }
From source file:ch.wisv.areafiftylan.teams.controller.TeamRestController.java
/** * The method to handle POST requests on the /teams endpoint. This creates a new team. Users can only create new * Teams with themselves as Captain. Admins can also create Teams with other Users as Captain. * * @param teamDTO Object containing the Team name and Captain username. When coming from a user, username should * equal their own username. * @param auth Authentication object from Spring Security * * @return Return status message of the operation *//*ww w .j a v a 2 s . co m*/ @PreAuthorize("isAuthenticated() and @currentUserServiceImpl.hasAnyTicket(principal)") @JsonView(View.Public.class) @RequestMapping(method = RequestMethod.POST) ResponseEntity<?> add(@Validated @RequestBody TeamDTO teamDTO, Authentication auth) { if (teamService.teamnameUsed(teamDTO.getTeamName())) { return createResponseEntity(HttpStatus.CONFLICT, "Team with name \"" + teamDTO.getTeamName() + "\" already exists."); } Team team; // Users can only create teams with themselves as Captain if (auth.getAuthorities().contains(Role.ROLE_ADMIN)) { team = teamService.create(teamDTO.getCaptainUsername(), teamDTO.getTeamName()); } else { // If the DTO contains another username as the the current user, return an error. if (!auth.getName().equalsIgnoreCase(teamDTO.getCaptainUsername())) { return createResponseEntity(HttpStatus.BAD_REQUEST, "Can not create team with another user as Captain"); } team = teamService.create(auth.getName(), teamDTO.getTeamName()); } HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}") .buildAndExpand(team.getId()).toUri()); return createResponseEntity(HttpStatus.CREATED, httpHeaders, "Team successfully created at " + httpHeaders.getLocation(), team); }
From source file:edu.sjsu.cmpe275.lab2.controller.ManagePersonController.java
/** Create a person object * 1 Path: person?firstname=XX&lastname=YY& email=ZZ&description=UU&street=VV$... * Method: POST/* ww w . java 2 s. co m*/ * This API creates a person object. * 1. For simplicity, all the person fields (firstname, lastname, email, street, city, * organization, etc), except ID and friends, are passed in as query parameters. Only the * firstname, lastname, and email are required. Anything else is optional. * 2. Friends is not allowed to be passed in as a parameter. * 3. The organization parameter, if present, must be the ID of an existing organization. * 4. The request returns the newly created person object in JSON in its HTTP payload, * including all attributes. (Please note this differs from generally recommended practice * of only returning the ID.) * 5. If the request is invalid, e.g., missing required parameters, the HTTP status code * should be 400; otherwise 200. * @param a Description of a * @param b Description of b * @return Description of c */ @RequestMapping(value = "", method = RequestMethod.POST) public ResponseEntity<?> createPerson(@RequestParam(value = "firstname", required = true) String firstname, @RequestParam(value = "lastname", required = true) String lastname, @RequestParam(value = "email", required = true) String email, @RequestParam(value = "description", required = false) String description, @RequestParam(value = "street", required = false) String street, @RequestParam(value = "city", required = false) String city, @RequestParam(value = "state", required = false) String state, @RequestParam(value = "zip", required = false) String zip, @RequestParam(value = "orgid", required = false) Long orgid) { Organization organization = null; Person person = new Person(); person.setEmail(email); person.setFirstname(firstname); person.setLastname(lastname); person.setAddress(new Address(street, city, state, zip)); person.setDescription(description); person = personDao.create(person, orgid); if (person == null) { return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST); } return new ResponseEntity<Object>(person, HttpStatus.OK); }
From source file:com.iggroup.oss.sample.web.controller.BaseController.java
/** * Validate the given object using the configured validator, throwing a * BusinessException if the object fails validation * //from w ww. j a v a2 s .c o m * @param o the object to be validated */ protected void validate(Object o) { ArrayList<SampleError> errors = new ArrayList<SampleError>(); for (ConstraintViolation<Object> violation : globalValidator.validate(o)) { errors.add(new ValidationError(violation.getLeafBean().getClass().getSimpleName(), violation.getPropertyPath().toString(), violation.getInvalidValue().toString(), violation.getRootBeanClass().getSimpleName())); } if (!errors.isEmpty()) { LOGGER.debug(errors); throw new SampleException(errors, HttpStatus.BAD_REQUEST); } }
From source file:org.venice.piazza.servicecontroller.messaging.handlers.DeleteServiceHandler.java
/** * Handler for the DeleteServiceJob that was submitted. Stores the metadata * in MongoDB (non-Javadoc)/*from w w w. jav a 2 s. c om*/ * * @see org.venice.piazza.servicecontroller.messaging.handlers.Handler#handle( * model.job.PiazzaJobType) */ @Override public ResponseEntity<String> handle(PiazzaJobType jobRequest) { ResponseEntity<String> responseEntity; if (jobRequest != null) { coreLogger.log("Deleting a service", Severity.DEBUG); DeleteServiceJob job = (DeleteServiceJob) jobRequest; // Get the ResourceMetadata String resourceId = job.serviceID; coreLogger.log("deleteService serviceId=" + resourceId, Severity.INFORMATIONAL); String result = handle(resourceId, false); if ((result != null) && (result.length() > 0)) { String jobId = job.getJobId(); ArrayList<String> resultList = new ArrayList<>(); resultList.add(jobId); resultList.add(resourceId); responseEntity = new ResponseEntity<>(resultList.toString(), HttpStatus.OK); } else { coreLogger.log("No result response from the handler, something went wrong", Severity.ERROR); responseEntity = new ResponseEntity<>("DeleteServiceHandler handle didn't work", HttpStatus.NOT_FOUND); } } else { coreLogger.log("A null PiazzaJobRequest was passed in. Returning null", Severity.ERROR); responseEntity = new ResponseEntity<>("A Null PiazzaJobRequest was received", HttpStatus.BAD_REQUEST); } return responseEntity; }