Java 类org.springframework.http.HttpStatus 实例源码

项目:second-opinion-api    文件:TreatmentControllerIT.java   
@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);
}
项目:osoon    文件:TopicService.java   
public Topic create(String name) {
    if (repository.findByName(name).isPresent()) {
        throw new HttpClientErrorException(HttpStatus.CONFLICT, name + " 이미 등록된 태그 입니다.");
    }

    return repository.save(new Topic(name));
}
项目:thingsboard-gateway    文件:HttpController.java   
@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);
        }
    }
}
项目:shoucang    文件:PostResource.java   
/**
 * 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);
}
项目:stubmarine    文件:SendGridController.java   
@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);
}
项目:spring-io    文件:ExceptionTranslator.java   
@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);
}
项目:Guestbook9001    文件:ExceptionController.java   
@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";
}
项目:syndesis    文件:ConnectorsITCase.java   
@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();
}
项目:xm-gate    文件:LogObjectPrinterTest.java   
@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());

}
项目:cfsummiteu2017    文件:ServiceInstanceController.java   
@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);
}
项目:Spring-Security-Third-Edition    文件:ErrorController.java   
@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;
}
项目:errorest-spring-boot-starter    文件:ErrorsHttpResponseSetter.java   
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());
    }
}
项目:spring-cloud-samples    文件:ApplicationTests.java   
@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());
}
项目:spring-credhub    文件:CredHubTemplateDetailUnitTestsBase.java   
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);
    }
}
项目:spring-io    文件:UserJWTController.java   
@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);
    }
}
项目:cf-java-client-sap    文件:CloudControllerClientImpl.java   
/**
 * Get organization by given name.
 *
 * @param orgName
 * @param required
 * @return CloudOrganization instance
 */
