本文整理汇总了Java中org.springframework.http.HttpStatus类的典型用法代码示例。如果您正苦于以下问题:Java HttpStatus类的具体用法?Java HttpStatus怎么用?Java HttpStatus使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpStatus类属于org.springframework.http包,在下文中一共展示了HttpStatus类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: create
import org.springframework.http.HttpStatus; //导入依赖的package包/类
public Topic create(String name) {
if (repository.findByName(name).isPresent()) {
throw new HttpClientErrorException(HttpStatus.CONFLICT, name + " 이미 등록된 태그 입니다.");
}
return repository.save(new Topic(name));
}
示例2: should_put_return_406_when_assigned_to_deleted_case
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@Test
public void should_put_return_406_when_assigned_to_deleted_case() throws Exception {
// given
ResponseEntity<Void> postResponse = getCreateTreatmentResponse();
URI location = postResponse.getHeaders().getLocation();
String id = RestHelper.extractIdStringFromURI(location);
Treatment savedTreatment = treatmentRepository.findOne(Long.parseLong(id));
theCase.setId(104243L);
savedTreatment.setRelevantCase(theCase);
// when
ResponseEntity<Void> putResponse = testRestTemplate
.withBasicAuth("1", "1")
.exchange("/v1/treatments/" + id,
HttpMethod.PUT,
new HttpEntity<>(savedTreatment),
Void.class);
// then
assertThat(putResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_ACCEPTABLE);
}
示例3: mailSend
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@RequestMapping(path = "/eapi/sendgrid/v3/mail/send")
public ResponseEntity mailSend(
@RequestBody MailSendForm form,
@RequestHeader(required = false) String authorization
) {
if (!checkAuthentication(authorization)) {
return new ResponseEntity<>("", HttpStatus.UNAUTHORIZED);
}
String inbox = sendGridTokenVerifier.extractInbox(authorization.substring(7));
sendGridEmailFactory.getEmailsFromRequest(form, inbox)
.forEach((unsaved) -> {
EmailRecord saved = emailRepository.save(unsaved);
try {
emailWebSocketHandler.broadcastNewEmailMessage(saved);
} catch (IOException e) {
e.printStackTrace();
}
});
return new ResponseEntity<>("", HttpStatus.ACCEPTED);
}
示例4: createServiceInstance
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@RequestMapping(value = "/service_instances/{instanceId}", method = RequestMethod.PUT)
public ResponseEntity<ServiceInstanceResponse> createServiceInstance(
@PathVariable("instanceId") String serviceInstanceId,
@RequestParam(value = "accepts_incomplete", required = false) Boolean acceptsIncomplete,
@Valid @RequestBody ServiceInstanceRequest request) throws ServiceDefinitionDoesNotExistException,
ServiceInstanceExistsException, ServiceBrokerException, AsyncRequiredException {
if (acceptsIncomplete == null) {
throw new AsyncRequiredException();
}
log.debug("PUT: " + SERVICE_INSTANCE_BASE_PATH + "/{instanceId}"
+ ", createServiceInstance(), serviceInstanceId = " + serviceInstanceId);
ServiceDefinition svc = catalogService.getServiceDefinition(request.getServiceDefinitionId());
if (svc == null) {
throw new ServiceDefinitionDoesNotExistException(request.getServiceDefinitionId());
}
ServiceInstanceResponse response = deploymentService.createServiceInstance(serviceInstanceId,
request.getServiceDefinitionId(), request.getPlanId(), request.getOrganizationGuid(),
request.getSpaceGuid(), request.getParameters(), request.getContext());
if (DashboardUtils.hasDashboard(svc))
response.setDashboardUrl(DashboardUtils.dashboard(svc, serviceInstanceId));
log.debug("ServiceInstance Created: " + serviceInstanceId);
if (response.isAsync())
return new ResponseEntity<ServiceInstanceResponse>(response, HttpStatus.ACCEPTED);
else
return new ResponseEntity<ServiceInstanceResponse>(response, HttpStatus.CREATED);
}
示例5: handleThingsboardException
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@ExceptionHandler(Exception.class)
public void handleThingsboardException(Exception exception, HttpServletResponse response) {
log.debug("Processing exception {}", exception.getMessage(), exception);
if (!response.isCommitted()) {
try {
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
if (exception instanceof SecurityException) {
response.setStatus(HttpStatus.FORBIDDEN.value());
mapper.writeValue(response.getWriter(),
new HttpRequestProcessingError("You don't have permission to perform this operation!"));
} else {
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
mapper.writeValue(response.getWriter(), new HttpRequestProcessingError(exception.getMessage()));
}
} catch (IOException e) {
log.error("Can't handle exception", e);
}
}
}
示例6: exception
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@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"));
if (throwable != null && throwable.getCause() != null) {
sb.append(" root cause: ").append(throwable.getCause());
}
model.addAttribute("error", sb.toString());
ModelAndView mav = new ModelAndView();
mav.addObject("error", sb.toString());
mav.setViewName("error");
return mav;
}
示例7: setErrorsResponse
import org.springframework.http.HttpStatus; //导入依赖的package包/类
public void setErrorsResponse(Errors errors, HttpStatus responseHttpStatus, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setStatus(responseHttpStatus.value());
HttpResponseData responseData = getResponseData(errors, request);
if (responseData != null) {
response.addHeader(CONTENT_TYPE, responseData.getContentType());
response.getWriter().write(responseData.getBody());
}
}
示例8: envPostAvailable
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@Test
public void envPostAvailable() {
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().postForEntity(
"http://localhost:" + port + "/admin/env", form, Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
}
示例9: verifyRegenerate
import org.springframework.http.HttpStatus; //导入依赖的package包/类
void verifyRegenerate(ResponseEntity<CredentialDetails<T>> expectedResponse) {
Map<String, Object> request = new HashMap<String, Object>() {{
put("name", NAME.getName());
}};
when(restTemplate.exchange(eq(REGENERATE_URL_PATH), eq(POST),
eq(new HttpEntity<>(request)), isA(ParameterizedTypeReference.class)))
.thenReturn(expectedResponse);
if (!expectedResponse.getStatusCode().equals(HttpStatus.OK)) {
try {
credHubTemplate.regenerate(NAME);
fail("Exception should have been thrown");
}
catch (CredHubException e) {
assertThat(e.getMessage(), containsString(expectedResponse.getStatusCode().toString()));
}
}
else {
CredentialDetails<T> response = credHubTemplate.regenerate(NAME);
assertDetailsResponseContainsExpectedCredential(expectedResponse, response);
}
}
示例10: authorize
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@PostMapping("/authenticate")
@Timed
public ResponseEntity authorize(@Valid @RequestBody LoginVM loginVM, HttpServletResponse response) {
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginVM.getUsername(), loginVM.getPassword());
try {
Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);
return ResponseEntity.ok(new JWTToken(jwt));
} catch (AuthenticationException ae) {
log.trace("Authentication exception trace: {}", ae);
return new ResponseEntity<>(Collections.singletonMap("AuthenticationException",
ae.getLocalizedMessage()), HttpStatus.UNAUTHORIZED);
}
}
示例11: vote
import org.springframework.http.HttpStatus; //导入依赖的package包/类
/**
* POST /posts/:id -> get the "id" post.
*/
@RequestMapping(value = "/posts/{id:\\d+}/vote",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<PostVoteDTO> vote(@PathVariable Long id, @RequestParam(required = true) String type) {
log.debug("REST request to vote-up Post : {}", id);
Post post = postRepository.findByStatusAndId(PostStatus.PUBLIC, id);
if (post == null || !(type.equals("up") || type.equals("down"))) {
return new ResponseEntity<>(new PostVoteDTO(), HttpStatus.UNPROCESSABLE_ENTITY);
}
String result;
if (type.equals("up")) {
result = voteService.voteUp(post, userService.getUserWithAuthorities());
} else {
result = voteService.voteDown(post, userService.getUserWithAuthorities());
}
return new ResponseEntity<>(new PostVoteDTO(post, result), HttpStatus.OK);
}
示例12: processException
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorVM> processException(Exception ex) {
log.error(ex.getMessage(), ex);
BodyBuilder builder;
ErrorVM errorVM;
ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class);
if (responseStatus != null) {
builder = ResponseEntity.status(responseStatus.value());
errorVM = new ErrorVM("error." + responseStatus.value().value(), responseStatus.reason());
} else {
builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error");
}
return builder.body(errorVM);
}
示例13: handleError
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@RequestMapping("/error")
public String handleError(HttpServletRequest request, HttpServletResponse response, Model model) {
int code = response.getStatus();
String message = HttpStatus.valueOf(code).getReasonPhrase();
model.addAttribute("code", code);
model.addAttribute("message", message);
LOG.info(String.format("HTTP error: %s, %s on request %s '%s' caused by %s",
code, message,
request.getMethod(), request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI),
LogUtil.getUserInfo(request)));
return "error";
}
示例14: verifyGoodTwitterConnectionSettings
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@Test
@Ignore
public void verifyGoodTwitterConnectionSettings() throws IOException {
final Properties credentials = new Properties();
try (InputStream is = getClass().getResourceAsStream("/valid-twitter-keys.properties")) {
credentials.load(is);
}
final ResponseEntity<Verifier.Result> response = post("/api/v1/connectors/twitter/verifier/connectivity", credentials,
Verifier.Result.class);
assertThat(response.getStatusCode()).as("component list status code").isEqualTo(HttpStatus.OK);
final Verifier.Result result = response.getBody();
assertThat(result).isNotNull();
assertThat(result.getStatus()).isEqualTo(Verifier.Result.Status.OK);
assertThat(result.getErrors()).isEmpty();
}
示例15: testPrintRestResult
import org.springframework.http.HttpStatus; //导入依赖的package包/类
@Test
public void testPrintRestResult() {
assertEquals("status=OK, body=null", LogObjectPrinter.printRestResult(null).toString());
assertEquals("status=OK, body=value1", LogObjectPrinter.printRestResult("value1").toString());
assertEquals("status=OK, body=[<ArrayList> size = 5]",
LogObjectPrinter.printRestResult(Arrays.asList(1, 2, 3, 4, 5)).toString());
when(responseEntity.getStatusCode()).thenReturn(HttpStatus.OK);
when(responseEntity.getBody()).thenReturn(null);
assertEquals("status=200, body=", LogObjectPrinter.printRestResult(responseEntity).toString());
when(responseEntity.getBody()).thenReturn("value1");
assertEquals("status=200, body=value1", LogObjectPrinter.printRestResult(responseEntity).toString());
when(responseEntity.getBody()).thenReturn(Arrays.asList(1, 2, 3, 4, 5));
assertEquals("status=200, body=[<ArrayList> size = 5]",
LogObjectPrinter.printRestResult(responseEntity).toString());
}