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:com.tamnd2.basicwebapp.rest.mvc.AccountController.java

@RequestMapping(method = RequestMethod.POST)
@PreAuthorize("permitAll")
public ResponseEntity<AccountResource> createAccount(@RequestBody AccountResource sentAccount) {
    try {/*w  ww .j  a v  a 2 s.com*/
        Account createdAccount = accountService.createAccount(sentAccount.toAccount());
        AccountResource res = new AccountResourceAsm().toResource(createdAccount);
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(URI.create(res.getLink("self").getHref()));
        return new ResponseEntity<AccountResource>(res, headers, HttpStatus.CREATED);
    } catch (AccountExistException exception) {
        throw new ConflictException(exception);
    }
}

From source file:io.spring.initializr.actuate.stat.ProjectGenerationStatPublisherTests.java

@Test
public void recoverFromError() {
    ProjectRequest request = createProjectRequest();

    this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
            .andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));

    this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
            .andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));

    this.mockServer.expect(requestTo("http://example.com/elastic/initializr/request"))
            .andExpect(method(HttpMethod.POST))
            .andRespond(withStatus(HttpStatus.CREATED).body(mockResponse(UUID.randomUUID().toString(), true))
                    .contentType(MediaType.APPLICATION_JSON));

    this.statPublisher.handleEvent(new ProjectGeneratedEvent(request));
    this.mockServer.verify();
}

From source file:com.appglu.impl.CrudTemplateTest.java

@Test
public void create() {
    mockServer.expect(requestTo("http://localhost/appglu/v1/tables/user")).andExpect(method(HttpMethod.POST))
            .andExpect(header("Content-Type", jsonMediaType.toString()))
            .andExpect(content().string(compactedJson("data/crud_row_relationships")))
            .andRespond(withStatus(HttpStatus.CREATED).body(compactedJson("data/crud_create_response"))
                    .headers(responseHeaders));

    Row row = row();// w  w w.  j a  va  2s .c  o  m

    Object id = crudOperations.create("user", row);
    Assert.assertEquals(8, id);

    mockServer.verify();
}

From source file:com.swcguild.blacksmithblogcapstone.controller.BlackSmithController.java

@RequestMapping(value = "/comment", method = RequestMethod.POST)
@ResponseBody/*from   w w  w  .  j ava 2  s.  c o  m*/
@ResponseStatus(HttpStatus.CREATED)
public Comment addComment(@RequestBody Comment comment) {
    return dao.addComment(comment);
}

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

@Override
@RequestMapping(method = RequestMethod.POST)
public void crearServicio(@Valid @RequestBody final Servicio servicio, final HttpServletResponse response) {
    servicio.setId(null);//  w w  w. j a  v  a 2s  .c om
    this.servicioDAO.guardar(servicio);
    //TODO el evento que marca la hora en la que se creo el servicio podria generarse aqui y no en el cliente.
    //bitacoraDAO.guardar(servicio.getId(), new LinkedList<Evento>());
    response.setStatus(HttpStatus.CREATED.value());
    response.setHeader("Location", "/servicios/" + servicio.getId());
}

From source file:ch.wisv.areafiftylan.products.controller.OrderRestController.java

/**
 * When a User does a POST request to /orders, a new Order is created. The requestbody is a TicketDTO, so an order
 * always contains at least one ticket. Optional next tickets should be added to the order by POSTing to the
 * location provided./*from  w  ww.j a v  a 2  s .co m*/
 *
 * @param auth      The User that is currently logged in
 * @param ticketDTO Object containing information about the Ticket that is being ordered.
 *
 * @return A message informing about the result of the request
 */
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/orders", method = RequestMethod.POST)
@JsonView(View.OrderOverview.class)
public ResponseEntity<?> createOrder(Authentication auth, @RequestBody @Validated TicketDTO ticketDTO) {
    HttpHeaders headers = new HttpHeaders();
    User user = (User) auth.getPrincipal();

    // You can't buy non-buyable Tickts for yourself, this should be done via the createAdminOrder() method.
    if (!ticketDTO.getType().isBuyable()) {
        return createResponseEntity(HttpStatus.FORBIDDEN,
                "Can't order tickets with type " + ticketDTO.getType().getText());
    }

    Order order = orderService.create(user.getId(), ticketDTO);

    headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(order.getId()).toUri());

    return createResponseEntity(HttpStatus.CREATED, headers,
            "Ticket available and order successfully created at " + headers.getLocation(), order);
}

