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.ClienteControllerImp.java

@Override
@RequestMapping(method = RequestMethod.POST)
public void crearCliente(@Valid @RequestBody Cliente cliente, HttpServletResponse response) {
    cliente.setId(null);/*  w ww. j a v  a 2s  .  co m*/
    preprocesaCliente(cliente);
    this.clienteDao.guardar(cliente);
    response.setStatus(HttpStatus.CREATED.value());
    response.setHeader("Location", "/clientes/" + cliente.getId());
}

From source file:de.hska.ld.content.controller.FolderControllerIntegrationTest.java

@Test
public void testAddDocumentToFolderUsesHttpOkOnPersist() throws Exception {
    Folder folder = new Folder("Test");
    HttpResponse responseFolder = UserSession.user().post(RESOURCE_FOLDER, folder);
    Assert.assertEquals(HttpStatus.CREATED, ResponseHelper.getStatusCode(responseFolder));
    folder = ResponseHelper.getBody(responseFolder, Folder.class);
    Assert.assertNotNull(folder);/*from  ww  w . j  a va2 s  .c  o  m*/
    Long folderId = folder.getId();
    Assert.assertNotNull(folderId);

    HttpResponse responseDocument = UserSession.user().post(RESOURCE_DOCUMENT, document);
    Assert.assertEquals(HttpStatus.CREATED, ResponseHelper.getStatusCode(responseDocument));
    document = ResponseHelper.getBody(responseDocument, Document.class);
    Assert.assertNotNull(document);
    Long documentId = document.getId();
    Assert.assertNotNull(documentId);

    HttpResponse responseDocInFolder = UserSession.user()
            .post(RESOURCE_FOLDER + "/" + folderId + "/documents/" + documentId + "?old-parent=-1", document);
    Assert.assertEquals(HttpStatus.OK, ResponseHelper.getStatusCode(responseDocInFolder));

    // TODO add check if the document is in the parent folder
}

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

@POST
@Consumes(MediaType.APPLICATION_JSON)// ww w. j a v  a2s  . c  om
@Produces(MediaType.APPLICATION_JSON)
public Response addNew(UserCaseBo userCase) throws Exception {
    HttpStatus status = HttpStatus.CREATED;
    String response = StringUtils.EMPTY;
    if (!checkParam(userCase)) {
        status = HttpStatus.BAD_REQUEST;
        response = FailResult.toJson(Code.PARAM_ERROR, "?");
    } else {
        response = userCaseService.addUserCase(userCase).toJSONString();
    }

    return Response.status(status.value()).entity(response).build();
}

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

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

    analyticsOperations.uploadSessions(new ArrayList<AnalyticsSession>());

    mockServer.verify();//from ww w . j a v  a  2 s  .  co  m
}

From source file:de.zib.gndms.gndmc.gorfx.Test.GORFXClientTest.java

@Test(groups = { "GORFXServiceTest" }, dependsOnMethods = { "listFacets", "listTaskFlows" })
public void createTaskFlow() {
    // create TaskFlow
    {//from  w w w.j  a v a2s.c o  m
        FailureOrder order = new FailureOrder();
        order.setMessage("TESTING TaskFlow creation");
        order.setWhere(FailureOrder.FailurePlace.NOWHERE);

        ResponseEntity<Specifier<Facets>> responseEntity = gorfxClient.createTaskFlow(
                FailureTaskFlowMeta.TASK_FLOW_TYPE_KEY, order, admindn, "GORFXTaskFlowTEST",
                new LinkedMultiValueMap<String, String>());

        Assert.assertNotNull(responseEntity);
        Assert.assertEquals(responseEntity.getStatusCode(), HttpStatus.CREATED);
    }

    // get TaskFlow Info
    //{
    //    ResponseEntity< TaskFlowInfo > responseEntity = gorfxClient.getTaskFlowInfo(
    //            FailureTaskFlowMeta.TASK_FLOW_TYPE_KEY, admindn );
    //
    //    Assert.assertNotNull( responseEntity );
    //    Assert.assertEquals( responseEntity.getStatusCode(), HttpStatus.OK );
    //}
}

From source file:com.gazbert.bxbot.rest.api.MarketConfigController.java

