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.venice.piazza.servicecontroller.messaging.handlers.DeleteServiceHandlerTest.java

/**
 * Test that the handle method returns null
 *//*from   w w w  . j  a  v  a 2s .  co  m*/
@Test
public void testHandleJobRequestNull() {
    PiazzaJobType jobRequest = null;
    //Mockito.doNothing().when(loggerMock).log(Mockito.anyString(), Severity.INFORMATIONAL);
    ResponseEntity<String> result = dhHandler.handle(jobRequest);

    assertEquals("The response to a null JobRequest Deletion should be null", result.getStatusCode(),
            HttpStatus.BAD_REQUEST);
}

From source file:net.maritimecloud.identityregistry.controllers.EntityController.java

/**
 * Creates a new Entity// www. j a v  a 2  s  .c  o  m
 *
 * @return a reply...
 * @throws McBasicRestException
 */
protected ResponseEntity<T> createEntity(HttpServletRequest request, String orgMrn, T input)
        throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being created belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        input.setIdOrganization(org.getId());
        try {
            T newEntity = this.entityService.save(input);
            return new ResponseEntity<>(newEntity, HttpStatus.OK);
        } catch (DataIntegrityViolationException e) {
            throw new McBasicRestException(HttpStatus.CONFLICT, e.getRootCause().getMessage(),
                    request.getServletPath());
        }
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:io.getlime.security.powerauth.rest.api.spring.exception.PowerAuthExceptionHandler.java

/**
 * Handle PowerAuthSecureVaultException exceptions.
 * @param ex Exception instance.//from   www .  ja  v a  2 s  .  c o  m
 * @return Error response.
 */
@ExceptionHandler(value = PowerAuthSecureVaultException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public @ResponseBody PowerAuthApiResponse<ErrorModel> handleSecureVaultException(Exception ex) {
    PowerAuthSecureVaultException paex = (PowerAuthSecureVaultException) ex;
    Logger.getLogger(PowerAuthExceptionHandler.class.getName()).log(Level.SEVERE, paex.getMessage(), paex);
    ErrorModel error = new ErrorModel(paex.getDefaultCode(), paex.getMessage());
    return new PowerAuthApiResponse<>(PowerAuthApiResponse.Status.ERROR, error);
}

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

@RequestMapping(method = RequestMethod.DELETE, produces = "application/json")
public CustomResponseMessage deleteRole(@RequestBody RoleRequest roleRequest) {
    try {/* ww  w.jav a 2  s . c  om*/
        roleService.deleteRole(roleRequest.getId());
        return new CustomResponseMessage(HttpStatus.CREATED, "Detele Successfull");
    } catch (Exception ex) {
        return new CustomResponseMessage(HttpStatus.BAD_REQUEST, ex.toString());
    }
}

From source file:de.hska.ld.core.controller.LogEntryController.java

@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.POST)
@Transactional//from ww w .j  a  v  a2  s  . c om
public Callable addClientLogEntry(List<String> values) {
    return () -> {
        try {
            LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(Core.currentUser().getEmail()));
            values.forEach(v -> {
                String[] splittedValue = v.split("###");
                String key = splittedValue[0];
                String value = splittedValue[1];
                LoggingContext.put(key, EscapeUtil.escapeJsonForLogging(value));
            });
            Logger.trace("Client-side logging event.");
            return new ResponseEntity<>(HttpStatus.OK);
        } catch (Exception e) {
            Logger.error(e);
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } finally {
            LoggingContext.clear();
        }
    };
}

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

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

From source file:br.com.modoagil.asr.rest.security.UserWebService.java

/**
 * Busca por usurio pelo email fornecido
 *
 * @param email/*from   w  w w  . ja  v a 2 s  . c  om*/
 *            email a ser consultado
 * @return {@link Usuario}
 */
@RequestMapping(value = WebServicesURL.URL_USUARIO_FIND_EMAIL + "/{email}", method = { GET,
        POST }, produces = APPLICATION_JSON)
public Response<User> findUsuarioByEmail(@PathVariable("email") final String email) {
    Response<User> response;
    getLogger().debug("buscando usurio pelo email '" + email + "'");
    try {
        final User usuario = getRepository().findByEmailIgnoreCase(email);
        if (usuario != null) {
            response = new ResponseBuilder<User>().success(true).data(usuario)
                    .message(String.format(ResponseMessages.FIND_MESSAGE, usuario.getId()))
                    .status(HttpStatus.OK).build();
            getLogger().debug("sucesso ao buscar usurio pelo email '" + email + "'");
        } else {
            response = new ResponseBuilder<User>().success(true)
                    .message(String.format("Usurio com email %s no foi encontrado", email))
                    .status(HttpStatus.OK).build();
            getLogger().debug("no foi encontrado usurio com email '" + email + "'");
        }
    } catch (final Exception e) {
        final String message = ExceptionUtils.getRootCauseMessage(e);
        response = new ResponseBuilder<User>().success(false).message(message).status(HttpStatus.BAD_REQUEST)
                .build();
        getLogger().error("erro ao buscar usurio pelo email '" + email + "'", e);
    }
    return response;
}

From source file:org.ow2.proactive.procci.rest.SwarmRest.java

@RequestMapping(value = "{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResourceRendering> getSwarm(@PathVariable("id") String id) {
    logger.debug("Get Swarm " + id);
    try {/*from w w  w.j ava  2 s.  c  o m*/
        return instanceService.getEntity(id, transformerManager.getTransformerProvider(TransformerType.SWARM))
                .map(swar -> new ResponseEntity<>(((Swarm) swar).getRendering(), HttpStatus.OK))
                .orElse(new ResponseEntity(HttpStatus.NOT_FOUND));
    } catch (ClientException e) {
        logger.error(this.getClass().getName(), e);
        return new ResponseEntity(e.getJsonError(), HttpStatus.BAD_REQUEST);
    } catch (ServerException e) {
        logger.error(this.getClass().getName(), e);
        return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:cn.aozhi.songify.functional.rest.TaskRestFT.java

@Test
public void invalidInput() {

    // create// ww w  .  ja v a  2s. c  o  m
    Task titleBlankTask = new Task();
    try {
        restTemplate.postForLocation(resourceUrl, titleBlankTask);
        fail("Create should fail while title is blank");
    } catch (HttpStatusCodeException e) {
        assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
        Map messages = jsonMapper.fromJson(e.getResponseBodyAsString(), Map.class);
        assertThat(messages).hasSize(1);
        assertThat(messages.get("title")).isIn("may not be empty", "?");
    }

    // update
    titleBlankTask.setId(1L);
    try {
        restTemplate.put(resourceUrl + "/1", titleBlankTask);
        fail("Update should fail while title is blank");
    } catch (HttpStatusCodeException e) {
        assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
        Map messages = jsonMapper.fromJson(e.getResponseBodyAsString(), Map.class);
        assertThat(messages).hasSize(1);
        assertThat(messages.get("title")).isIn("may not be empty", "?");
    }
}

From source file:org.openlmis.fulfillment.web.errorhandler.ServiceErrorHandling.java

@ExceptionHandler(ReportingException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody//from  ww w  . ja v  a 2 s . c om
public Message.LocalizedMessage handlerReportingException(ReportingException ex) {
    return logErrorAndRespond("Reporting error", ex);
}