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.osiam.addons.selfadministration.registration.RegistrationController.java

@RequestMapping(method = RequestMethod.POST)
public String register(@Valid @ModelAttribute final RegistrationUser registrationUser,
        final BindingResult bindingResult, final Model model, final HttpServletRequest request,
        final HttpServletResponse response) {

    userValidator.validate(registrationUser, bindingResult);
    if (bindingResult.hasErrors()) {
        model.addAttribute("allowedFields", registrationService.getAllAllowedFields());
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return "registration";
    }//from w w  w . j  a v a  2  s.  com

    User user = registrationService.saveRegistrationUser(registrationUser);
    registrationService.sendRegistrationEmail(user, request);

    model.addAttribute("user", user);

    response.setStatus(HttpStatus.CREATED.value());
    return "registrationSuccess";
}

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

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

From source file:com.hp.autonomy.frontend.find.idol.view.IdolViewController.java

@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ModelAndView handleViewNoReferenceFieldException(final ViewNoReferenceFieldException e,
        final HttpServletRequest request, final ServletResponse response) {
    response.reset();/*from   w w  w  . j a  v a2s. co  m*/

    final String reference = e.getReference();
    final String referenceField = configService.getConfig().getViewConfig().getReferenceField();

    log.info(Markers.AUDIT, "TRIED TO VIEW DOCUMENT WITH REFERENCE {} BUT THE REFERENCE FIELD {} WAS MISSING",
            reference, referenceField);

    return controllerUtils.buildErrorModelAndView(new ErrorModelAndViewInfo.Builder().setRequest(request)
            .setMainMessageCode("error.documentNoReferenceField")
            .setSubMessageCode("error.documentNoReferenceFieldExtended")
            .setSubMessageArguments(new Object[] { reference, referenceField })
            .setStatusCode(HttpStatus.BAD_REQUEST.value()).setContactSupport(true).setException(e).build());
}

From source file:eu.freme.broker.integration_tests.UserControllerTest.java

@Test
public void testUserSecurity() throws UnirestException {

    String username = "myuser";
    String password = "mypassword";

    logger.info("create user");
    logger.info(baseUrl + "/user");
    HttpResponse<String> response = Unirest.post(baseUrl + "/user").queryString("username", username)
            .queryString("password", password).asString();
    assertTrue(response.getStatus() == HttpStatus.OK.value());
    String responseUsername = new JSONObject(response.getBody()).getString("name");
    assertTrue(username.equals(responseUsername));

    logger.info("create user with dublicate username - should not work, exception is ok");
    loggerIgnore("eu.freme.broker.exception.BadRequestException");
    response = Unirest.post(baseUrl + "/user").queryString("username", username)
            .queryString("password", password).asString();
    assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST.value());
    loggerUnignore("eu.freme.broker.exception.BadRequestException");

    logger.info("create users with invalid usernames - should not work");
    loggerIgnore("eu.freme.broker.exception.BadRequestException");
    response = Unirest.post(baseUrl + "/user").queryString("username", "123").queryString("password", password)
            .asString();//from  w ww.jav a  2s  .  c  om
    assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST.value());

    response = Unirest.post(baseUrl + "/user").queryString("username", "*abc").queryString("password", password)
            .asString();
    assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST.value());

    response = Unirest.post(baseUrl + "/user").queryString("username", adminUsername)
            .queryString("password", password).asString();
    assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST.value());

    response = Unirest.post(baseUrl + "/user").queryString("username", "").queryString("password", password)
            .asString();
    assertTrue(response.getStatus() == HttpStatus.BAD_REQUEST.value());
    loggerUnignore("eu.freme.broker.exception.BadRequestException");

    logger.info("login with bad password should fail");
    loggerIgnore(accessDeniedExceptions);
    response = Unirest.post(baseUrl + BaseRestController.authenticationEndpoint)
            .header("X-Auth-Username", username).header("X-Auth-Password", password + "xyz").asString();
    assertTrue(response.getStatus() == HttpStatus.UNAUTHORIZED.value());
    loggerUnignore(accessDeniedExceptions);

    logger.info("login with new user / create token");
    response = Unirest.post(baseUrl + BaseRestController.authenticationEndpoint)
            .header("X-Auth-Username", username).header("X-Auth-Password", password).asString();
    assertTrue(response.getStatus() == HttpStatus.OK.value());
    String token = new JSONObject(response.getBody()).getString("token");
    assertTrue(token != null);
    assertTrue(token.length() > 0);

    logger.info("delete user without providing credentials - should fail, exception is ok");
    loggerIgnore(accessDeniedExceptions);
    response = Unirest.delete(baseUrl + "/user/" + username).asString();
    assertTrue(response.getStatus() == HttpStatus.UNAUTHORIZED.value());
    loggerUnignore(accessDeniedExceptions);

    logger.info("create a 2nd user");
    String otherUsername = "otheruser";
    response = Unirest.post(baseUrl + "/user").queryString("username", otherUsername)
            .queryString("password", password).asString();
    assertTrue(response.getStatus() == HttpStatus.OK.value());
    String responseOtherUsername = new JSONObject(response.getBody()).getString("name");
    assertTrue(otherUsername.equals(responseOtherUsername));

    logger.info("delete other user should fail");
    loggerIgnore(accessDeniedExceptions);
    response = Unirest.delete(baseUrl + "/user/" + otherUsername).header("X-Auth-Token", token).asString();
    assertTrue(response.getStatus() == HttpStatus.UNAUTHORIZED.value());
    loggerUnignore(accessDeniedExceptions);

    logger.info("cannot do authenticated call with username / password, only token should work");
    loggerIgnore(accessDeniedExceptions);
    response = Unirest.delete(baseUrl + "/user/" + username).header("X-Auth-Username", username)
            .header("X-Auth-Password", password).asString();
    assertTrue(response.getStatus() == HttpStatus.UNAUTHORIZED.value());
    loggerUnignore(accessDeniedExceptions);

    logger.info("get user information");
    response = Unirest.get(baseUrl + "/user/" + username).header("X-Auth-Token", token).asString();
    assertTrue(response.getStatus() == HttpStatus.OK.value());
    responseUsername = new JSONObject(response.getBody()).getString("name");
    assertTrue(responseUsername.equals(username));

    logger.info("delete own user - should work");
    response = Unirest.delete(baseUrl + "/user/" + username).header("X-Auth-Token", token).asString();
    assertTrue(response.getStatus() == HttpStatus.NO_CONTENT.value());

}