@RequestMapping(value = "/market/{marketId}", method = RequestMethod.POST)
ResponseEntity<?> createMarket(@AuthenticationPrincipal User user, @PathVariable String marketId,
        @RequestBody MarketConfig config) {

    final MarketConfig updatedMarketConfig = marketConfigService.createMarket(config);
    final HttpHeaders httpHeaders = new HttpHeaders();

    httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{marketId}")
            .buildAndExpand(updatedMarketConfig.getId()).toUri());
    return new ResponseEntity<>(null, httpHeaders, HttpStatus.CREATED);
}

From source file:org.jbr.commons.rest.RestEndpointAspect.java

/**
 * Aspect that surrounds a bound RESTful controller method to provide the
 * following enhanced functionality://from  w w  w. j a va2s .c om
 * 
 * @param joinPoint
 *            Provides reflective access to both the state available at a
 *            join point and static information about it.
 * @param responseType
 *            the {@link ResponseType} annotation which is used to specify
 *            the response class for the bound controller method
 * @throws Throwable
 *             any encountered error is passed through
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Around(value = "@annotation(responseTimer)", argNames = "joinPoint, responseTimer")
public Object around(final ProceedingJoinPoint joinPoint, final RestEndpoint responseTimer) throws Throwable {

    // start execution timer
    final Date startTime = startTimer();

    // execute wrapped method
    final Object returnValue = joinPoint.proceed();

    // halt and record execution timer
    final long elapsedTime = System.currentTimeMillis() - startTime.getTime();
    LOG.debug("elapsed time for {} is {}ms", joinPoint, elapsedTime);

    // handle response entity
    if (returnValue instanceof ResponseEntity<?>) {
        final ResponseEntity<?> entity = (ResponseEntity<?>) returnValue;
        final HttpHeaders headers = new HttpHeaders();

        // transfer any existing headers, if enabled
        if (responseTimer.transferHeaders()) {
            headers.putAll(entity.getHeaders());
        }

        // transfer self link as Location header, if CREATED reponse
        if (entity.getStatusCode().equals(HttpStatus.CREATED)) {
            if (entity.getBody() instanceof ResourceSupport) {
                final ResourceSupport resource = (ResourceSupport) entity.getBody();
                if (resource.getId() != null) {
                    headers.setLocation(new URI(resource.getId().getHref()));
                }
            }
        }

        // save elapsed time header
        headers.add(HEADER_RESPONSE_ID, generatedResponseIdentifier());
        headers.add(HEADER_START_TIME, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(startTime));
        headers.add(HEADER_ELAPSED_TIME, String.valueOf(elapsedTime));

        // return new response entity
        return new ResponseEntity(entity.getBody(), headers, entity.getStatusCode());
    }

    // handle non-response entity
    else {
        return returnValue;
    }
}

From source file:com.javiermoreno.springboot.mvc.users.UserCtrl.java

/**
 * Creates a new user with the provided password
 * @param dto An object with a DailyUser and a Password
 * @return 201 Created if ok, 409 Conflict if already exists that username.
 *///from ww w . jav  a  2  s .c  o  m
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(value = "POST /users", notes = "Returns the created user with its assigned id. 201 if ok, 409 if already exists.")
public HttpEntity<DailyUserResource> createNewUser(@RequestBody UserAndPasswordDTO dto) {
    DailyUserResource resource = new DailyUserResource();
    resource.user = dto.user;
    resource.add(linkTo(methodOn(UserCtrl.class).showUser(dto.user.getEmail())).withSelfRel());
    try {
        userService.registerNewUser(dto.user, dto.password, true);
        return new ResponseEntity<>(resource, HttpStatus.OK);
    } catch (DataIntegrityViolationException exc) {
        return new ResponseEntity<>(resource, HttpStatus.CONFLICT);
    }
}

From source file:curly.artifactory.ArtifactResourceControllerTests.java

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

From source file:org.trustedanalytics.kafka.adminapi.api.ApiController.java

@RequestMapping(method = RequestMethod.POST, value = "/topics/{topic}", consumes = "text/plain")
@ResponseStatus(HttpStatus.CREATED)
public void writeMessage(@PathVariable String topic, @RequestBody String message) {
    LOG.info("writeMessage invoked: {}, {}", topic, message);

    kafkaService.writeMessage(topic, message);
}