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.company.eleave.leave.rest.TestLeaveTypeController.java

@Test
public void testCreateLeaveType() {
    //given/* www. ja  va2s.  c o m*/
    final long newLeaveTypeId = 10l;

    final LeaveTypeDTO leaveTypeDTO = new LeaveTypeDTO();
    leaveTypeDTO.setComment("testComment");
    leaveTypeDTO.setDefaultDaysAllowed(20);
    leaveTypeDTO.setLeaveTypeName("testLeaveTypeName");

    final LeaveType leaveType = new LeaveType();
    leaveType.setComment("testComment");
    leaveType.setDefaultDaysAllowed(20);
    leaveType.setLeaveTypeName("testLeaveTypeName");

    Mockito.when(mapperMock.toEntity(leaveTypeDTO)).thenReturn(leaveType);
    Mockito.when(leaveTypeServiceMock.createNewLeaveType(leaveType)).thenReturn(newLeaveTypeId);

    //when
    ResponseEntity<Long> result = testedObject.createNewLeaveType(leaveTypeDTO);

    //then
    Assert.assertEquals(HttpStatus.CREATED, result.getStatusCode());
    Assert.assertEquals("/leaveTypes/10", result.getHeaders().getLocation().toString());
}

From source file:de.zib.gndms.gndmc.gorfx.AbstractTaskFlowExecClient.java

/**
 *
 * @brief Executes a complete task flow.
 *
 * This method is imported when you want to understand the
 * Taskflow protocol.//from  ww w  .  j a  v a  2 s .c om
 *
 * @param order The order of the taskflow.
 * @param dn    The DN of the user calling the task flow.
 *
 * @param withQuote Activates co-scheduling
 * @param desiredQuote A quote holding desired time values for
 * the tasflow execution.
 * @param wid the workflow id
 */
public void execTF(Order order, String dn, boolean withQuote, final Quote desiredQuote, final String wid) {

    GNDMSResponseHeader context = setupContext(new GNDMSResponseHeader());

    if (null == gorfxClient) {
        throw new IllegalStateException("You need to set gorfxClient before executing a TaskFlow!");
    }

    /**
     * \code this is important
     */

    // sends the order and creates the task flow
    ResponseEntity<Specifier<Facets>> res = gorfxClient.createTaskFlow(order.getTaskFlowType(), order, dn, wid,
            context);

    if (!HttpStatus.CREATED.equals(res.getStatusCode())) {
        throw new RuntimeException("createTaskFlow failed " + res.getStatusCode().name() + " ("
                + res.getStatusCode() + ")" + " on URL " + gorfxClient.getServiceURL());
    }

    // the taskflow id is stored under "id" in the urlmap
    String tid = res.getBody().getUriMap().get("id");

    Integer q = null;
    if (withQuote) {
        if (null == tfClient) {
            throw new IllegalStateException("No TaskFlowClient set.");
        }

        if (desiredQuote != null) {
            tfClient.setQuote(order.getTaskFlowType(), tid, desiredQuote, dn, wid);
        }
        // queries the quotes for the task flow
        ResponseEntity<List<Specifier<Quote>>> res2 = tfClient.getQuotes(order.getTaskFlowType(), tid, dn, wid);

        if (!HttpStatus.OK.equals(res2.getStatusCode()))
            throw new RuntimeException("getQuotes failed " + res2.getStatusCode().name());

        // lets the implementors of this class choose a quote
        q = selectQuote(res2.getBody());
    }

    //
    // 'til here it is valid to change the order and request new quotes
    // 

    // accepts quote q and triggers task creation
    ResponseEntity<Specifier<Facets>> res3 = tfClient.createTask(order.getTaskFlowType(), tid, q, dn, wid);

    if (!HttpStatus.CREATED.equals(res3.getStatusCode()))
        throw new RuntimeException("createTask failed " + res3.getStatusCode().name());

    final Specifier<Facets> taskSpecifier = res3.getBody();

    // let the implementor do smart things with the task specifier
    handleTaskSpecifier(taskSpecifier);

    // the task id is stored under "taskId" in the specifiers urlmap
    waitForFinishOrFail(taskSpecifier, this, taskClient, pollingDelay, dn, wid);

    /**
     * \endcode
     */
}

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

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

    analyticsOperations.uploadSession(new AnalyticsSession());

    mockServer.verify();//from  w w  w.j av a  2 s.c  o  m
}

