Java Code Examples for org.springframework.http.HttpStatus

The following examples show how to use org.springframework.http.HttpStatus. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: syndesis   Source File: TodoListApi_IT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@CitrusTest
public void testGetOpenApiSpec(@CitrusResource TestCaseRunner runner) {
    cleanupDatabase(runner);

    runner.given(waitFor().http()
            .method(HttpMethod.GET.name())
            .seconds(10L)
            .status(HttpStatus.OK.value())
            .url(String.format("http://localhost:%s/actuator/health", integrationContainer.getManagementPort())));

    runner.when(http().client(todoListApiClient)
            .send()
            .get("/openapi.json"));

    runner.then(http().client(todoListApiClient)
            .receive()
            .response(HttpStatus.OK)
            .contentType(VND_OAI_OPENAPI_JSON)
            .payload(new ClassPathResource("todolist-api.json", TodoApi_IT.class)));
}
 
Example 2
Source Project: jeecg   Source File: TSFillRuleController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public ResponseMessage<?> delete(@PathVariable("id") String id) {
	logger.info("delete[{}]" , id);
	// 验证
	if (StringUtils.isEmpty(id)) {
		return Result.error("ID不能为空");
	}
	try {
		tSFillRuleService.deleteEntityById(TSFillRuleEntity.class, id);
	} catch (Exception e) {
		e.printStackTrace();
		return Result.error("填值规则表删除失败");
	}

	return Result.success();
}
 
Example 3
Source Project: java-technology-stack   Source File: AbstractXhrTransport.java    License: MIT License 6 votes vote down vote up
@Override
public void executeSendRequest(URI url, HttpHeaders headers, TextMessage message) {
	if (logger.isTraceEnabled()) {
		logger.trace("Starting XHR send, url=" + url);
	}
	ResponseEntity<String> response = executeSendRequestInternal(url, headers, message);
	if (response.getStatusCode() != HttpStatus.NO_CONTENT) {
		if (logger.isErrorEnabled()) {
			logger.error("XHR send request (url=" + url + ") failed: " + response);
		}
		throw new HttpServerErrorException(response.getStatusCode());
	}
	if (logger.isTraceEnabled()) {
		logger.trace("XHR send request (url=" + url + ") response: " + response);
	}
}
 
Example 4
Source Project: echo   Source File: PipelineInitiator.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean isRetryableError(Throwable error) {
  if (!(error instanceof RetrofitError)) {
    return false;
  }
  RetrofitError retrofitError = (RetrofitError) error;

  if (retrofitError.getKind() == Kind.NETWORK) {
    return true;
  }

  if (retrofitError.getKind() == Kind.HTTP) {
    Response response = retrofitError.getResponse();
    return (response != null && response.getStatus() != HttpStatus.BAD_REQUEST.value());
  }

  return false;
}
 
Example 5
Source Project: api-layer   Source File: PageRedirectionTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Test ui instance of staticclient
 */
@Test
@TestsNotMeantForZowe
public void uiRouteOfDiscoverableClient() {
    String location = String.format("%s://%s:%d%s", dcScheme, dcHost, dcPort, BASE_URL);
    String uiPrefix = "/ui/v1";
    String transformedLocation = String.format("%s://%s:%d%s%s", gatewayScheme, gatewayHost, gatewayPort, uiPrefix, "/" + SERVICE_ID);

    RedirectLocation redirectLocation = new RedirectLocation(location);

    given()
        .contentType(JSON)
        .body(redirectLocation)
        .when()
        .post(requestUrl)
        .then()
        .statusCode(is(HttpStatus.TEMPORARY_REDIRECT.value()))
        .header(LOCATION, transformedLocation);
}
 
Example 6
Source Project: cf-SpringBootTrader   Source File: AccountController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * REST call to decrease the balance in the account. Decreases the balance
 * of the account if the new balance is not lower than zero. Returns HTTP OK
 * and the new balance if the decrease was successful, or HTTP
 * EXPECTATION_FAILED if the new balance would be negative and the
 * old/current balance.
 * 
 * @param userId
 *            The id of the account.
 * @param amount
 *            The amount to decrease the balance by.
 * @return The new balance of the account with HTTP OK.
 */
