当前位置: 首页>>代码示例>>Java>>正文


Java HttpStatus类代码示例

本文整理汇总了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));
}
 
开发者ID:spring-sprout,项目名称:osoon,代码行数:8,代码来源:TopicService.java

示例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);
}
 
开发者ID:JUGIstanbul,项目名称:second-opinion-api,代码行数:25,代码来源:TreatmentControllerIT.java

示例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);
}
 
开发者ID:Stubmarine,项目名称:stubmarine,代码行数:24,代码来源:SendGridController.java

示例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);
}
 
开发者ID:evoila,项目名称:cfsummiteu2017,代码行数:35,代码来源:ServiceInstanceController.java

示例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);
        }
    }
}
 
开发者ID:thingsboard,项目名称:thingsboard-gateway,代码行数:20,代码来源:HttpController.java

示例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;
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:21,代码来源:ErrorController.java

示例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());
    }
}
 
开发者ID:mkopylec,项目名称:errorest-spring-boot-starter,代码行数:9,代码来源:ErrorsHttpResponseSetter.java

示例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());
}
 
开发者ID:zhaoqilong3031,项目名称:spring-cloud-samples,代码行数:9,代码来源:ApplicationTests.java

示例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);
	}
}
 
开发者ID:spring-projects,项目名称:spring-credhub,代码行数:25,代码来源:CredHubTemplateDetailUnitTestsBase.java

示例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);
    }
}
 
开发者ID:deepu105,项目名称:spring-io,代码行数:21,代码来源:UserJWTController.java

示例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);
}
 
开发者ID:ugouku,项目名称:shoucang,代码行数:25,代码来源:PostResource.java

示例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);
}
 
开发者ID:deepu105,项目名称:spring-io,代码行数:16,代码来源:ExceptionTranslator.java

示例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";
}
 
开发者ID:kalsowerus,项目名称:Guestbook9001,代码行数:15,代码来源:ExceptionController.java

示例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();
}
 
开发者ID:syndesisio,项目名称:syndesis,代码行数:17,代码来源:ConnectorsITCase.java

示例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());

}
 
开发者ID:xm-online,项目名称:xm-gate,代码行数:21,代码来源:LogObjectPrinterTest.java


注:本文中的org.springframework.http.HttpStatus类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。