public CloudOrganization getOrganization(String orgName, boolean required) {
    Map<String, Object> urlVars = new HashMap<String, Object>();
    String urlPath = "/v2/organizations?inline-relations-depth=1&q=name:{name}";
    urlVars.put("name", orgName);
    CloudOrganization org = null;
    List<Map<String, Object>> resourceList = getAllResources(urlPath, urlVars);
    if (resourceList.size() > 0) {
        Map<String, Object> resource = resourceList.get(0);
        org = resourceMapper.mapResource(resource, CloudOrganization.class);
    }

    if (org == null && required) {
        throw new CloudFoundryException(HttpStatus.NOT_FOUND, "Not Found", "Organization '" + orgName + "' not found.");
    }

    return org;
}
项目:mirrorgate    文件:ReviewControllerTests.java   
@Test
public void createReviewTest() throws Exception {
    Review review1 = createReview();
    Review review2 = createReview();

    List<Review> list = new ArrayList<>();
    list.add(review1);
    list.add(review2);

    Iterable<Review> reviews = list;

    List<String> ids = new ArrayList();
    ids.add(review1.getId().toString());
    ids.add(review2.getId().toString());

    when(reviewService.save(reviews)).thenReturn(ids);

    this.mockMvc.perform(post("/api/reviews")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(reviews)))
            .andExpect(status().is(HttpStatus.CREATED.value()));
}
项目:sentry    文件:ExceptionTranslator.java   
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorVM> processRuntimeException(Exception ex) {
    log.debug("Processing runtime exception", 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);
}
项目:second-opinion-api    文件:MedicineControllerIT.java   
@Test
public void should_save_medicine() throws Exception {
    // given

    // when
    ResponseEntity<Void> responseEntityResponseEntity = postMedicineAndGetResponse();

    //then
    URI location = responseEntityResponseEntity.getHeaders().getLocation();
    String id = extractIdStringFromURI(location);
    Medicine one = medicineRepository.findOne(Long.valueOf(id));

    assertThat(one).isNotNull();
    assertThat(location.toString()).
            isEqualTo("http://localhost:" + serverPort + "/api/v1/medicine/" + id);
    assertThat(one.getId()).isEqualTo(Long.valueOf(id));
    assertThat(responseEntityResponseEntity.getStatusCode()).isEqualTo(HttpStatus.CREATED);
}
项目:multi-tenant-rest-api    文件:ResourcesController.java   
@PreAuthorize("@roleChecker.hasValidRole(#principal)")
@RequestMapping(value="/company", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CompanyDTO> createCompany(
        Principal principal,
        @RequestBody CompanyDTO companyDTO) {

    // Check for SUPERADMIN role
    // RoleChecker.hasValidRole(principal);

    companyDTO = companyService.create(companyDTO);

    return new ResponseEntity<CompanyDTO>(companyDTO, HttpStatus.CREATED);
}
项目:WeiMusicCommunity-server    文件:PathController.java   
@RequestMapping(produces = "application/json")
public ResponseEntity<HttpJson> getPathTest(@RequestBody String test) {
    HttpJson inObj = new HttpJson(test);
    HttpJson json = new HttpJson();
    UserExtend ue = new UserExtend();
    json.setClassObject(ue);
    json.setClassName(String.class.toString());

    return new ResponseEntity<HttpJson>(json, HttpStatus.ACCEPTED);
}
项目:plumdo-work    文件:FormModelEditorResource.java   
@ApiOperation(value = "获取表单模型设计内容", notes = "根据表单模型的id来获取表单模型设计内容")
@ApiImplicitParam(name = "id", value = "表单模型ID", required = true, dataType = "Long", paramType = "path")
@RequestMapping(value = "/form-models/{id}/json", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
public String getEditorJson(@PathVariable Long id) throws UnsupportedEncodingException {
    FormModel formModel = getFormModelFromRequest(id);
    String editorJson = null;
    if (formModel.getEditorSourceBytes() == null) {
        editorJson = objectMapper.createArrayNode().toString();
    } else {
        editorJson = new String(formModel.getEditorSourceBytes(), "utf-8");
    }
    return editorJson;
}
项目:spring-reactive-sample    文件:DemoApplicationTests.java   
@Test
public void postCrudOperations() {
    int randomInt = new Random().nextInt();
    String title = "Post test " + randomInt;
    FluxExchangeResult<Void> postResult = client
        .mutate().filter(basicAuthentication("user", "password")).build()
        .post()
        .uri("/posts")
        .body(BodyInserters.fromObject(Post.builder().title(title).content("content of " + title).build()))
        .exchange()
        .expectStatus().isEqualTo(HttpStatus.CREATED)
        .returnResult(Void.class);

    URI location = postResult.getResponseHeaders().getLocation();
    assertNotNull(location);

    EntityExchangeResult<byte[]> getResult = client
        .get()
        .uri(location)
        .exchange()
        .expectStatus().isOk()
        .expectBody().jsonPath("$.title").isEqualTo(title)
        .returnResult();

    String getPost = new String(getResult.getResponseBody());
    assertTrue(getPost.contains(title));
}
项目:xxproject    文件:CustomRestExceptionHandler.java   
@ExceptionHandler({ OAuth2Exception.class })
public ResponseEntity<Object> handleOAuth2Exception(HttpClientErrorException ex, WebRequest request) {
    final String error = "Digits oauth authorization failed" ;
    final ApiError apiError = new ApiError(HttpStatus.FORBIDDEN, ex.getLocalizedMessage(), error);

    return new ResponseEntity<Object>(apiError, new HttpHeaders(), HttpStatus.FORBIDDEN);
}
项目:errorest-spring-boot-starter    文件:ErrorData.java   
protected ErrorData(String id, LoggingLevel loggingLevel, String requestMethod, String requestUri, HttpStatus responseStatus, List<Error> errors, Throwable throwable) {
    this.id = id;
    this.loggingLevel = loggingLevel;
    this.requestMethod = requestMethod;
    this.requestUri = requestUri;
    this.responseStatus = responseStatus;
    this.errors = errors;
    this.throwable = throwable;
}
项目:smockin    文件:MockedServerEngineController.java   
@RequestMapping(path="/mockedserver/jms/stop", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<?> stopJms() throws MockServerException {
    mockedServerEngineService.shutdownJms();
    return new ResponseEntity<String>(HttpStatus.NO_CONTENT);
}
项目:keti    文件:ZoneDoesNotExistExceptionHandler.java   
@ExceptionHandler(ZoneDoesNotExistException.class)
public ResponseEntity<JSONObject> handleException(final ZoneDoesNotExistException e) {
    LOGGER.error(e.getMessage(), e);
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON)
            .body(new JSONObject() {{
                put("error",
                        HttpStatus.BAD_REQUEST.getReasonPhrase());
                put("message",
                        "Zone not found");
            }});
}
项目:cf-mta-deploy-service    文件:CustomControllerClientErrorHandlerTest.java   
@Parameters
        public static Iterable<Object[]> getParameters() throws IOException {
            return Arrays.asList(new Object[][] {
// @formatter:off
                // (0) The response body contains a description in the supported format:
                {
                    prepareHttpStatusCodeException(HttpStatus.BAD_GATEWAY, "Service broker error", "cf-error-response-body-0.json"),
                         new CloudFoundryException(HttpStatus.BAD_GATEWAY, "Service broker error", "Application currency-services-core-uaa-dev1!i211 does not exist"),
                },
                // (1) The response body does not contain a description (but does contain other information in a JSON format):
                {
                    prepareHttpStatusCodeException(HttpStatus.BAD_GATEWAY, "Service broker error", "cf-error-response-body-1.json"),
                         new CloudFoundryException(HttpStatus.BAD_GATEWAY, "Service broker error", null),
                },
                // (2) The response body contains a description in an unsupported format:
                {
                    prepareHttpStatusCodeException(HttpStatus.BAD_GATEWAY, "Service broker error", "cf-error-response-body-2.json"),
                         new CloudFoundryException(HttpStatus.BAD_GATEWAY, "Service broker error", null),
                },
                // (3) The response body contains a description in an unsupported format:
                {
                    prepareHttpStatusCodeException(HttpStatus.BAD_GATEWAY, "Service broker error", "cf-error-response-body-3.json"),
                         new CloudFoundryException(HttpStatus.BAD_GATEWAY, "Service broker error", null),
                },
// @formatter:on
            });
        }
项目:plumdo-work    文件:ExceptionHandlerAdvice.java   
@ResponseStatus(HttpStatus.BAD_REQUEST)
// 400
@ExceptionHandler(HttpMessageConversionException.class)
@ResponseBody
public ErrorInfo handleBadMessageConversion(HttpMessageConversionException e) {
    LOGGER.error("Bad request", e);
    return new ErrorInfo("Bad request", e);
}
项目:QuizZz    文件:QuestionController.java   
@RequestMapping(value = "/{question_id}", method = RequestMethod.DELETE)
@PreAuthorize("isAuthenticated()")
@ResponseStatus(HttpStatus.OK)
public void delete(@PathVariable Long question_id) {
    Question question = questionService.find(question_id);
    questionService.delete(question);
}
项目:devops-cstack    文件:RestUtils.java   
public Map<String, Object> sendPostForUpload( String url, String path, Log log )
    throws IOException
{
    File file = new File( path );
    FileInputStream fileInputStream = new FileInputStream( file );
    fileInputStream.available();
    fileInputStream.close();
    FileSystemResource resource = new FileSystemResource( file );
    Map<String, Object> params = new HashMap<>();
    params.put( "file", resource );
    RestTemplate restTemplate = new RestTemplate();
    MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>();
    postParams.setAll( params );
    Map<String, Object> response = new HashMap<String, Object>();
    HttpHeaders headers = new HttpHeaders();
    headers.set( "Content-Type", "multipart/form-data" );
    headers.set( "Accept", "application/json" );
    headers.add( "Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get( 0 ).getValue() );
    org.springframework.http.HttpEntity<Object> request =
        new org.springframework.http.HttpEntity<Object>( postParams, headers );
    ResponseEntity<?> result = restTemplate.exchange( url, HttpMethod.POST, request, String.class );
    String body = result.getBody().toString();
    MediaType contentType = result.getHeaders().getContentType();
    HttpStatus statusCode = result.getStatusCode();
    response.put( "content-type", contentType );
    response.put( "statusCode", statusCode );
    response.put( "body", body );

    return response;
}
项目:ingest-core    文件:GlobalStateExceptionHandler.java   
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(IllegalStateException.class)
public @ResponseBody
ExceptionInfo handleIllegalStateException(HttpServletRequest request, Exception e) {
    getLog().warn(String.format("Attempted an illegal state transition at '%s';" +
                    "this will generate a CONFLICT RESPONSE",
            request.getRequestURL().toString()));
    getLog().debug("Handling IllegalStateException and returning CONFLICT response", e);
    return new ExceptionInfo(request.getRequestURL().toString(), e.getLocalizedMessage());
}
项目:Mastering-Microservices-with-Java-9-Second-Edition    文件:RestaurantServiceAPI.java   
@RequestMapping("/restaurants/{restaurant-id}")
@HystrixCommand(fallbackMethod = "defaultRestaurant")
public ResponseEntity<Restaurant> getRestaurant(
        @PathVariable("restaurant-id") int restaurantId) {
    MDC.put("restaurantId", restaurantId);
    String url = "http://restaurant-service/v1/restaurants/" + restaurantId;
    LOG.debug("GetRestaurant from URL: {}", url);

    ResponseEntity<Restaurant> result = restTemplate.getForEntity(url, Restaurant.class);
    LOG.info("GetRestaurant http-status: {}", result.getStatusCode());
    LOG.debug("GetRestaurant body: {}", result.getBody());

    return new ResponseEntity<>(result.getBody(), HttpStatus.OK);
}
项目:errorest-spring-boot-starter    文件:ExternalHttpRequestErrorDataProvider.java   
protected LoggingLevel getLoggingLevel(HttpStatus responseHttpStatus) {
    return responseHttpStatus.is4xxClientError() ? errorestProperties.getHttpClientError().getLoggingLevel() : ERROR;
}
项目:role-api    文件:MethodNotAllowedErrorHandlerTest.java   
@Test
public void check_Response405_ReturnTrue() {
    HttpServletRequest request = new MockHttpServletRequest();
    HttpServletResponse response = new MockHttpServletResponse();
    response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());

    boolean check = HANDLER.check(request, response);

    assertThat(check, is(Boolean.TRUE));
}
项目:ait-platform    文件:AitMailSenderSrv.java   
private void addAttachment(final MimeMessageHelper helper, final String filePath) throws MessagingException {
    if (filePath != null) {
        String fileName = filePath.substring(filePath.lastIndexOf(IAitConstants.SEPARATOR) + 1);
        FileSystemResource file = new FileSystemResource(new File(filePath));
        helper.addAttachment(fileName, file);
    } else {
        throw new AitException(HttpStatus.BAD_REQUEST, "El path del archivo es nulo", "Mensaje: " + helper.getMimeMessage().getSubject());
    }
}
项目:second-opinion-api    文件:CaseService.java   
public ResponseEntity deleteCase(Long caseId) {
    Case tempCase = caseRepository.findOne(caseId);
    if (tempCase == null)
        throw new EntityNotFoundException("entity.notFound");
    tempCase.setModelStatus(ModelStatus.DELETED);
    caseRepository.save(tempCase);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
项目:setra    文件:ReceiveController.java   
/**
 * Download attached file.
 */
@GetMapping("/file/{id:[a-f0-9]{64}}/{key:[a-f0-9]{64}}")
public ResponseEntity<StreamingResponseBody> file(@PathVariable("id") final String id,
                                                  @PathVariable("key") final String keyHex,
                                                  final HttpSession session) {

    final KeyIv keyIv =
        new KeyIv(BaseEncoding.base16().lowerCase().decode(keyHex), resolveFileIv(id, session));

    final DecryptedFile decryptedFile = messageService.resolveStoredFile(id, keyIv);

    final HttpHeaders headers = new HttpHeaders();

    // Set application/octet-stream instead of the original mime type to force download
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

    if (decryptedFile.getName() != null) {
        headers.setContentDispositionFormData("attachment", decryptedFile.getName(),
            StandardCharsets.UTF_8);
    }
    headers.setContentLength(decryptedFile.getOriginalFileSize());

    final StreamingResponseBody body = out -> {
        try (final InputStream in = messageService.getStoredFileInputStream(id, keyIv)) {
            ByteStreams.copy(in, out);
            out.flush();
        }

        messageService.burnFile(id);
    };

    return new ResponseEntity<>(body, headers, HttpStatus.OK);
}
项目:patient-portal    文件:ExceptionTranslator.java   
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseBody
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
public ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) {
    return new ErrorVM(ErrorConstants.ERR_METHOD_NOT_SUPPORTED, exception.getMessage());
}
项目:osoon    文件:MeetingAttendService.java   
@Transactional
public void attendCancel(Meeting meeting, User user) {
    if (meeting.isAttendBy(user)) {
        meeting.attendCancel(user);
    } else {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "취소할 수 없습니다.");
    }
    repository.save(meeting);
}