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:com.github.lynxdb.server.api.http.handlers.EpSuggest.java

@RequestMapping(path = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity post(@RequestBody @Valid SuggestRequest _request, Authentication _authentication,
        BindingResult _bindingResult) {//from ww w .j  av  a 2 s .  com

    if (_bindingResult.hasErrors()) {
        ArrayList<String> errors = new ArrayList();
        _bindingResult.getFieldErrors().forEach((FieldError t) -> {
            errors.add(t.getField() + ": " + t.getDefaultMessage());
        });
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, errors.toString(), null).response();
    }

    return response(_request, _authentication);
}

From source file:de.petendi.ethereum.secure.proxy.controller.SecureController.java

@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/{fingerprint}")
public ResponseEntity<EncryptedMessage> post(@PathVariable("fingerprint") String fingerPrint,
        @RequestBody EncryptedMessage encryptedMessage) {

    IO.UnencryptedResponse unencryptedResponse = new IO.UnencryptedResponse() {
        @Override//www . ja v a 2s  .  c o  m
        public byte[] getUnencryptedResponse(byte[] bytes, String s, String s1) {
            return SecureController.this.dispatch(bytes).getBytes();
        }
    };
    try {
        EncryptedMessage encrypted = seccoco.io().dispatch(fingerPrint, encryptedMessage, unencryptedResponse);
        return new ResponseEntity<EncryptedMessage>(encrypted, HttpStatus.OK);
    } catch (IO.RequestException e) {
        HttpStatus status;
        if (e instanceof IO.CertificateNotFoundException) {
            status = HttpStatus.FORBIDDEN;
        } else if (e instanceof IO.SignatureCheckFailedException) {
            status = HttpStatus.UNAUTHORIZED;
        } else if (e instanceof IO.InvalidInputException) {
            status = HttpStatus.BAD_REQUEST;
        } else {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return new ResponseEntity<EncryptedMessage>(status);
    }
}

From source file:org.venice.piazza.servicecontroller.messaging.handlers.DescribeServiceHandlerTest.java

@Test
/**// w w  w .ja  va2 s.co  m
 * Test what happens when a null is sent to register a service
 */
public void testHandleJobRequestNull() {
    PiazzaJobType jobRequest = null;
    ResponseEntity<String> result = dsHandler.handle(jobRequest);
    assertEquals("The response to a null JobRequest update should be null", result.getStatusCode(),
            HttpStatus.BAD_REQUEST);
}

From source file:org.wallride.web.controller.admin.article.ArticleCreateController.java

@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody RestValidationErrorModel bindException(BindException e) {
    logger.debug("BindException", e);
    return RestValidationErrorModel.fromBindingResult(e.getBindingResult(), messageSourceAccessor);
}

From source file:de.steilerdev.myVerein.server.controller.user.UserController.java

@RequestMapping(method = RequestMethod.POST, params = "deviceToken")
public ResponseEntity updateDeviceToken(@RequestParam String deviceToken, @CurrentUser User currentUser) {
    logger.trace("[{}] Updating device token", currentUser);
    if (deviceToken.isEmpty()) {
        logger.warn("[{}] The device token is empty", currentUser);
        return new ResponseEntity(HttpStatus.BAD_REQUEST);
    } else {//from ww w  . j ava2  s .  c om
        if (currentUser.setDeviceTokenBase64Encoded(deviceToken)) {
            logger.info("[{}] Successfully updated device token", currentUser);
            userRepository.save(currentUser);
            return new ResponseEntity(HttpStatus.OK);
        } else {
            logger.warn(
                    "[{}] Unable to update device token, decoded token does not have the correct length of 32 bytes",
                    currentUser);
            return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }
    }
}

From source file:org.trustedanalytics.user.invite.RestErrorHandler.java

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(InvalidOrganizationNameException.class)
public String invalidOrgName(InvalidOrganizationNameException e) throws IOException {
    return e.getMessage();
}

From source file:it.reply.orchestrator.exception.GlobalControllerExceptionHandler.java

/**
 * Bad Request exception handler./*  w  ww .  j  av  a 2s.  c o  m*/
 * 
 * @param ex
 *          the exception
 * @return a {@code ResponseEntity} instance
 */
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public Error handleException(BadRequestException ex) {

    return new Error().withCode(HttpStatus.BAD_REQUEST.value())
            .withTitle(HttpStatus.BAD_REQUEST.getReasonPhrase()).withMessage(ex.getMessage());
}

From source file:org.createnet.raptor.auth.service.controller.RoleController.java

@PreAuthorize("hasAuthority('admin') or hasAuthority('super_admin')")
@RequestMapping(value = { "/role/{roleId}" }, method = RequestMethod.PUT)
@ApiOperation(value = "Update a role", notes = "", response = Role.class, nickname = "updateRole")
public ResponseEntity<?> update(@AuthenticationPrincipal RaptorUserDetailsService.RaptorUserDetails currentUser,
        @PathVariable Long roleId, @RequestBody Role rawRole) {

    if ((rawRole.getName().isEmpty() || rawRole.getName() == null)) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Name property is missing");
    }/*from   w  w w.  j  a  va 2  s  .  c o  m*/

    Role role2 = roleService.getByName(rawRole.getName());
    if (role2 != null) {
        return ResponseEntity.status(HttpStatus.CONFLICT).body(null);
    }

    rawRole.setId(roleId);
    Role role = roleService.update(roleId, rawRole);
    if (role == null) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
    }

    logger.debug("Updated role {}", role.getName());
    return ResponseEntity.ok(role);
}

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

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@PreAuthorize("isAuthenticated() and principal.idPerson == #id")
public ResponseEntity<List<TestData>> retrieveByPersonId(@PathVariable("id") long id) {

    Logger.getLogger("TestDataController.java").log(Level.INFO, "GET on /testdata/" + id);

    List<TestData> data = this.testDataRepository.findByPerson_IdPerson(id);

    if (data != null) {

        Logger.getLogger("TestDataController.java").log(Level.INFO, "Returning data  /testdata/" + id);

        return new ResponseEntity(data, HttpStatus.OK);
    } else {/*from  w  w  w  .  j a v a  2  s .c o m*/

        Logger.getLogger("TestDataController.java").log(Level.INFO, "Data not found");

        return new ResponseEntity(HttpStatus.BAD_REQUEST);

    }

}