@RequestMapping(value = "/accounts/{userId}/decreaseBalance/{amount}", method = RequestMethod.GET)
public ResponseEntity<Double> decreaseBalance(@PathVariable("userId") final String userId, @PathVariable("amount") final double amount) {

	logger.debug("AccountController.decreaseBalance: id='" + userId + "', amount='" + amount + "'");

	Account accountResponse = this.service.findAccount(userId);

	BigDecimal currentBalance = accountResponse.getBalance();

	BigDecimal newBalance = currentBalance.subtract(new BigDecimal(amount));

	if (newBalance.compareTo(BigDecimal.ZERO) >= 0) {
		accountResponse.setBalance(newBalance);
		this.service.saveAccount(accountResponse);
		return new ResponseEntity<Double>(accountResponse.getBalance().doubleValue(), getNoCacheHeaders(), HttpStatus.OK);

	} else {
		// no sufficient founds available
		return new ResponseEntity<Double>(accountResponse.getBalance().doubleValue(), getNoCacheHeaders(), HttpStatus.EXPECTATION_FAILED);
	}

}
 
Example 7
Source Project: java-trader   Source File: ConfigController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(path=URL_PREFIX+"/{configSource}/**",
        method=RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getConfigItem(@PathVariable(value="configSource") String configSourceStr, HttpServletRequest request){
    String requestURI = request.getRequestURI();
    String configItem = requestURI.substring( URL_PREFIX.length()+configSourceStr.length()+1);
    Object obj = null;
    if ( "ALL".equalsIgnoreCase(configSourceStr) ) {
        obj = ConfigUtil.getObject(configItem);
    }else{
        String configSource = configSources.get(configSourceStr.toLowerCase());
        if (configSource==null){
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
        obj = ConfigUtil.getObject(configSource, configItem);
    }
    if( logger.isDebugEnabled() ){
        logger.debug("Get config "+configSourceStr+" path \""+configItem+"\" value: \""+obj+"\"");
    }
    if ( obj==null ){
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }else{
        return obj.toString();
    }
}
 
Example 8
@PublicApi
@PremiumPublicApi
@ApiOperation(value = "", notes = "Annotate mutations by genomic change.", response = IndicatorQueryResp.class, responseContainer = "List")
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "OK", response = IndicatorQueryResp.class, responseContainer = "List"),
    @ApiResponse(code = 400, message = "Error, error message will be given.", response = String.class)})
@RequestMapping(value = "/annotate/mutations/byHGVSg",
    consumes = {"application/json"},
    produces = {"application/json"},
    method = RequestMethod.POST)
public ResponseEntity<List<IndicatorQueryResp>> annotateMutationsByHGVSgPost(
    @ApiParam(value = "List of queries. Please see swagger.json for request body format.", required = true) @RequestBody() List<AnnotateMutationByHGVSgQuery> body
) {
    HttpStatus status = HttpStatus.OK;
    List<IndicatorQueryResp> result = new ArrayList<>();

    if (body == null) {
        status = HttpStatus.BAD_REQUEST;
    } else {
        for (AnnotateMutationByHGVSgQuery query : body) {
            result.add(IndicatorUtils.processQuery(new Query(query), null, false, query.getEvidenceTypes()));
        }
    }
    return new ResponseEntity<>(result, status);
}
 
Example 9
@Test
@Description("Tests that an download request is denied for an artifact which is not assigned to the requested target")
public void authenticationRequestDeniedForArtifactWhichIsNotAssignedToTarget() {
    final MessageProperties messageProperties = createMessageProperties(null);
    final DmfTenantSecurityToken securityToken = new DmfTenantSecurityToken(TENANT, TENANT_ID, CONTROLLER_ID,
            TARGET_ID, FileResource.createFileResourceBySha1("12345"));
    final Message message = amqpMessageHandlerService.getMessageConverter().toMessage(securityToken,
            messageProperties);

    final Artifact localArtifactMock = mock(Artifact.class);
    when(artifactManagementMock.findFirstBySHA1(anyString())).thenReturn(Optional.of(localArtifactMock));

    // test
    final Message onMessage = amqpAuthenticationMessageHandlerService.onAuthenticationRequest(message);

    // verify
    final DmfDownloadResponse downloadResponse = (DmfDownloadResponse) messageConverter.fromMessage(onMessage);
    assertThat(downloadResponse).as("Message body should not null").isNotNull();
    assertThat(downloadResponse.getResponseCode()).as("Message body response code is wrong")
            .isEqualTo(HttpStatus.NOT_FOUND.value());
}
 
