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: second-opinion-api   File: TreatmentControllerIT.java   Source Code and License 9 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 2
Project: stubmarine   File: SendGridController.java   Source Code and License 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 3
Project: osoon   File: TopicService.java   Source Code and License 7 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 4
Project: cfsummiteu2017   File: ServiceInstanceController.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
}
 
Example 41
Project: keti   File: AccessControlServiceIT.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider = "endpointProvider")
public void testPolicyEvalNotApplicable(final String endpoint) throws Exception {
    String testPolicyName = null;
    try {
        this.privilegeHelper.putSubject(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(), MARISSA_V1,
                this.acsitSetUpFactory.getAcsUrl(), this.acsitSetUpFactory.getZone1Headers(),
                this.privilegeHelper.getDefaultAttribute());

        String policyFile = "src/test/resources/policy-set-with-multiple-policies-na-with-condition.json";
        testPolicyName = this.policyHelper.setTestPolicy(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(),
                this.acsitSetUpFactory.getZone1Headers(), endpoint, policyFile);

        PolicyEvaluationRequestV1 policyEvaluationRequest = this.policyHelper
                .createEvalRequest(MARISSA_V1.getSubjectIdentifier(), "sanramon");
        ResponseEntity<PolicyEvaluationResult> postForEntity = this.acsitSetUpFactory.getAcsZoneAdminRestTemplate()
                .postForEntity(endpoint + PolicyHelper.ACS_POLICY_EVAL_API_PATH,
                        new HttpEntity<>(policyEvaluationRequest, this.acsitSetUpFactory.getZone1Headers()),
                        PolicyEvaluationResult.class);

        Assert.assertEquals(postForEntity.getStatusCode(), HttpStatus.OK);
        PolicyEvaluationResult responseBody = postForEntity.getBody();
        Assert.assertEquals(responseBody.getEffect(), Effect.NOT_APPLICABLE);
    } catch (Exception e) {
        Assert.fail("testPolicyEvalNotApplicable should have NOT failed " + endpoint + " " + e.getMessage());
    } finally {
        this.policyHelper.deletePolicySet(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(),
                this.acsitSetUpFactory.getAcsUrl(), testPolicyName, this.acsitSetUpFactory.getZone1Headers());
        this.privilegeHelper.deleteSubject(this.acsitSetUpFactory.getAcsZoneAdminRestTemplate(),
                this.acsitSetUpFactory.getAcsUrl(), MARISSA_V1.getSubjectIdentifier(),
                this.acsitSetUpFactory.getZone1Headers());
    }
}
 
Example 42
Project: nixmash-blog   File: PermaPostsController.java   Source Code and License 5 votes vote down vote up
@ResponseStatus(HttpStatus.MOVED_PERMANENTLY)
@GetMapping(value = "/{category:java|linux|postgresql|mysql|wordpress|android|codejohnny}/{postName}")
public String categoryPost() {
    return "redirect:/post/{postName}";
}
 
Example 43
Project: fwm   File: Webservice1_5Controller.java   Source Code and License 5 votes vote down vote up
@RequestMapping("getEvent/{id}")
public @ResponseBody ResponseEntity<String> getEvent(@PathVariable("id") int id, HttpServletRequest request, HttpServletResponse response){
	String json;
	try{
		Event ev = Backend.getEventDao().getFullEvent(id);
		if(showLogic(ev) && ev != null){
			JsonHelper help = new JsonHelper(ev.toOneFiveJsonString());
			Region curReg = null;
			if(ev.getRegion() != null){
				curReg = Backend.getRegionDao().getRegion(ev.getRegion().getID()); 
			}
			// add our god
			if(showLogic(curReg)){
				help.addRawString("region", curReg.toOneFiveJsonString());
			}else
			{
				help.addAttribute("region", null);
			}
			// should in theory work for every type of searchable list... 
			addListToHelper("npcs", App.toListSearchable(ev.getNpcs()), help);
			addListToHelper("gods", App.toListSearchable(ev.getGods()), help);
			json = help.getString();
		}else
		{
			throw new Exception("This " + Event.WHAT_IT_DO +  " is not showable.");
		}
	}
	catch(Exception e){
		json = "{\"Message\":\"" + e.getLocalizedMessage() + "\"}";
	}
	HttpHeaders headers = new HttpHeaders();
	headers.set("Content-Type", "application/json");
	
   	return new ResponseEntity<String>(json, headers, HttpStatus.CREATED);
}
 
