List of usage examples for org.springframework.http ResponseEntity badRequest
public static BodyBuilder badRequest()
From source file:org.createnet.raptor.auth.service.controller.AuthenticationController.java
@PreAuthorize("isAuthenticated()") @RequestMapping(value = "${jwt.route.authentication.path}", method = RequestMethod.DELETE) @ApiOperation(value = "Logout an user invalidating login the token", notes = "", nickname = "logout") public ResponseEntity<?> logout(HttpServletRequest request, Principal principal) { String reqToken = request.getHeader(tokenHeader).replace("Bearer ", ""); Token token = tokenService.read(reqToken); if (token == null) { return ResponseEntity.noContent().build(); }//from w w w. j a va 2 s .c o m if (token.getType() != Token.Type.LOGIN) { return ResponseEntity.badRequest().body(null); } tokenService.delete(token); return ResponseEntity.ok(null); }
From source file:cern.jarrace.controller.rest.controller.AgentContainerController.java
@RequestMapping(value = "/{" + CONTAINER_NAME_VARIABLE_NAME + "}/read", method = RequestMethod.GET) public ResponseEntity<String> readSource(@PathVariable(CONTAINER_NAME_VARIABLE_NAME) String containerName, @RequestParam("class") String className) { return agentContainerManager.findAgentContainer(containerName).map(container -> { try {//from w ww . j a v a 2s. c o m return JarReader.ofContainer(container, reader -> { final String entry = className + JAVA_CLASS_SUFFIX; try { return ResponseEntity.ok(reader.readEntry(entry)); } catch (NoSuchElementException e) { return ResponseEntity.badRequest().body("No class source found for entry " + entry); } catch (IOException e) { return ResponseEntity.status(INTERNAL_SERVER_ERROR) .body("Failed to read entry " + entry + " inside container " + containerName); } }); } catch (IOException e) { LOGGER.warn("Failed to read from container file {}: " + containerName, e); return ResponseEntity.status(INTERNAL_SERVER_ERROR) .body("Failed to open container of name " + containerName); } }).orElse(ResponseEntity.badRequest().body("No container deployed under the name " + containerName)); }
From source file:org.ow2.proactive.workflow_catalog.rest.controller.WorkflowController.java
@ApiOperation(value = "Gets a workflow's metadata by IDs", notes = "Returns metadata associated to the latest revision of the workflow.") @ApiResponses(value = @ApiResponse(code = 404, message = "Bucket or workflow not found")) @RequestMapping(value = "/buckets/{bucketId}/workflows/{idList}", method = GET) public ResponseEntity<?> get(@PathVariable Long bucketId, @PathVariable List<Long> idList, @ApiParam(value = "Force response to return workflow XML content when set to 'xml'. Or extract workflows as ZIP when set to 'zip'.") @RequestParam(required = false) Optional<String> alt, HttpServletResponse response) throws MalformedURLException { if (alt.isPresent() && ZIP_EXTENSION.equals(alt.get())) { byte[] zip = workflowService.getWorkflowsAsArchive(bucketId, idList); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("application/zip"); response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"archive.zip\""); response.addHeader(HttpHeaders.CONTENT_ENCODING, "binary"); try {// w ww .j a v a 2 s . com response.getOutputStream().write(zip); response.getOutputStream().flush(); } catch (IOException ioe) { throw new RuntimeException(ioe); } return ResponseEntity.ok().build(); } else { if (idList.size() == 1) { return workflowService.getWorkflowMetadata(bucketId, idList.get(0), alt); } else { return ResponseEntity.badRequest().build(); } } }
From source file:org.createnet.raptor.auth.service.controller.AuthenticationController.java
@PreAuthorize("isAuthenticated()") @RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET) @ApiOperation(value = "Refresh a login token", notes = "The authentication token, provided via `Authorization` header must still be valid.", response = JwtResponse.class, nickname = "refreshToken") public ResponseEntity<?> refreshToken(HttpServletRequest request, Principal principal) { String reqToken = request.getHeader(tokenHeader).replace("Bearer ", ""); Token token = tokenService.read(reqToken); if (token == null) { return ResponseEntity.badRequest().body(null); }//from w w w. ja v a 2s. c om Token refreshedToken = tokenService.refreshToken(token); return ResponseEntity.ok(new JwtResponse((User) principal, refreshedToken.getToken())); }
From source file:org.openlmis.fulfillment.web.TransferPropertiesController.java
/** * Allows updating transfer properties.//from w w w . j a v a 2s .co m * * @param properties A transfer properties bound to the request body * @param id UUID of transfer properties which we want to update * @return ResponseEntity containing the updated transfer properties */ @RequestMapping(value = "/transferProperties/{id}", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.OK) @ResponseBody public ResponseEntity update(@RequestBody TransferPropertiesDto properties, @PathVariable("id") UUID id) { LOGGER.debug("Checking right to update transfer properties "); permissionService.canManageSystemSettings(); TransferProperties toUpdate = transferPropertiesRepository.findOne(id); if (null == toUpdate) { return ResponseEntity.notFound().build(); } else if (null == properties.getFacility() || !Objects.equals(toUpdate.getFacilityId(), properties.getFacility().getId())) { throw new IncorrectTransferPropertiesException(); } else { LOGGER.debug("Updating Transfer Properties with id: {}", id); } TransferProperties entity = TransferPropertiesFactory.newInstance(properties); if (!Objects.equals(entity.getClass(), toUpdate.getClass())) { transferPropertiesRepository.delete(toUpdate); } List<Message.LocalizedMessage> errors = validate(entity); if (isNotTrue(errors.isEmpty())) { return ResponseEntity.badRequest().body(errors); } toUpdate = transferPropertiesRepository.save(entity); LOGGER.debug("Updated Transfer Properties with id: {}", toUpdate.getId()); return ResponseEntity.ok(TransferPropertiesFactory.newInstance(toUpdate, exporter)); }
From source file:co.bluepass.web.rest.ClubResource.java
/** * Update response entity.//from w w w .jav a 2 s.c o m * * @param dto the dto * @param request the request * @param principal the principal * @return the response entity * @throws URISyntaxException the uri syntax exception */ @RequestMapping(value = "/clubs", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<Void> update(@Valid @RequestBody ClubDTO dto, HttpServletRequest request, Principal principal) throws URISyntaxException { log.debug("REST request to update Club : {}", dto); if (dto.getId() == null) { return ResponseEntity.badRequest().header("Failure", " ?? ? .") .build(); } Club club = clubRepository.findOne(dto.getId()); if (!request.isUserInRole("ROLE_ADMIN") && !club.getCreator().getEmail().equals(SecurityUtils.getCurrentLogin())) { return ResponseEntity.badRequest().header("Failure", "?? ? .") .build(); } CommonCode category = dto.getCategory(); club.update(dto.getName(), dto.getLicenseNumber(), dto.getPhoneNumber(), dto.getZipcode(), dto.getAddress1(), dto.getAddress2(), dto.getOldAddress(), dto.getAddressSimple(), dto.getDescription(), dto.getHomepage(), dto.getOnlyFemale(), category, dto.getManagerMobile(), dto.getNotificationType(), dto.getReservationClose()); clubRepository.save(club); List<CommonCode> featureCodes = null; if (dto.getFeatures() != null) { List<Feature> oldFeatures = featureRepository.findByClub(club); featureRepository.delete(oldFeatures); //featureCodes = commonCodeRepository.findByNameIn(dto.getFeatures()); featureCodes = commonCodeRepository.findAll(Arrays.asList(dto.getFeatures())); if (featureCodes != null && !featureCodes.isEmpty()) { List<Feature> features = new ArrayList<Feature>(); for (CommonCode featureCode : featureCodes) { features.add(new Feature(club, featureCode)); } featureRepository.save(features); } } try { if (StringUtils.isNotEmpty(club.getOldAddress())) { addressIndexRepository.save(new AddressIndex(club.getOldAddress())); } } catch (Exception e) { e.printStackTrace(); } return ResponseEntity.ok().build(); }
From source file:com.boyuanitsm.fort.web.rest.AccountResource.java
/** * POST /account : update the current user information. * * @param userDTO the current user information * @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) or 500 (Internal Server Error) if the user couldn't be updated *//* www .j a va 2 s . c om*/ @RequestMapping(value = "/account", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<String> saveAccount(@Valid @RequestBody UserDTO userDTO) { Optional<User> existingUser = userRepository.findOneByEmail(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userDTO.getLogin()))) { return ResponseEntity.badRequest() .headers( HeaderUtil.createFailureAlert("user-management", "emailexists", "Email already in use")) .body(null); } return userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).map(u -> { userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey()); return new ResponseEntity<String>(HttpStatus.OK); }).orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); }
From source file:com.couchbase.trombi.controllers.CoworkerController.java
@RequestMapping(value = "/{coworkerId}", method = RequestMethod.PATCH) public ResponseEntity<?> patchCoworker(@PathVariable("coworkerId") int id, @RequestBody Map<String, Object> body) { String fullId = CoworkerRepository.PREFIX + id; if (!bucket.exists(fullId)) { return ResponseEntity.notFound().build(); }/*from ww w . j a v a 2 s . c om*/ MutateInBuilder builder = bucket.mutateIn(fullId); if (body.containsKey("name")) { builder.upsert("name", body.get("name"), false); } if (body.containsKey("description")) { builder.upsert("description", body.get("description"), false); } if (body.containsKey("team")) { builder.upsert("team", body.get("team"), false); } if (body.containsKey("skills")) { Iterable<Object> skills = (Iterable<Object>) body.get("skills"); for (Object skill : skills) { builder.arrayAddUnique("skills", skill, false); } } if (body.containsKey("imHandles")) { Map<String, Object> imHandles = (Map<String, Object>) body.get("imHandles"); for (Map.Entry<String, Object> entry : imHandles.entrySet()) { builder.upsert("imHandles." + entry.getKey(), entry.getValue(), true); } } if (body.containsKey("mainLocation")) { Map<String, Object> mainLocation = (Map<String, Object>) body.get("mainLocation"); if (mainLocation.containsKey("name")) { builder.replace("mainLocation.name", mainLocation.get("name")); } if (mainLocation.containsKey("description")) { builder.replace("mainLocation.description", mainLocation.get("description")); } //disallow anything else (coordinates and timezone) if (!mainLocation.containsKey("name") && !mainLocation.containsKey("description")) { return ResponseEntity.badRequest().body("Main location can only have name and description updated, " + "use a different API to switch to a whole new location"); } } if (body.containsKey("lastCheckin")) { return ResponseEntity.badRequest().body("Checkin can only be performed through the dedicated API"); } builder.execute(); Coworker result = repository.findOne(fullId); return ResponseEntity.ok().body(result); }
From source file:com.frequentis.maritime.mcsr.web.rest.AccountResource.java
/** * POST /account : update the current user information. * * @param userDTO the current user information * @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) or 500 (Internal Server Error) if the user couldn't be updated *//*from w w w.j av a 2 s .c om*/ @RequestMapping(value = "/account", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<String> saveAccount(@Valid @RequestBody UserDTO userDTO) { Optional<User> existingUser = userRepository.findFirstByEmail(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userDTO.getLogin()))) { return ResponseEntity.badRequest() .headers( HeaderUtil.createFailureAlert("user-management", "emailexists", "Email already in use")) .body(null); } return userRepository.findFirstByLogin(SecurityUtils.getCurrentUserLogin()).map(u -> { userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(), userDTO.getLangKey()); return new ResponseEntity<String>(HttpStatus.OK); }).orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR)); }
From source file:jp.classmethod.aws.brian.web.TriggerController.java
/** * Create trigger.//from w w w . j av a 2 s .co m * * @param triggerGroupName groupName * @return trigger names * @throws SchedulerException */ @ResponseBody @RequestMapping(value = "/triggers/{triggerGroupName}", method = RequestMethod.POST) public ResponseEntity<?> createTrigger(@PathVariable("triggerGroupName") String triggerGroupName, @RequestBody BrianTriggerRequest triggerRequest) throws SchedulerException { logger.info("createTrigger {}.{}", triggerGroupName, triggerRequest.getTriggerName()); logger.info("{}", triggerRequest); String triggerName = triggerRequest.getTriggerName(); if (Strings.isNullOrEmpty(triggerName)) { return new ResponseEntity<>(new BrianResponse<>(false, "triggerName is not found"), HttpStatus.BAD_REQUEST); } try { TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName); if (scheduler.checkExists(triggerKey)) { String message = String.format("trigger %s.%s already exists.", triggerGroupName, triggerName); return new ResponseEntity<>(new BrianResponse<>(false, message), HttpStatus.CONFLICT); } Trigger trigger = getTrigger(triggerRequest, triggerKey); Date nextFireTime = scheduler.scheduleJob(trigger); logger.info("scheduled {}", triggerKey); SimpleDateFormat df = CalendarUtil.newSimpleDateFormat(TimePoint.ISO8601_FORMAT_UNIVERSAL, Locale.US, TimeZones.UNIVERSAL); Map<String, Object> map = new HashMap<>(); map.put("nextFireTime", df.format(nextFireTime)); return new ResponseEntity<>(new BrianResponse<>(true, "created", map), HttpStatus.CREATED); // TODO return URI } catch (ParseException e) { logger.warn("parse cron expression failed", e); String message = "parse cron expression failed - " + e.getMessage(); return ResponseEntity.badRequest().body(new BrianResponse<>(false, message)); } }