From source file:plbtw.klmpk.barang.hilang.controller.KategoriBarangController.java

@RequestMapping(method = RequestMethod.PUT, produces = "application/json")
public CustomResponseMessage updateKategoriBarang(@RequestBody KategoriBarangRequest kategoriBarangRequest) {
    try {//from   w  w w. ja v a2s.c  om
        KategoriBarang kategoriBarang = kategoriBarangService.getKategoriBarang(kategoriBarangRequest.getId());
        kategoriBarang.setJenis(kategoriBarangRequest.getJenis());
        kategoriBarangService.updateKategoriBarang(kategoriBarang);
        return new CustomResponseMessage(HttpStatus.CREATED, "Update Successfull");
    } catch (Exception ex) {
        return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.toString());
    }
}

From source file:com.hyphenated.card.controller.ExceptionController.java

/**
 * MissingServletRequestParameterException handler.  This exception will occur whenever
 * a controller method does not receive a required request parameter.
 * @param e Exception being thrown/*w ww  .  j a  v a  2s . c  o  m*/
 * @return JSON Error messages specific to the missing parameter exception.
 */
@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody Map<String, String> handleBadParameterExcpetion(
        MissingServletRequestParameterException e) {
    Map<String, String> error = new HashMap<String, String>();
    error.put("error", "Required parameter not present.");
    error.put("errorDetails",
            "The parameter " + e.getParameterName() + " is required and not present in the request.");
    log.error("Error: " + e.getMessage());
    return error;
}

From source file:com.github.lynxdb.server.api.http.handlers.EpUser.java

@RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity createUser(Authentication _authentication, @RequestBody @Valid UserCreationRequest _ucr,
        BindingResult _bindingResult) {//from w  ww  .  j  av a 2 s.  co  m

    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()).response();
    }

    User u = new User(_ucr);

    if (users.create(u)) {
        return ResponseEntity.ok(u);
    } else {
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, "User already exists").response();
    }
}

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

@Click
@Background/*from   w  w  w .j a va2s  .  c  om*/
void changePassword() {
    if (!validate()) {
        return;
    }

    showChangePasswordPending();

    try {
        final ChangePasswordRequest requestDto = new ChangePasswordRequest(currentPassword.getValue(),
                newPassword.getValue());
        userService.changePassword(requestDto);
        onPasswordChanged(requestDto);
    } catch (HttpStatusCodeException e) {
        hideChangePasswordPending();
        if (e.getStatusCode() == HttpStatus.BAD_REQUEST || e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            showWarningDialog(R.string.change_password_old_invalid);
            return;
        }

        showWarningDialog(R.string.change_password_error);
    } catch (Exception e) {
        hideChangePasswordPending();
        showWarningDialog(R.string.change_password_error);
    }
}

From source file:com.envision.envservice.rest.EvaluationResource.java

/**
 * ??/*from ww w  .  j a  v  a 2s  . c o  m*/
 * 
 * */
@POST
@Path("/addEvaluation")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addEvaluation(EvaluationBo evaluationBo) throws Exception {
    HttpStatus status = HttpStatus.CREATED;
    String response = StringUtils.EMPTY;
    if (!checkParam(evaluationBo)) {
        status = HttpStatus.BAD_REQUEST;
        response = FailResult.toJson(Code.PARAM_ERROR, "?");
    } else {
        response = evaluationService.addEvaluation(evaluationBo).toJSONString();
    }
    return Response.status(status.value()).entity(response).build();
}

From source file:br.upe.community.ui.ControllerDoacao.java

@RequestMapping(value = "/interessadoDoacao", produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<?> interesseDoacao(String email, long id) {

    try {/*from   w  w w .ja v a2s. com*/
        fachada.interesseDoacao(email, id);
        return new ResponseEntity<String>(HttpStatus.OK);
    } catch (UsuarioInexistenteException e) {
        return new ResponseEntity<UsuarioInexistenteException>(e, HttpStatus.BAD_REQUEST);
    } catch (ProprioUsuarioAnunciadorException ex) {
        return new ResponseEntity<ProprioUsuarioAnunciadorException>(ex, HttpStatus.BAD_REQUEST);
    } catch (DoacaoJaRealizadaException ex) {
        return new ResponseEntity<DoacaoJaRealizadaException>(ex, HttpStatus.BAD_REQUEST);
    }
}