Example 44
Project: spring-boot-tus   File: TusExceptionsCotroller.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(value = { TusDBFileNotFoundException.class })
@ResponseStatus(HttpStatus.NOT_FOUND)
public TusException VideoNotFoundExceptionHandler(TusDBFileNotFoundException e, WebRequest req) {
    e.printStackTrace();

    TusException err = new TusException("not found", e);
    return err;
}
 
Example 45
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    String errorMessage = (throwable != null ? throwable.getMessage() : "Unknown error");
    model.addAttribute("error", errorMessage);
    return "error";
}
 
Example 46
Project: RestAndSpringMVC-CodingChallenge   File: MainRestController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/rest/history",  method = RequestMethod.GET)
public ResponseEntity<List<HistoryEntity>> getHistories(@RequestParam(value="access_key", defaultValue = "") String accessKey) {
    if(ACCESS_KEY.equals(accessKey)) {
        return ResponseEntity.ok(Lists.newArrayList(historyRepository.findAll()));
    } else {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
    }
}
 
Example 47
Project: devoxxus-jhipster-microservices-demo   File: EurekaResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /eureka/status : get Eureka status
 */
@GetMapping("/eureka/status")
@Timed
public ResponseEntity<EurekaDTO> eurekaStatus() {

    EurekaDTO eurekaDTO = new EurekaDTO();
    eurekaDTO.setStatus(getEurekaStatus());
    return new ResponseEntity<>(eurekaDTO, HttpStatus.OK);
}
 
Example 48
Project: metamodel-membrane   File: RestErrorHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Query parsing exception - mapped to BAD_REQUEST.
 * 
 * @param ex
 * @return
 */
