下面列出了怎么用org.springframework.http.HttpStatus的API类实例代码及写法,或者点击链接到github查看源代码。
@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)));
}
@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();
}
@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);
}
}
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;
}
/**
* 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);
}
/**
* 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);
}
}
@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();
}
}
@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);
}
@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());
}
@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();
}
@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;
}
@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);
}
@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());
}
}
@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);
}
@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;
}
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 ;
}
@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());
}
@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());
}
@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);
}
/**
* 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);
}
}
/**
* 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);
}
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);
}
@Test
void getLastOperationWithInProgressResponseGivesExpectedStatus() {
validateGetLastOperationWithResponseStatus(GetLastServiceOperationResponse.builder()
.operationState(OperationState.IN_PROGRESS)
.description("in progress")
.build(), HttpStatus.OK);
}
@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);
}
@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));
}
/**
* 编辑一个用户对象
* 幂等性
* */
@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;
}
@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);
}
/**
* 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");
}
@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!");
}
}
@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"));
}