Example usage for org.springframework.http HttpStatus CREATED

List of usage examples for org.springframework.http HttpStatus CREATED

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus CREATED.

Prototype

HttpStatus CREATED

To view the source code for org.springframework.http HttpStatus CREATED.

Click Source Link

Document

201 Created .

Usage

From source file:org.nekorp.workflow.backend.controller.imp.RegistroCostoControllerImp.java

@Override
@RequestMapping(method = RequestMethod.POST)
public void crearRegistro(@PathVariable final Long idServicio, @Valid @RequestBody final RegistroCosto dato,
        final HttpServletResponse response) {
    dato.setId(null);/*from w  ww  . j a  v  a 2s  . c  o m*/
    if (!idServicioValido(idServicio)) {
        response.setStatus(HttpStatus.NOT_FOUND.value());
        return;
    }
    this.registroCostoDAO.guardar(idServicio, dato);
    response.setStatus(HttpStatus.CREATED.value());
    response.setHeader("Location", "/servicios/" + idServicio + "/costo/registros/" + dato.getId());
}

From source file:com.wisemapping.rest.AdminController.java

@ApiOperation("Note: Administration permissions required.")
@RequestMapping(method = RequestMethod.POST, value = "admin/users", consumes = { "application/xml",
        "application/json" }, produces = { "application/json", "application/xml" })
@ResponseStatus(value = HttpStatus.CREATED)
public void createUser(@RequestBody @ApiParam(required = true) RestUser user, HttpServletResponse response)
        throws WiseMappingException {
    if (user == null) {
        throw new IllegalArgumentException("User could not be found");
    }/*from ww w . ja v  a  2s . c o  m*/

    // User already exists ?
    final String email = user.getEmail();
    if (userService.getUserBy(email) != null) {
        throw new IllegalArgumentException("User already exists with this email.");
    }

    // Run some other validations ...
    final User delegated = user.getDelegated();
    final String lastname = delegated.getLastname();
    if (lastname == null || lastname.isEmpty()) {
        throw new IllegalArgumentException("lastname can not be null");
    }

    final String firstName = delegated.getFirstname();
    if (firstName == null || firstName.isEmpty()) {
        throw new IllegalArgumentException("firstname can not be null");
    }

    // Finally create the user ...
    delegated.setAuthenticationType(AuthenticationType.DATABASE);
    userService.createUser(delegated, false, true);
    response.setHeader("Location", "/service/admin/users/" + user.getId());
}

From source file:gob.mx.salud.api.util.ResponseWrapper.java

/**
 * Genera una respuesta exitosa para peticiones <b>POST</b>.
 * @param data {@code T}// www  .  j a va2 s .c  om
 * @return {@code ResponseWrapper<T>}
 */
public ResponseWrapper<T> successPOST(T data) {
    success(ResponseWrapper.SUCCESS, HttpStatus.CREATED.value(), data);
    return this;
}

From source file:com.orange.cepheus.cep.controller.AdminController.java