@ExceptionHandler(QueryParserException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public RestErrorResponse processQueryParsingError(QueryParserException ex) {
    return new RestErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
}
 
Example 49
Project: devoxxus-jhipster-microservices-demo   File: SshResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  / : get the SSH public key
 */
@GetMapping(value = "/ssh/public_key", produces = MediaType.TEXT_PLAIN_VALUE)
@Timed
public ResponseEntity<String> eureka() {
    try {
        String publicKey = new String(Files.readAllBytes(
            Paths.get(System.getProperty("user.home") + "/.ssh/id_rsa.pub")));

        return new ResponseEntity<>(publicKey, HttpStatus.OK);
    } catch (IOException e) {
        log.warn("SSH public key could not be loaded: {}", e.getMessage());
        return new ResponseEntity<>("", HttpStatus.NOT_FOUND);
    }
}
 
Example 50
Project: stuffEngine   File: CertificateController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(name ="17", value = "", method = RequestMethod.POST, consumes = {"application/json; charset=UTF-8"} )
public ResponseEntity<?> createCertificate(@RequestBody Certificate certificate, HttpServletRequest request) {
    logger.info("Получен request на создание сертификата");
    logger.info("Cоздаваемый сертификат: " + certificate.toString());
    Certificate certificate1 = certificateService.create(certificate);
    return new ResponseEntity<>(certificate1, HttpStatus.CREATED);
}
 
Example 51
Project: speakTogether   File: AccountResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /activate : activate the registered user.
 *
 * @param key the activation key
 * @return the ResponseEntity with status 200 (OK) and the activated user in body, or status 500 (Internal Server Error) if the user couldn't be activated
 */
@GetMapping("/activate")
@Timed
public ResponseEntity<String> activateAccount(@RequestParam(value = "key") String key) {
    return userService.activateRegistration(key)
        .map(user -> new ResponseEntity<String>(HttpStatus.OK))
        .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
}
 
Example 52
Project: codemotion-2017-taller-de-jhipster   File: TaskResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /tasks : get all the tasks.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of tasks in body
 */
@GetMapping("/tasks")
@Timed
public ResponseEntity<List<Task>> getAllTasks(@ApiParam Pageable pageable) {
    log.debug("REST request to get a page of Tasks");
    final Page<Task> page;
    if (SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)) {
    	page = this.taskRepository.findAll(pageable);
    } else {
    	page = this.taskRepository.findAllByUser(SecurityUtils.getCurrentUserLogin(), pageable);
    }
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tasks");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 53
Project: swaggy-jenkins   File: BlueApiController.java   Source Code and License 5 votes vote down vote up
public ResponseEntity<GithubScm> getSCM(@ApiParam(value = "Name of the organization",required=true ) @PathVariable("organization") String organization,
    @ApiParam(value = "Name of SCM",required=true ) @PathVariable("scm") String scm,
    @RequestHeader(value = "Accept", required = false) String accept) throws Exception {
    // do some magic!

    if (accept != null && accept.contains("application/json")) {
        return new ResponseEntity<GithubScm>(objectMapper.readValue("{  \"_links\" : {    \"self\" : {      \"_class\" : \"_class\",      \"href\" : \"href\"    },    \"_class\" : \"_class\"  },  \"credentialId\" : \"credentialId\",  \"_class\" : \"_class\",  \"id\" : \"id\",  \"uri\" : \"uri\"}", GithubScm.class), HttpStatus.OK);
    }

    return new ResponseEntity<GithubScm>(HttpStatus.OK);
}
 
Example 54
Project: Practical-Microservices   File: UserController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(method = RequestMethod.DELETE, value = "{userId}", produces = "application/json", consumes = "application/json")
public ResponseEntity<String> deleteUser(@PathVariable("userId") UUID userId) {
	logger.debug(deleteUser + " deleting user with Id " + userId);
	userService.deleteUser(userId);
	return new ResponseEntity<>(HttpStatus.CREATED);
}
 
Example 55
Project: bxbot-ui-server   File: EngineConfigController.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the Engine Config for a Bot id.
 *
 * @param user  the authenticated user making the request.
 * @param botId the id of the Bot to fetch the Engine config for.
 * @return the Engine configuration.
 */
@PreAuthorize("hasRole('USER')")
@RequestMapping(value = "/{botId}" + ENGINE_RESOURCE_PATH, method = RequestMethod.GET)
public ResponseEntity<?> getEngine(@AuthenticationPrincipal User user, @PathVariable String botId) {

    LOG.info("GET " + CONFIG_ENDPOINT_BASE_URI + botId + ENGINE_RESOURCE_PATH + " - getEngine() "); //- caller: " + user.getUsername());

    final EngineConfig engineConfig = engineConfigService.getEngineConfig(botId);
    return engineConfig == null
            ? new ResponseEntity<>(HttpStatus.NOT_FOUND)
            : buildResponseEntity(engineConfig, HttpStatus.OK);
}
 
Example 56
Project: open-kilda   File: SwitchController.java   Source Code and License 5 votes vote down vote up
/**
 * Get all available links.
 *
 * @return list of links.
 */
@ApiOperation(value = "Get all available switches", response = SwitchDto.class)
@ApiResponses(value = {
        @ApiResponse(code = 200, response = FlowPayload.class, message = "Operation is successful"),
        @ApiResponse(code = 400, response = MessageError.class, message = "Invalid input data"),
        @ApiResponse(code = 401, response = MessageError.class, message = "Unauthorized"),
        @ApiResponse(code = 403, response = MessageError.class, message = "Forbidden"),
        @ApiResponse(code = 404, response = MessageError.class, message = "Not found"),
        @ApiResponse(code = 500, response = MessageError.class, message = "General error"),
        @ApiResponse(code = 503, response = MessageError.class, message = "Service unavailable")})
@GetMapping(path = "/switches")
@ResponseStatus(HttpStatus.OK)
public List<SwitchDto> getSwitches() {
    return switchService.getSwitches();
}
 
Example 57
Project: pcc-like   File: RestResponseEntityExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(Error.class)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
protected ErrorResult handleError(Error ex) {
	logger.error(ex.getMessage(), ex);
	return new ErrorResult(2000, "系统错误");
}
 
Example 58
Project: spring-cloud-samples   File: ApplicationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void configurationAvailable() {
	@SuppressWarnings("rawtypes")
	ResponseEntity<Map> entity = new TestRestTemplate().getForEntity(
			"http://localhost:" + port + "/app/cloud", Map.class);
	assertEquals(HttpStatus.OK, entity.getStatusCode());
}
 
Example 59
Project: gauravbytes   File: UserController.java   Source Code and License 5 votes vote down vote up
@PostMapping
public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
	logger.info("Registering user: {} ", user);
	if (userService.userExists(user)) {
		logger.warn("User with username: {} already exists...", user.getUsername());
		return new ResponseEntity<Void>(HttpStatus.CONFLICT);
	}

	userService.saveUser(user);

	URI uri = ucBuilder.path("/users/{id}").buildAndExpand(user.getId()).toUri();
	return ResponseEntity.created(uri).build();
}
 
Example 60
Project: stuffEngine   File: CertificateController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(name ="19",value = "/empid/{empID}", method = RequestMethod.GET)
public ResponseEntity<?> readAllCertsByEmpID(@PathVariable(name = "empID") int empID,  HttpServletRequest request) {
    logger.info("Получен request на чтение всех сертификатов сотрудника с ID: " + empID);
    List<Certificate> allCerts = certificateService.readAllCertsByEmpID(empID);
    logger.info("Возвращаемые сертификаты сотрудника: " + allCerts);
    for (Certificate cert : allCerts) logger.info(cert.toString());
    return new ResponseEntity<>(allCerts, HttpStatus.OK);
}