Java Code Examples for org.springframework.http.HttpStatus

The following are top voted examples for showing how to use org.springframework.http.HttpStatus. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: osoon   File: TopicService.java   View source code 8 votes vote down vote up
public Topic create(String name) {
	if (repository.findByName(name).isPresent()) {
		throw new HttpClientErrorException(HttpStatus.CONFLICT, name + " 이미 등록된 태그 입니다.");
	}

	return repository.save(new Topic(name));
}
 
Example 2
Project: second-opinion-api   File: TreatmentControllerIT.java   View source code 8 votes vote down vote up
@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);
}
 
Example 3
Project: stubmarine   File: SendGridController.java   View source code 7 votes vote down vote up
@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);
}
 
Example 4
Project: cfsummiteu2017   File: ServiceInstanceController.java   View source code 7 votes vote down vote up
@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);
}
 
Example 5
Project: thingsboard-gateway   File: HttpController.java   View source code 7 votes vote down vote up
@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);
        }
    }
}
 
Example 6
Project: Spring-Security-Third-Edition   File: ErrorController.java   View source code 7 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"));

    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;
}
 
Example 7
Project: errorest-spring-boot-starter   File: ErrorsHttpResponseSetter.java   View source code 7 votes vote down vote up
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());
    }
}
 
Example 8
Project: spring-cloud-samples   File: ApplicationTests.java   View source code 7 votes vote down vote up
@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());
}
 
Example 9
Project: spring-credhub   File: CredHubTemplateDetailUnitTestsBase.java   View source code 7 votes vote down vote up
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);
	}
}
 
Example 10
Project: spring-io   File: UserJWTController.java   View source code 7 votes vote down vote up
@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);
    }
}
 
Example 11
Project: shoucang   File: PostResource.java   View source code 7 votes vote down vote up
/**
 * 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);
}
 
Example 12
Project: spring-io   File: ExceptionTranslator.java   View source code 6 votes vote down vote up
@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);
}
 
Example 13
Project: Guestbook9001   File: ExceptionController.java   View source code 6 votes vote down vote up
@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";
}
 
Example 14
Project: syndesis   File: ConnectorsITCase.java   View source code 6 votes vote down vote up
@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();
}
 
Example 15
Project: xm-gate   File: LogObjectPrinterTest.java   View source code 6 votes vote down vote up
@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());

}
 
Example 16
Project: cf-java-client-sap   File: CloudControllerClientImpl.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 17
Project: mirrorgate   File: ReviewControllerTests.java   View source code 6 votes vote down vote up
@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()));
}
 
Example 18
Project: sentry   File: ExceptionTranslator.java   View source code 6 votes vote down vote up
@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);
}
 
Example 19
Project: second-opinion-api   File: MedicineControllerIT.java   View source code 6 votes vote down vote up
@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);
}
 
Example 20
Project: multi-tenant-rest-api   File: ResourcesController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 21
Project: WeiMusicCommunity-server   File: PathController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 22
Project: plumdo-work   File: FormModelEditorResource.java   View source code 5 votes vote down vote up
@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;
}
 
Example 23
Project: spring-reactive-sample   File: DemoApplicationTests.java   View source code 5 votes vote down vote up
@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));
}
 
Example 24
Project: xxproject   File: CustomRestExceptionHandler.java   View source code 5 votes vote down vote up
@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);
}
 
Example 25
Project: errorest-spring-boot-starter   File: ErrorData.java   View source code 5 votes vote down vote up
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;
}
 
Example 26
Project: smockin   File: MockedServerEngineController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 27
Project: keti   File: ZoneDoesNotExistExceptionHandler.java   View source code 5 votes vote down vote up
@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");
            }});
}
 
Example 28
Project: cf-mta-deploy-service   File: CustomControllerClientErrorHandlerTest.java   View source code 5 votes vote down vote up
@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
            });
        }
 
Example 29
Project: plumdo-work   File: ExceptionHandlerAdvice.java   View source code 5 votes vote down vote up
@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);
}
 
Example 30
Project: QuizZz   File: QuestionController.java   View source code 5 votes vote down vote up
@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);
}
 
Example 31
Project: devops-cstack   File: RestUtils.java   View source code 5 votes vote down vote up
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;
}
 
Example 32
Project: ingest-core   File: GlobalStateExceptionHandler.java   View source code 5 votes vote down vote up
@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());
}
 
Example 33
Project: Mastering-Microservices-with-Java-9-Second-Edition   File: RestaurantServiceAPI.java   View source code 5 votes vote down vote up
@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);
}
 
Example 34
Project: errorest-spring-boot-starter   File: ExternalHttpRequestErrorDataProvider.java   View source code 5 votes vote down vote up
protected LoggingLevel getLoggingLevel(HttpStatus responseHttpStatus) {
    return responseHttpStatus.is4xxClientError() ? errorestProperties.getHttpClientError().getLoggingLevel() : ERROR;
}
 
Example 35
Project: role-api   File: MethodNotAllowedErrorHandlerTest.java   View source code 5 votes vote down vote up
@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));
}
 
Example 36
Project: ait-platform   File: AitMailSenderSrv.java   View source code 5 votes vote down vote up
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());
	}
}
 
Example 37
Project: second-opinion-api   File: CaseService.java   View source code 5 votes vote down vote up
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);
}
 
Example 38
Project: setra   File: ReceiveController.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 39
Project: patient-portal   File: ExceptionTranslator.java   View source code 5 votes vote down vote up
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseBody
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
public ErrorVM processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) {
    return new ErrorVM(ErrorConstants.ERR_METHOD_NOT_SUPPORTED, exception.getMessage());
}
 
Example 40
Project: osoon   File: MeetingAttendService.java   View source code 5 votes vote down vote up
@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);
}