Example usage for org.springframework.http ResponseEntity badRequest

List of usage examples for org.springframework.http ResponseEntity badRequest

Introduction

In this page you can find the example usage for org.springframework.http ResponseEntity badRequest.

Prototype

public static BodyBuilder badRequest() 

Source Link

Document

Create a builder with a HttpStatus#BAD_REQUEST BAD_REQUEST status.

Usage

From source file:com.greglturnquist.springagram.fileservice.s3.ApplicationController.java

@RequestMapping(method = RequestMethod.GET, value = "/files/{filename}")
public ResponseEntity<?> getFile(@PathVariable String filename) throws IOException {

    Resource file = this.fileService.findOne(filename);

    try {/*  www  .  ja va  2s .  com*/
        return ResponseEntity.ok().contentLength(file.contentLength()).contentType(MediaType.IMAGE_JPEG)
                .body(new InputStreamResource(file.getInputStream()));
    } catch (IOException e) {
        return ResponseEntity.badRequest().body("Couldn't process the request");
    }
}

From source file:com.couchbase.trombi.controllers.CoworkerController.java

@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity<?> createCoworker(@RequestBody Map<String, Object> body) {
    String name;//from   ww  w . java  2s  . co m
    String description;
    String team;
    Set<String> skills = new HashSet<>();
    Map<String, String> imHandles;
    Location mainLocation;
    try {
        if (body.containsKey("skills")) {
            skills.addAll((Collection<String>) body.get("skills"));
        }

        imHandles = (Map<String, String>) body.get("imHandles");

        Map<String, Object> mainLocationMap = (Map<String, Object>) body.get("mainLocation");
        Map<String, Object> mainLocationCoord = (Map<String, Object>) mainLocationMap.get("coordinates");
        double x = ((Number) mainLocationCoord.get("x")).doubleValue();
        double y = ((Number) mainLocationCoord.get("y")).doubleValue();
        mainLocation = new Location((String) mainLocationMap.get("name"),
                (String) mainLocationMap.get("description"), (int) mainLocationMap.get("timeZoneOffset"),
                new Point(x, y));

        name = (String) body.get("name");
        description = (String) body.get("description");
        team = (String) body.get("team");

    } catch (Exception e) {
        return ResponseEntity.badRequest().body("Malformed Coworker creation data, error: " + e.toString());
    }

    //generate an ID
    Long sequence = bucket.counter("coworkerSequence", 1, TrombinoscopeApplication.RESERVED_IDS + 1).content();
    String id = CoworkerRepository.PREFIX + sequence.longValue();

    Coworker coworker = new Coworker(id, name, description, team, skills, imHandles, mainLocation, null);

    repository.save(coworker);

    final URI location = ServletUriComponentsBuilder.fromCurrentServletMapping().path("/{id}").build()
            .expand(id).toUri();

    return ResponseEntity.created(location).body(coworker);
}

From source file:io.pivotal.cla.mvc.github.GitHubHooksController.java

/**
 * @param request/*from w w  w  . ja  va 2s .  c o m*/
 * @param body
 * @param cla
 * @param githubEvent
 * @return
 * @throws Exception
 */
@RequestMapping("/github/hooks/pull_request/{cla}")
public ResponseEntity<String> pullRequest(HttpServletRequest request, @RequestBody String body,
        @PathVariable String cla, @RequestHeader("X-GitHub-Event") String githubEvent) throws Exception {

    if (!ACCEPTED_EVENTS.contains(githubEvent)) {
        return ResponseEntity.badRequest()
                .body(String.format("X-Github-Event: %s not acceptable", githubEvent));
    }

    Gson gson = GsonUtils.createGson();
    RepositoryAware payload = gson.fromJson(body, PAYLOAD_TYPES.get(githubEvent));

    PullRequest pullRequest = getPullRequest(payload);

    if (pullRequest == null) {
        return ResponseEntity.badRequest().body("Not related to a Pull request");
    }

    User senderUser = getSender(payload);

    if (senderUser.getLogin().equals(gitHubApi.getGitHubClaUserLogin())) {
        return ResponseEntity.ok("Skipping self-events");
    }

    User user = getPullRequestUser(payload);

    Repository repository = payload.getRepository();
    RepositoryId repoId = RepositoryId
            .createFromId(repository.getOwner().getLogin() + "/" + repository.getName());
    String sha = getPullRequestSha(repoId, pullRequest);
    String gitHubLogin = user.getLogin();

    PullRequestStatus status = new PullRequestStatus();
    status.setGitHubUsername(gitHubLogin);
    status.setPullRequestId(pullRequest.getNumber());
    status.setPullRequestBody(pullRequest.getBody());
    status.setRepoId(repoId.generateId());
    status.setSha(sha);
    String signUrl = UrlBuilder.signUrl().request(request).claName(cla).repositoryId(status.getRepoId())
            .pullRequestId(status.getPullRequestId()).build();
    status.setUrl(signUrl);
    status.setPullRequestState(pullRequest.getState());

    String syncUrl = UrlBuilder.createSyncUrl(request, cla, status.getRepoId(), status.getPullRequestId());
    status.setSyncUrl(syncUrl);

    String faqUrl = UrlBuilder.createAboutUrl(request);
    status.setFaqUrl(faqUrl);

    ClaPullRequestStatusRequest pullRequestStatusRequest = new ClaPullRequestStatusRequest();
    pullRequestStatusRequest.setClaName(cla);
    pullRequestStatusRequest.setCommitStatus(status);
    claService.savePullRequestStatus(pullRequestStatusRequest);

    return ResponseEntity.ok("SUCCESS");
}

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