From source file:ch.heigvd.gamification.api.PointScalesEndpoint.java

@Override
@RequestMapping(value = "/{pointScaleId}", method = RequestMethod.GET)
public ResponseEntity<PointScaleDTO> pointScalesPointScaleIdGet(
        @ApiParam(value = "pointScaleId", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken,
        @ApiParam(value = "pointScaleId", required = true) @PathVariable("pointScaleId") Long pointScaleId) {

    AuthenKey apiKey = authenRepository.findByAppKey(xGamificationToken);
    if (apiKey == null) {
        return new ResponseEntity("apikey not exist", HttpStatus.UNAUTHORIZED);
    }/* w w  w. jav a 2s.  c  o m*/

    PointScale p = pointscaleRepository.findByIdAndApp(pointScaleId, apiKey.getApp());

    if (p == null) {
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }

    PointScaleDTO dto = toDTO(p);
    dto.setId(p.getId());

    return new ResponseEntity(dto, HttpStatus.CREATED);
}

From source file:com.jiwhiz.rest.author.AuthorBlogRestController.java

@RequestMapping(method = RequestMethod.POST, value = URL_AUTHOR_BLOGS)
@Transactional/*from   w  w  w . j  a  va2  s.  c  om*/
public HttpEntity<Void> createBlogPost(@RequestBody BlogPostForm blogPostForm) {
    UserAccount currentUser = getCurrentAuthenticatedAuthor();
    BlogPost blogPost = new BlogPost(currentUser, blogPostForm.getTitle(), blogPostForm.getContent(),
            blogPostForm.getTagString());

    blogPost = blogPostRepository.save(blogPost);
    AuthorBlogResource resource = authorBlogResourceAssembler.toResource(blogPost);
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(URI.create(resource.getLink("self").getHref()));

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

From source file:org.hsweb.web.controller.GenericController.java

/**
 * ?POST?/* w ww. j a  va  2  s  . c  o m*/
 *
 * @param object 
 * @return ?
 * @throws javax.validation.ValidationException ???
 */
@RequestMapping(method = RequestMethod.POST)
@AccessLogger("")
@Authorize(action = "C")
@ResponseStatus(HttpStatus.CREATED)
public ResponseMessage add(@RequestBody PO object) {
    PK pk = getService().insert(object);
    return ResponseMessage.created(pk);
}

From source file:de.codecentric.boot.admin.services.ApplicationRegistratorTest.java

@SuppressWarnings("rawtypes")
@Test/*from   w ww  .  j  a  v  a  2 s.  c o  m*/
public void deregister() {
    when(restTemplate.postForEntity(isA(String.class), isA(HttpEntity.class), eq(Map.class)))
            .thenReturn(new ResponseEntity<Map>(Collections.singletonMap("id", "-id-"), HttpStatus.CREATED));
    registrator.register();
    registrator.deregister();

    verify(restTemplate).delete("http://sba:8080/api/applications/-id-");
}

From source file:gateway.controller.AlertTriggerController.java

/**
 * Creates a new Trigger/*from   w w  w  . j a  v a 2  s  .  c  om*/
 * 
 * @see "http://pz-swagger.stage.geointservices.io/#!/Trigger/post_trigger"
 * 
 * @param trigger
 *            The Trigger JSON.
 * @param user
 *            The user making the request
 * @return The Trigger, or an error.
 */
@RequestMapping(value = "/trigger", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(value = "Creates a Trigger", notes = "Creates a new Trigger", tags = { "Trigger", "Workflow" })
@ApiResponses(value = {
        @ApiResponse(code = 201, message = "The newly created Trigger", response = TriggerResponse.class),
        @ApiResponse(code = 400, message = "Bad Request", response = ErrorResponse.class),
        @ApiResponse(code = 401, message = "Unauthorized", response = ErrorResponse.class),
        @ApiResponse(code = 500, message = "Internal Error", response = ErrorResponse.class) })
public ResponseEntity<?> createTrigger(
        @ApiParam(value = "The Trigger information to register. This defines the Conditions that must be hit in order for some Action to occur.", required = true) @Valid @RequestBody Trigger trigger,
        Principal user) {
    try {
        // Log the message
        logger.log(String.format("User %s has requested a new Trigger to be created.",
                gatewayUtil.getPrincipalName(user)), PiazzaLogger.INFO);
        try {
            // Attempt to set the username of the Job in the Trigger to the
            // submitting username
            trigger.job.createdBy = gatewayUtil.getPrincipalName(user);
            trigger.createdBy = gatewayUtil.getPrincipalName(user);
        } catch (Exception exception) {
            String message = String.format(
                    "Failed to set the username field in Trigger created by User %s: - exception: %s",
                    gatewayUtil.getPrincipalName(user), exception.getMessage());
            LOGGER.warn(message, exception);
            logger.log(message, PiazzaLogger.WARNING);
        }

        try {
            // Proxy the request to Workflow
            return new ResponseEntity<String>(
                    restTemplate.postForObject(String.format("%s/%s", WORKFLOW_URL, "trigger"),
                            objectMapper.writeValueAsString(trigger), String.class),
                    HttpStatus.CREATED);
        } catch (HttpClientErrorException | HttpServerErrorException hee) {
            LOGGER.error(String.format("Received Code %s with Message %s while creating a Trigger.",
                    hee.getStatusCode().toString(), hee.getMessage()), hee);
            return new ResponseEntity<PiazzaResponse>(
                    gatewayUtil.getErrorResponse(
                            hee.getResponseBodyAsString().replaceAll("}", " ,\"type\":\"error\" }")),
                    hee.getStatusCode());
        }
    } catch (Exception exception) {
        String error = String.format("Error Creating Trigger by user %s: %s",
                gatewayUtil.getPrincipalName(user), exception.getMessage());
        LOGGER.error(error, exception);
        logger.log(error, PiazzaLogger.ERROR);
        return new ResponseEntity<PiazzaResponse>(new ErrorResponse(error, "Gateway"),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:de.loercher.localpress.core.api.LocalPressController.java

@RequestMapping(value = "/articles", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> addArticleEntry(@RequestBody LocalPressArticleEntity entity,
        @RequestHeader HttpHeaders headers)
        throws UnauthorizedException, GeneralLocalPressException, JsonProcessingException {
    AddArticleEntityDTO geoDTO = new AddArticleEntityDTO(entity.getRelease());

    List<String> userHeader = headers.get("UserID");
    if (userHeader == null || userHeader.isEmpty()) {
        throw new UnauthorizedException("There needs to be set a UserID-Header!", "", "");
    }//w  w w . ja v  a2  s .com

    MultiValueMap<String, String> geoHeaders = new LinkedMultiValueMap<>();
    geoHeaders.add("UserID", userHeader.get(0));

    HttpEntity<AddArticleEntityDTO> request = new HttpEntity<>(geoDTO, geoHeaders);

    RestTemplate template = new RestTemplate();
    String ratingURL = RATING_URL + "feedback";
    ResponseEntity<Map> result;
    try {
        result = template.postForEntity(ratingURL, request, Map.class);
    } catch (RestClientException e) {
        GeneralLocalPressException ex = new GeneralLocalPressException(
                "There happened an error by trying to invoke the geo API!", e);
        log.error(ex.getLoggingString());
        throw ex;
    }

    if (!result.getStatusCode().equals(HttpStatus.CREATED)) {
        GeneralLocalPressException e = new GeneralLocalPressException(result.getStatusCode().getReasonPhrase());
        log.error(e.getLoggingString());
        throw e;
    }

    String articleID = (String) result.getBody().get("articleID");
    if (articleID == null) {
        GeneralLocalPressException e = new GeneralLocalPressException(
                "No articleID found in response from rating module by trying to add new article!");
        log.error(e.getLoggingString());
        throw e;
    }

    HttpEntity<LocalPressArticleEntity> second = new HttpEntity<>(entity, geoHeaders);

    template.put(GEO_URL + articleID, second);

    String url = (String) result.getBody().get("feedbackURL");

    Map<String, Object> returnMap = new LinkedHashMap<>();
    returnMap.put("articleID", articleID);
    returnMap.put("userID", userHeader.get(0));

    Timestamp now = new Timestamp(new Date().getTime());
    returnMap.put("timestamp", now);
    returnMap.put("status", 201);
    returnMap.put("message", "Created.");

    returnMap.put("feedbackURL", url);

    return new ResponseEntity<>(objectMapper.writeValueAsString(returnMap), HttpStatus.CREATED);
}