From source file:at.ac.tuwien.infosys.ArtifactBuilder.java

@RequestMapping(value = "/build", method = RequestMethod.POST)
public ResponseEntity<String> build(@RequestBody DeviceUpdateRequest updateRequest) {

    logger.info("Got request: " + updateRequest);

    if (updateRequest == null)
        return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);

    updateRequest.setVersion(updateRequest.getVersion().replace(".", "_"));

    ResponseEntity<Component[]> dmsResponse = restTemplate.getForEntity(dmsURL, Component[].class,
            updateRequest.getComponent(), updateRequest.getVersion());

    logger.info("Invoked Component/Dependency-Management and received: " + dmsResponse.getStatusCode());

    if (dmsResponse.getStatusCode() != HttpStatus.OK)
        return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);

    Plan bundle = new Plan(dmsResponse.getBody());

    logger.info("Received following bundle: " + bundle);

    try {// w  w  w. j ava2  s .com
        String idPrefix = updateRequest.getComponent() + "_" + updateRequest.getVersion();

        // search if an image for the respective component and version
        // already exists
        Image image = imageStorage.getUpdate(idPrefix);

        if (image == null) {
            Path imagePath = imageUtil.createImage(bundle, idPrefix);

            // Upload image to image store
            image = imageStorage.storeUpdate(updateRequest.getDeviceIds(), imageUtil.getImageId(),
                    Files.newInputStream(imagePath));

            logger.info("Finished uploading image to image-store");
        } else {
            logger.info("Image already present in image-store, reuse it!");
            if (image.getDeviceIds() == null)
                image.setDeviceIds(updateRequest.getDeviceIds());
        }

        // Invoke device manager to send image
        //
        //         Map<String, Object> map = new HashMap<String, Object>();
        //         map.put("force", updateRequest.isPush());

        ResponseEntity<String> managerResponse = restTemplate.postForEntity(managerURL, image, String.class);

        logger.info("Received request from device-manager: " + managerResponse.getStatusCode());

    } catch (IOException e) {
        e.printStackTrace();
        return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
    } finally {
        if (imageUtil != null)
            try {
                imageUtil.clean();
            } catch (Exception e) {
            }
    }

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