private ResponseEntity<SerializablePair<Boolean, String>> createOrUpdate(String previousPath,
        String previousName, Extension script, Principal principal) {
    try {//from   w w  w . j  ava2 s  .co  m
        ensureAdmin(principal);
        extensionService.createOrUpdate(previousPath, previousName, script);
        return ResponseEntity.ok(SerializablePair.of(true, null));
    } catch (Throwable t) {
        return ResponseEntity.badRequest().body(SerializablePair.of(false, t.getMessage()));
    }
}

From source file:com.greglturnquist.springagram.fileservice.mongodb.ApplicationController.java

@RequestMapping(method = RequestMethod.GET, value = "/files/{filename}")
public ResponseEntity<?> getFile(@PathVariable String filename) {

    GridFsResource file = this.fileService.findOne(filename);

    if (file == null) {
        return ResponseEntity.notFound().build();
    }//from w w  w . j a v  a  2  s  . c o m

    try {
        return ResponseEntity.ok().contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType(file.getContentType()))
                .body(new InputStreamResource(file.getInputStream()));
    } catch (IOException e) {
        return ResponseEntity.badRequest().body("Couldn't process the request");
    }
}

From source file:co.bluepass.web.rest.ClubResource.java

/**
 * Create response entity./* w w w  . j  av a2  s  .  co m*/
 *
 * @param dto the dto
 * @return the response entity
 * @throws URISyntaxException the uri syntax exception
 */
@RequestMapping(value = "/clubs", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> create(@Valid @RequestBody ClubDTO dto) throws URISyntaxException {
    log.debug("REST request to save Club Information : {}", dto);
    if (dto.getId() != null) {
        return ResponseEntity.badRequest()
                .header("Failure", "?? ? ?  .").build();
    }

    CommonCode category = dto.getCategory();

    Club club = new Club(null, 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());

    User loginUser = userRepository.findOneByEmail(SecurityUtils.getCurrentLogin());
    club.setCreator(loginUser);

    Club saved = clubRepository.save(club);

    List<CommonCode> featureCodes = null;
    if (dto.getFeatures() != null) {
        //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(saved, featureCode));
            }
            featureRepository.save(features);
        }
    }

    try {
        if (StringUtils.isNotEmpty(saved.getOldAddress())) {
            addressIndexRepository.save(new AddressIndex(saved.getOldAddress()));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return ResponseEntity.created(new URI("/api/clubs/" + club.getId())).build();
}

From source file:org.openlmis.fulfillment.web.TransferPropertiesController.java

/**
 * Allows creating new transfer properties.
 * If the id is specified, it will be ignored.
 *
 * @param properties A transfer properties bound to the request body
 * @return ResponseEntity containing the created transfer properties
 *///from ww w.  j ava 2 s.  c o  m
@RequestMapping(value = "/transferProperties", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity create(@RequestBody TransferPropertiesDto properties) {

    LOGGER.debug("Checking right to create transfer properties");
    permissionService.canManageSystemSettings();

    LOGGER.debug("Creating new Transfer Properties");

    TransferProperties entity = TransferPropertiesFactory.newInstance(properties);

    List<Message.LocalizedMessage> errors = validate(entity);
    if (isNotTrue(errors.isEmpty())) {
        return ResponseEntity.badRequest().body(errors);
    }

    properties.setId(null);
    TransferProperties saved = transferPropertiesService.save(entity);

    LOGGER.debug("Created new Transfer Properties with id: {}", saved.getId());

    return ResponseEntity.status(HttpStatus.CREATED)
            .body(TransferPropertiesFactory.newInstance(saved, exporter));
}

From source file:com.organization.projectname.controller.AuthenticationController.java

@RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET)
public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) throws Exception {

    userService.isIPOK();/*  w  w w  .jav a 2s. co  m*/

    String token = request.getHeader(tokenHeader);
    String username = jwtTokenUtil.getUsernameFromToken(token);
    User user = (User) userService.loadUserByUsername(username);

    if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
        String refreshedToken = jwtTokenUtil.refreshToken(token);
        return ResponseEntity.ok(new AuthenticationResponse(refreshedToken));
    } else {
        return ResponseEntity.badRequest().body(null);
    }
}

From source file:com.couchbase.trombi.controllers.CoworkerController.java

@RequestMapping(value = "/{coworkerId}", method = RequestMethod.PUT)
public ResponseEntity<?> updateCoworker(@PathVariable("coworkerId") int id, @RequestBody Coworker body) {
    String fullId = CoworkerRepository.PREFIX + id;
    if (!fullId.equals(body.getId())) {
        return ResponseEntity.badRequest().body(body);
    }//from  w ww  .  ja v a2 s .  co m
    if (!bucket.exists(fullId)) {
        return ResponseEntity.notFound().build();
    }
    repository.save(body);
    return ResponseEntity.ok(body);
}

From source file:ch.ge.ve.protopoc.controller.impl.AuthenticationController.java

@Override
public ResponseEntity<?> renewAuthenticationToken(HttpServletRequest request) {
    String token = request.getHeader(tokenHeader);

    if (jwtTokenUtil.canTokenBeRefreshed(token)) {
        String refreshedToken = jwtTokenUtil.refreshToken(token);
        return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
    } else {/* w ww. j a  v a 2 s  .co m*/
        return ResponseEntity.badRequest().body(null);
    }
}