@RequestMapping(value = "/config", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public synchronized ResponseEntity<?> configuration(@Valid @RequestBody final Configuration configuration)
        throws ConfigurationException, PersistenceException {
    logger.info("Update configuration");

    String configurationId = TenantFilter.DEFAULT_TENANTID;
    if (tenantScope != null) {
        configurationId = tenantScope.getConversationId();

        // Force tenant information to configuration
        injectTenant(configuration);// ww  w  .  j a  v  a2  s  .  co  m
    }

    /*
     * Try to apply a new configuration, in case of configuration error
     * try to restore the previous configuration if any
     */
    final Configuration previousConfiguration = complexEventProcessor.getConfiguration();
    try {
        complexEventProcessor.setConfiguration(configuration);
        eventMapper.setConfiguration(configuration);
        subscriptionManager.setConfiguration(configuration);
        persistence.saveConfiguration(configurationId, configuration);
    } catch (ConfigurationException e) {
        // try to restore previous configuration
        if (previousConfiguration != null) {
            complexEventProcessor.restoreConfiguration(previousConfiguration);
            eventMapper.setConfiguration(previousConfiguration);
            subscriptionManager.setConfiguration(previousConfiguration);
        }
        throw e;
    }

    return new ResponseEntity<>(HttpStatus.CREATED);
}

From source file:org.springsource.restbucks.training.payment.web.PaymentController.java

/**
 * Accepts a payment for an {@link Order}
 * //  w ww  .  j a va2s  .com
 * @param order the {@link Order} to process the payment for. Retrieved from the path variable and converted into an
 *          {@link Order} instance by Spring Data's {@link DomainClassConverter}. Will be {@literal null} in case no
 *          {@link Order} with the given id could be found.
 * @param number the {@link CreditCardNumber} unmarshalled from the request payload.
 * @return
 */
@RequestMapping(value = PaymentLinks.PAYMENT, method = RequestMethod.PUT)
ResponseEntity<PaymentResource> submitPayment(@PathVariable("id") Order order,
        @RequestBody CreditCardNumber number) {

    if (order == null || order.isPaid()) {
        return new ResponseEntity<PaymentResource>(HttpStatus.NOT_FOUND);
    }

    CreditCardPayment payment = paymentService.pay(order, number);

    PaymentResource resource = new PaymentResource(order.getPrice(), payment.getCreditCard());
    resource.add(entityLinks.linkToSingleResource(order));

    return new ResponseEntity<PaymentResource>(resource, HttpStatus.CREATED);
}

From source file:web.UsersRESTController.java

/**
 * Adds a user to the database through REST API
 * @param user/*from  w ww.  j ava  2  s .c om*/
 * @param ucBuilder
 * @return
 */
@RequestMapping(value = "/api/users/", method = RequestMethod.POST)
public ResponseEntity<Void> addUser(@RequestBody Users user, UriComponentsBuilder ucBuilder) {
    dao.addUser(user);
    //returns newly added User info
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/api/users/userinfo/{id}").buildAndExpand(user.getUserId()).toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}

From source file:edu.eci.cosw.restcontrollers.RestControladorPublicarEstablecimiento.java

/**
 * /* w  w  w .  j  a v  a  2  s  .  co  m*/
 * @param nombre del establecimiento a habilitar
 * @return respuesta a la operacion realizada de habilitacion de establecimiento
 */
@RequestMapping(value = "/inhabilitados/{id}", method = RequestMethod.GET)
public ResponseEntity<?> habilitarEstablecimiento(@PathVariable int id) {
    HttpStatus hs;
    String mens = "";
    try {
        logica.habilitarEstablecimiento(id);
        hs = HttpStatus.CREATED;
    } catch (Exception ex) {
        mens = ex.getMessage();
        hs = HttpStatus.CONFLICT;
    }
    return new ResponseEntity<>(mens, hs);
}

From source file:org.openmrs.module.dataexchange.web.controller.DataExchangeController.java

private ResponseEntity<String> exportConcepts(Set<Integer> ids) throws IOException, FileNotFoundException {
    File tempFile = null;/*from   ww  w .  ja v a 2  s  .c o  m*/
    FileInputStream tempIN = null;
    String xml;
    try {
        tempFile = File.createTempFile("concepts", ".xml");

        if (ids.isEmpty()) {
            dataExporter.exportAllConcepts(tempFile.getPath());
        } else {
            dataExporter.exportConcepts(tempFile.getPath(), ids);
        }

        tempIN = new FileInputStream(tempFile);

        xml = IOUtils.toString(tempIN, "UTF-8");

        tempIN.close();
    } finally {
        IOUtils.closeQuietly(tempIN);

        if (tempFile != null) {
            tempFile.delete();
        }
    }

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentType(org.springframework.http.MediaType.APPLICATION_XML);
    return new ResponseEntity<String>(xml, responseHeaders, HttpStatus.CREATED);
}

From source file:de.zib.gndms.gndmc.dspace.Test.SubspaceClientTest.java

@Test(groups = { "subspaceServiceTest" }, dependsOnMethods = { "testCreateSubspace" })
public void testCreateSliceKind() {
    final ResponseEntity<Specifier<Void>> sliceKind = subspaceClient.createSliceKind(subspaceId, sliceKindId,
            sliceKindConfig, admindn);//w ww  .j a  v a 2s .  c  o m
    Assert.assertNotNull(sliceKind);
    Assert.assertEquals(sliceKind.getStatusCode(), HttpStatus.CREATED);

    final ResponseEntity<List<Specifier<Void>>> listResponseEntity = subspaceClient.listSliceKinds(subspaceId,
            admindn);
    final List<Specifier<Void>> specifierList = listResponseEntity.getBody();

    for (Specifier<Void> s : specifierList) {
        if (!s.getUriMap().containsKey(UriFactory.SLICE_KIND))
            continue;
        if (s.getUriMap().get(UriFactory.SLICE_KIND).equals(sliceKindId))
            return;
    }

    throw new IllegalStateException(
            "The created SliceKind " + sliceKindId + " could not be found in SliceKindListing");
}

From source file:ch.wisv.areafiftylan.teams.controller.TeamRestController.java

/**
 * The method to handle POST requests on the /teams endpoint. This creates a new team. Users can only create new
 * Teams with themselves as Captain. Admins can also create Teams with other Users as Captain.
 *
 * @param teamDTO Object containing the Team name and Captain username. When coming from a user, username should
 *                equal their own username.
 * @param auth    Authentication object from Spring Security
 *
 * @return Return status message of the operation
 *///from  w  w w.ja va2 s. c  om
@PreAuthorize("isAuthenticated() and @currentUserServiceImpl.hasAnyTicket(principal)")
@JsonView(View.Public.class)
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<?> add(@Validated @RequestBody TeamDTO teamDTO, Authentication auth) {
    if (teamService.teamnameUsed(teamDTO.getTeamName())) {
        return createResponseEntity(HttpStatus.CONFLICT,
                "Team with name \"" + teamDTO.getTeamName() + "\" already exists.");
    }

    Team team;
    // Users can only create teams with themselves as Captain
    if (auth.getAuthorities().contains(Role.ROLE_ADMIN)) {
        team = teamService.create(teamDTO.getCaptainUsername(), teamDTO.getTeamName());
    } else {
        // If the DTO contains another username as the the current user, return an error.
        if (!auth.getName().equalsIgnoreCase(teamDTO.getCaptainUsername())) {
            return createResponseEntity(HttpStatus.BAD_REQUEST,
                    "Can not create team with another user as Captain");
        }
        team = teamService.create(auth.getName(), teamDTO.getTeamName());
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(team.getId()).toUri());

    return createResponseEntity(HttpStatus.CREATED, httpHeaders,
            "Team successfully created at " + httpHeaders.getLocation(), team);
}