Example 10
Source Project: spring-analysis-note   Source File: RestTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void exchange() throws Exception {
	mockTextPlainHttpMessageConverter();
	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "https://example.com", requestHeaders);
	mockResponseStatus(HttpStatus.OK);
	String expected = "42";
	mockResponseBody(expected, MediaType.TEXT_PLAIN);

	HttpHeaders entityHeaders = new HttpHeaders();
	entityHeaders.set("MyHeader", "MyValue");
	HttpEntity<String> entity = new HttpEntity<>("Hello World", entityHeaders);
	ResponseEntity<String> result = template.exchange("https://example.com", POST, entity, String.class);
	assertEquals("Invalid POST result", expected, result.getBody());
	assertEquals("Invalid Content-Type", MediaType.TEXT_PLAIN, result.getHeaders().getContentType());
	assertEquals("Invalid Accept header", MediaType.TEXT_PLAIN_VALUE, requestHeaders.getFirst("Accept"));
	assertEquals("Invalid custom header", "MyValue", requestHeaders.getFirst("MyHeader"));
	assertEquals("Invalid status code", HttpStatus.OK, result.getStatusCode());

	verify(response).close();
}
 
Example 11
Source Project: Spring-Security-Third-Edition   Source File: ErrorController.java    License: MIT License 6 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!  ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    sb.append(", root cause: ").append((throwable != null && throwable.getCause() != null ? throwable.getCause() : "Unknown cause"));
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 12
Source Project: cola-cloud   Source File: GlobalExceptionHandler.java    License: MIT License 5 votes vote down vote up
@ResponseBody
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {

    log.error(ErrorStatus.METHOD_NOT_ALLOWED.getMessage() + ":" + e.getMessage());
    return failure(ErrorStatus.METHOD_NOT_ALLOWED,e);
}
 