From source file:com.jiwhiz.rest.user.PostCommentRestController.java

@RequestMapping(method = RequestMethod.POST, value = URL_USER_BLOGS_BLOG_COMMENTS, consumes = MediaType.APPLICATION_JSON_VALUE)
@Transactional/* w ww.j av  a2 s  . c  o m*/
public ResponseEntity<Void> postComment(@PathVariable("blogId") String blogId,
        @RequestBody CommentForm newComment) throws ResourceNotFoundException {
    UserAccount currentUser = getCurrentAuthenticatedUser();
    BlogPost blogPost = this.blogPostRepository.findOne(blogId);
    if (blogPost == null || !blogPost.isPublished()) {
        throw new ResourceNotFoundException("No published blog post with the id: " + blogId);
    }

    CommentPost commentPost = commentPostService.postComment(currentUser, blogPost, newComment.getContent());

    //send email to author if someone else posted a comment to blog.
    if (this.commentNotificationSender != null && !blogPost.getAuthor().equals(currentUser)) {
        this.commentNotificationSender.send(blogPost.getAuthor(), currentUser, commentPost, blogPost);
    }

    UserCommentResource resource = userCommentResourceAssembler.toResource(commentPost);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(URI.create(resource.getLink(Link.REL_SELF).getHref()));

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

From source file:org.osiam.addons.self_administration.registration.RegistrationController.java

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

    if (bindingResult.hasErrors()) {
        model.addAttribute("allowedFields", registrationService.getAllAllowedFields());
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return "registration";
    }// ww w  .  j av  a 2 s  . co m

    User user = registrationService.convertToScimUser(registrationUser);

    try {
        callbackPlugin.performPreRegistrationActions(user);
    } catch (CallbackException e) {
        model.addAttribute("errorMessage", e.getMessage());
        model.addAttribute("allowedFields", registrationService.getAllAllowedFields());

        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return "registration";
    }

    user = registrationService.saveRegistrationUser(user);

    registrationService.sendRegistrationEmail(user, request);

    model.addAttribute("user", user);

    response.setStatus(HttpStatus.CREATED.value());
    try {
        callbackPlugin.performPostRegistrationActions(user);
    } catch (CallbackException p) {
        LOGGER.error("An exception occurred while performing post registration actions for user with ID: "
                + user.getId(), p);
    }
    return "registrationSuccess";
}

From source file:com.intel.databackend.handlers.Data.java

@RequestMapping(value = "/v1/accounts/{accountId}/dataSubmission", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody// w w w  .  j  av  a 2 s.  c o m
public ResponseEntity dataSubmission(@PathVariable String accountId,
        @Valid @RequestBody DataSubmissionRequest request, BindingResult result)
        throws ServiceException, BindException {
    logger.info(REQUEST_LOG_ENTRY, accountId);
    logger.debug(DEBUG_LOG, request);

    if (result.hasErrors()) {
        throw new BindException(result);
    } else {
        dataSubmissionService.withParams(accountId, request);

        dataSubmissionService.invoke();
        ResponseEntity res = new ResponseEntity<>(HttpStatus.CREATED);
        logger.info(RESPONSE_LOG_ENTRY, res.getStatusCode());
        return res;
    }
}

From source file:curly.artifactory.web.ArtifactResourceControllerTests.java

@Test
public void testSaveResource() throws Exception {
    mockMvc.perform(asyncDispatch(mockMvc
            .perform(post("/artifacts").contentType(MediaType.APPLICATION_JSON)
                    .content(json(artifact, messageConverter)).principal(user()))
            .andExpect(request().asyncStarted())
            .andExpect(request().asyncResult(new ResponseEntity<>(HttpStatus.CREATED))).andReturn()));
}