Example 13
@Test
public void preFlightRequestWithoutCorsEnabled() throws Exception {
	try {
		this.headers.add(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET");
		performOptions("/welcome", this.headers, String.class);
		fail();
	}
	catch (HttpClientErrorException e) {
		assertEquals(HttpStatus.FORBIDDEN, e.getStatusCode());
	}
}
 
Example 14
Source Project: carts   Source File: CartsController.java    License: Apache License 2.0 5 votes vote down vote up
@ResponseStatus(HttpStatus.ACCEPTED)
@RequestMapping(value = "/{customerId}/merge", method = RequestMethod.GET)
public void mergeCarts(@PathVariable String customerId, @RequestParam(value = "sessionId") String sessionId) {
    logger.debug("Merge carts request received for ids: " + customerId + " and " + sessionId);
    CartResource sessionCart = new CartResource(cartDAO, sessionId);
    CartResource customerCart = new CartResource(cartDAO, customerId);
    customerCart.merge(sessionCart.value().get()).run();
    delete(sessionId);
}
 
Example 15
Source Project: youkefu   Source File: ApiSessionController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/session", method = RequestMethod.POST)
@Menu(type = "apps" , subtype = "session" , access = true)
@ApiOperation("登录服务,传入登录账号和密码")
public ResponseEntity<Object> session(HttpServletRequest request , HttpServletResponse response , @Valid String userid ) {
	ResponseEntity<Object> entity = null ;
    if(!StringUtils.isBlank(userid)){
    	String auth = UKTools.getUUID();
    	CacheHelper.getApiUserCacheBean().put(auth, super.getIMUser(request, userid, null), UKDataContext.SYSTEM_ORGI);
    	entity = new ResponseEntity<Object>(auth, HttpStatus.OK) ;
    	response.addCookie(new Cookie("authorization",auth));
    }else{
    	entity = new ResponseEntity<>(HttpStatus.UNAUTHORIZED) ;
    }
    return entity;
}
 
Example 16
Source Project: SDA   Source File: CmServiceImpl.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<CmCiDTO> selectCmCmiCiList(Map<String, Object> commandMap) throws Exception {
	List<CmCiDTO> list = new ArrayList<CmCiDTO>();
	list = cmDAO.selectCmCmiCiList(commandMap);

	// 데이타가 없으면 오류발생시킴
	if (list == null || list.size() == 0) {
		throw new UserDefinedException(HttpStatus.NOT_FOUND);
	}

	return list ;
}
 
Example 17
@ResponseStatus(HttpStatus.NOT_FOUND)  // 404
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseBody
public CustomErrorResponse handleNotFound(ResourceNotFoundException ex) {
    log.warn("Entity was not found", ex);
    return new CustomErrorResponse(ERROR_CODE.E0001.name(), ex.getMessage());
}
 
Example 18
@Test
void updateAppWithHostAndDomain() {
	cloudControllerFixture.stubAppExists(APP_NAME);
	cloudControllerFixture.stubUpdateAppWithHostAndDomain(APP_NAME);

	HashMap<String, Object> expectedUpdateParams = new HashMap<>();
	expectedUpdateParams.put("host", "myhost");
	expectedUpdateParams.put("domain", "my.domain.com");

	// when a service instance is updated with parameters
	given(brokerFixture.serviceInstanceRequest(expectedUpdateParams))
		.when()
		.patch(brokerFixture.createServiceInstanceUrl(), "instance-id")
		.then()
		.statusCode(HttpStatus.ACCEPTED.value());

	// when the "last_operation" API is polled
	given(brokerFixture.serviceInstanceRequest())
		.when()
		.get(brokerFixture.getLastInstanceOperationUrl(), "instance-id")
		.then()
		.statusCode(HttpStatus.OK.value())
		.body("state", is(equalTo(OperationState.IN_PROGRESS.toString())));

	String state = brokerFixture.waitForAsyncOperationComplete("instance-id");
	assertThat(state).isEqualTo(OperationState.SUCCEEDED.toString());
}
 
Example 19
Source Project: yshopmall   Source File: SystemStoreStaffController.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping
@Log("查询门店店员")
@ApiOperation("查询门店店员")
@PreAuthorize("@el.check('yxSystemStoreStaff:list')")
public ResponseEntity<Object> getYxSystemStoreStaffs(YxSystemStoreStaffQueryCriteria criteria, Pageable pageable){
    return new ResponseEntity<>(yxSystemStoreStaffService.queryAll(criteria,pageable),HttpStatus.OK);
}
 
Example 20
Source Project: steady   Source File: TenantController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link Tenant} with a new, random token in the database and returns it to the client.
 *
 * @param tenant a {@link com.sap.psr.vulas.backend.model.Tenant} object.
 * @return a {@link org.springframework.http.ResponseEntity} object.
 */
@RequestMapping(value = "", method = RequestMethod.POST, consumes = {"application/json;charset=UTF-8"}, produces = {"application/json;charset=UTF-8"})
@JsonView(Views.Default.class)
public ResponseEntity<Tenant> createTenant(@RequestBody Tenant tenant) {
	final StopWatch sw = new StopWatch("Create tenant [" + (tenant==null?null:tenant.getTenantName()) + "]").start();
	try {
		if(!this.tenantRepository.isTenantComplete(tenant)){
			return new ResponseEntity<Tenant>(HttpStatus.BAD_REQUEST);
		}
		//check that only 1 default tenant exists
		else if(tenant.isDefault() && tenantRepository.findDefault()!=null) {
			log.error("A default tenant already exists! Only one default tenant is allowed");
			return new ResponseEntity<Tenant>(HttpStatus.BAD_REQUEST);
		}
		
		// Always create token, whatever has been submitted
		tenant.setTenantToken(TokenUtil.generateToken());
		this.tenantRepository.save(tenant);
//		this.tenantRepository.createDefaultSpaces(tenant);
		sw.stop();
		return new ResponseEntity<Tenant>(tenant, HttpStatus.CREATED);
	}
	catch(Exception enfe) {
		sw.stop(enfe);
		return new ResponseEntity<Tenant>(HttpStatus.INTERNAL_SERVER_ERROR);
	}
}
 
Example 21
Source Project: kardio   Source File: GDMMainController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get All Counter Metrix related to the given environment and platform.
 * 
 * @param environmentName
 * @param platform
 * @return
 */
@ApiOperation(value="Get all Counter Metrics")
@CrossOrigin
@RequestMapping(value = "/getCounterMetrix", method = RequestMethod.GET)
public ResponseEntity<GDMResponse> getCounterMetrix(@RequestParam(value = "environment", required = false) String environmentName,
		@RequestParam(value = "platform", required = false) String platform) {
    log.debug("********************* getCounterMetrix ********************************");
    List<Counters> listOfCounters = regionStatusService.getCountersMatrix(environmentName, platform);
    return new ResponseEntity<GDMResponse>(new GDMResponse(listOfCounters), HttpStatus.OK);
}
 
Example 22
private RestOperations mockRestOperations() throws Exception {
	Map<String, String> payload = new HashMap<>();
	payload.put("one", keyGeneratorUtils.getPublicKeyCertificate());
	HttpHeaders headers = new HttpHeaders();
	headers.add(HttpHeaders.CACHE_CONTROL, CacheControl.maxAge(3600L, TimeUnit.SECONDS).getHeaderValue());
	ResponseEntity<Map<String, String>> response = new ResponseEntity<>(payload, headers, HttpStatus.OK);
	return mockRestOperations(response);
}
 
Example 23
@Test
void getLastOperationWithInProgressResponseGivesExpectedStatus() {
	validateGetLastOperationWithResponseStatus(GetLastServiceOperationResponse.builder()
			.operationState(OperationState.IN_PROGRESS)
			.description("in progress")
			.build(), HttpStatus.OK);
}
 
Example 24
Source Project: springboot-learn   Source File: ElasticSearchController.java    License: MIT License 5 votes vote down vote up
@PostMapping("query/book/novel")
@ResponseBody
public ResponseEntity query(
        @RequestParam(name = "title", required = false) String title,
        @RequestParam(name = "author", required = false) String author,
        @RequestParam(name = "gtWordCount", defaultValue = "0") int gtWordCount,
        @RequestParam(name = "ltWordCount", required = false) Integer ltWordCount
) {
    BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
    if (author != null) {
        queryBuilder.must(QueryBuilders.matchQuery("author", author));
    }
    if (title != null) {
        queryBuilder.must(QueryBuilders.matchQuery("title", title));
    }
    // 大于
    RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("word_count").from(gtWordCount);
    // 小于
    if (ltWordCount != null && ltWordCount > 0) {
        rangeQueryBuilder.to(ltWordCount);
    }
    //过滤条件
    queryBuilder.filter(rangeQueryBuilder);
    SearchRequestBuilder builder = transportClient.prepareSearch(INDEX)
            .setTypes(TYPE)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setQuery(queryBuilder)
            .setFrom(0)
            .setSize(10);
    SearchResponse response = builder.get();
    List<Map<String, Object>> result = new ArrayList<>();
    //将命中的数据放入List
    for (SearchHit hit : response.getHits()) {
        result.add(hit.getSourceAsMap());
    }
    return new ResponseEntity(result, HttpStatus.OK);
}
 
Example 25
@Test
@Order(8)
void testUpdateResource() throws IOException {
  JSONArray jsonArray = new JSONArray();

  JSONObject jsonObject = new JSONObject();
  jsonObject.put("id", 25);
  jsonObject.put("label", "Row 25b");
  jsonObject.put("myBool", false);
  jsonObject.put("myDate", "2000-02-25");
  jsonObject.put("myDateTime", "2000-02-24T21:02:03Z");
  jsonObject.put("myDecimal", 250.1);
  jsonObject.put("myInt", 250);
  jsonObject.put("myLong", 3000000250L);
  jsonObject.put("myString", "String 25b");
  jsonObject.put("myText", "Text 25b");
  jsonObject.put("myXref", null);
  jsonObject.put("myMref", jsonArray);

  given()
      .contentType(APPLICATION_JSON_VALUE)
      .body(jsonObject.toJSONString())
      .put("/api/data/v3_MyDataset/25")
      .then()
      .statusCode(NO_CONTENT.value());

  String expectedJson =
      TestResourceUtils.getRenderedString(
          getClass(), "updateResource.json", ImmutableMap.of("baseUri", RestAssured.baseURI));

  given()
      .get("/api/data/v3_MyDataset/25")
      .then()
      .statusCode(HttpStatus.OK.value())
      .body(isEqualJson(expectedJson));
}
 
Example 26
Source Project: spring-boot-study   Source File: UserController.java    License: MIT License 5 votes vote down vote up
/**
 * 编辑一个用户对象
 * 幂等性
 * */
@PutMapping("/users/{id}")
@ResponseStatus(HttpStatus.CREATED)
public Object editUser(@PathVariable("id") String id,@RequestBody UserDO user){
    List<UserDO> list= getData();
    for (UserDO userDO1:list
            ) {
        if(id.equals(userDO1.getUserId().toString())){
            userDO1=user;
            break;
        }
    }

    return user;
}
 
Example 27
Source Project: yshopmall   Source File: StoreCouponIssueController.java    License: Apache License 2.0 5 votes vote down vote up
@Log("删除")
@ApiOperation(value = "删除")
@DeleteMapping(value = "/yxStoreCouponIssue/{id}")
@PreAuthorize("@el.check('admin','YXSTORECOUPONISSUE_ALL','YXSTORECOUPONISSUE_DELETE')")
public ResponseEntity delete(@PathVariable Integer id){

    YxStoreCouponIssue resources = new YxStoreCouponIssue();
    resources.setId(id);
    resources.setIsDel(1);
    yxStoreCouponIssueService.saveOrUpdate(resources);
    return new ResponseEntity(HttpStatus.OK);
}
 
Example 28
/**
 * Test method for findById method
 */
@Test
public void validResturantById() {
    Logger.getGlobal().info("Start validResturantById test");
    ResponseEntity<Entity> restaurant = restaurantController.findById(RESTAURANT);

    Assert.assertEquals(HttpStatus.OK, restaurant.getStatusCode());
    Assert.assertTrue(restaurant.hasBody());
    Assert.assertNotNull(restaurant.getBody());
    Assert.assertEquals(RESTAURANT, restaurant.getBody().getId());
    Assert.assertEquals(RESTAURANT_NAME, restaurant.getBody().getName());
    Logger.getGlobal().info("End validResturantById test");
}
 
Example 29
@GetMapping("/status")
public ResponseEntity<String> getStatus() {
  if (this.chaosMonkeySettings.getChaosMonkeyProperties().isEnabled()) {
    return ResponseEntity.status(HttpStatus.OK).body("Ready to be evil!");
  } else {
    return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body("You switched me off!");
  }
}
 
Example 30
Source Project: problem-spring-web   Source File: NotAcceptableAdviceTraitTest.java    License: MIT License 5 votes vote down vote up
@Test
void notAcceptableNoProblem() {
    Problem problem = webTestClient().get().uri("http://localhost/api/handler-ok")
            .accept(MediaType.IMAGE_PNG)
            .exchange()
            .expectStatus().isEqualTo(HttpStatus.NOT_ACCEPTABLE)
            .expectHeader().contentType(MediaTypes.PROBLEM)
            .expectBody(Problem.class).returnResult().getResponseBody();

    assertThat(problem.getType().toString(), is("about:blank"));
    assertThat(problem.getTitle(), is("Not Acceptable"));
    assertThat(problem.getStatus(), is(Status.NOT_ACCEPTABLE));
    assertThat(problem.getDetail(), containsString("Could not find acceptable representation"));
}