Java Code Examples for org.springframework.web.server.ResponseStatusException

The following examples show how to use org.springframework.web.server.ResponseStatusException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: kafka-graphs   Source File: GraphAlgorithmHandler.java    License: Apache License 2.0 6 votes vote down vote up
public Mono<ServerResponse> run(ServerRequest request) {
    List<String> appIdHeaders = request.headers().header(X_KGRAPH_APPID);
    String appId = request.pathVariable("id");
    return request.bodyToMono(GraphAlgorithmRunRequest.class)
        .flatMapMany(input -> {
            log.debug("num iterations: {}", input.getNumIterations());
            PregelGraphAlgorithm<?, ?, ?, ?> algorithm = algorithms.get(appId);
            GraphAlgorithmState state = algorithm.run(input.getNumIterations());
            GraphAlgorithmStatus status = new GraphAlgorithmStatus(state);
            Flux<GraphAlgorithmStatus> states =
                proxyRun(appIdHeaders.isEmpty() ? group.getCurrentMembers().keySet() : Collections.emptySet(), appId, input);
            return Mono.just(status).mergeWith(states);
        })
        .onErrorMap(RuntimeException.class, e -> new ResponseStatusException(NOT_FOUND))
        .reduce((state1, state2) -> state1)
        .flatMap(state ->
            ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(state), GraphAlgorithmStatus.class)
        );

}
 
Example 2
Source Project: openvsx   Source File: UserAPI.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@PostMapping(
    path = "/user/token/delete/{id}",
    produces = MediaType.APPLICATION_JSON_VALUE
)
@Transactional(rollbackOn = ResponseStatusException.class)
public ResultJson deleteAccessToken(@PathVariable long id) {
    var principal = users.getOAuth2Principal();
    if (principal == null) {
        throw new ResponseStatusException(HttpStatus.FORBIDDEN);
    }
    var user = users.updateUser(principal);
    var token = repositories.findAccessToken(id);
    if (token == null || !token.isActive() || !token.getUser().equals(user)) {
        return ResultJson.error("Token does not exist.");
    }
    token.setActive(false);
    return ResultJson.success("Deleted access token for user " + user.getLoginName());
}
 
Example 3
@Test
public void verify_ResponseStatusException_with_TypeMismatchException_is_handled_generically_when_status_code_is_unexpected() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .log().all()
            .when()
            .get(TYPE_MISMATCH_WITH_UNEXPECTED_STATUS_ENDPOINT)
            .then()
            .log().all()
            .extract();

    // In this case the endpoint should throw a ResponseStatusException with a TypeMismatchException cause,
    //      but with an unexpected status code (403). Rather than treat it as a TypeMismatchException, we should
    //      get back a response that matches the desired status code.
    verifyErrorReceived(response, SampleCoreApiError.FORBIDDEN);
    ResponseStatusException ex = verifyResponseStatusExceptionSeenByBackstopper(
        ResponseStatusException.class, 403
    );
    TypeMismatchException tme = verifyExceptionHasCauseOfType(ex, TypeMismatchException.class);
    verifyHandlingResult(
        SampleCoreApiError.FORBIDDEN,
        Pair.of("exception_message", quotesToApostrophes(ex.getMessage()))
    );
}
 
Example 4
Source Project: openvsx   Source File: UserAPI.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@PostMapping(
    path = "/user/namespace/{namespace}/role",
    produces = MediaType.APPLICATION_JSON_VALUE
)
@Transactional(rollbackOn = ResponseStatusException.class)
public ResultJson setNamespaceMember(@PathVariable String namespace, @RequestParam String user,
        @RequestParam String role, @RequestParam(required = false) String provider) {
    var principal = users.getOAuth2Principal();
    if (principal == null) {
        throw new ResponseStatusException(HttpStatus.FORBIDDEN);
    }
    try {
        var requestingUser = users.updateUser(principal);
        return users.setNamespaceMember(requestingUser, namespace, provider, user, role);
    } catch (ErrorResultException exc) {
        return ResultJson.error(exc.getMessage());
    }
}
 
Example 5
Source Project: SpringCloud   Source File: GateWayExceptionHandlerAdvice.java    License: Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(value = {Throwable.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result handle(Throwable throwable) {
    Result result = Result.fail();
    if (throwable instanceof ResponseStatusException) {
        result = handle((ResponseStatusException) throwable);
    } else if (throwable instanceof ConnectTimeoutException) {
        result = handle((ConnectTimeoutException) throwable);
    } else if (throwable instanceof NotFoundException) {
        result = handle((NotFoundException) throwable);
    } else if (throwable instanceof RuntimeException) {
        result = handle((RuntimeException) throwable);
    } else if (throwable instanceof Exception) {
        result = handle((Exception) throwable);
    }
    return result;
}
 
Example 6
Source Project: java-trader   Source File: ConfigController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(path=URL_PREFIX+"/{configSource}/**",
        method=RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String getConfigItem(@PathVariable(value="configSource") String configSourceStr, HttpServletRequest request){
    String requestURI = request.getRequestURI();
    String configItem = requestURI.substring( URL_PREFIX.length()+configSourceStr.length()+1);
    Object obj = null;
    if ( "ALL".equalsIgnoreCase(configSourceStr) ) {
        obj = ConfigUtil.getObject(configItem);
    }else{
        String configSource = configSources.get(configSourceStr.toLowerCase());
        if (configSource==null){
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
        obj = ConfigUtil.getObject(configSource, configItem);
    }
    if( logger.isDebugEnabled() ){
        logger.debug("Get config "+configSourceStr+" path \""+configItem+"\" value: \""+obj+"\"");
    }
    if ( obj==null ){
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }else{
        return obj.toString();
    }
}
 
Example 7
Source Project: syndesis   Source File: TeiidOpenShiftClient.java    License: Apache License 2.0 6 votes vote down vote up
public void createDataSource(DefaultSyndesisDataSource scd) throws AdminException {
    String syndesisName = scd.getSyndesisName();
    debug(syndesisName, "Creating the Datasource of Type " + scd.getType());

    if (scd.getTeiidName() == null) {
        for (int i = 0; i < 3; i++) {
            try {
                String name = getUniqueTeiidName(scd, syndesisName);
                scd.setTeiidName(name);
                break;
            } catch (PersistenceException | DataIntegrityViolationException ignored) {
                //multiple pods are trying to assign a name simultaneously
                //if we try again, then we'll just pickup whatever someone else set
            }
        }
        if (scd.getTeiidName() == null) {
            throw new ResponseStatusException(HttpStatus.CONFLICT);
        }
    }

    //now that the name is set, we can create the properties
    this.metadata.registerDataSource(scd);
}
 
Example 8
@Test
public void verify_GENERIC_SERVICE_ERROR_returned_if_ResponseStatusException_with_ConversionNotSupportedException_cause_is_thrown() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .log().all()
            .when()
            .get(CONVERSION_NOT_SUPPORTED_EXCEPTION_ENDPOINT_PATH)
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, SampleCoreApiError.GENERIC_SERVICE_ERROR);
    ResponseStatusException ex = verifyExceptionSeenByBackstopper(ResponseStatusException.class);
    ConversionNotSupportedException cnse = verifyExceptionHasCauseOfType(ex, ConversionNotSupportedException.class);
    verifyHandlingResult(
        SampleCoreApiError.GENERIC_SERVICE_ERROR,
        Pair.of("exception_message", quotesToApostrophes(ex.getMessage())),
        Pair.of("bad_property_name", cnse.getPropertyName()),
        Pair.of("bad_property_value", cnse.getValue().toString()),
        Pair.of("required_type", cnse.getRequiredType().toString())
    );
}
 
Example 9
Source Project: java-trader   Source File: TAController.java    License: Apache License 2.0 6 votes vote down vote up
@RequestMapping(path=URL_PREFIX+"/{instrument}/{level:.+}",
method=RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public String getLevelBars(@PathVariable(value="instrument") String instrumentStr, @PathVariable(value="level") String level, @RequestParam(name="pretty", required=false) boolean pretty){
    Exchangeable instrument = Exchangeable.fromString(instrumentStr);
    TechnicalAnalysisAccess access = technicalAnalysisService.forInstrument(instrument);
    if ( access==null ) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }
    JsonElement json = null;
    PriceLevel l = PriceLevel.valueOf(level);
    BarSeries series = access.getSeries(l);
    if ( series==null ) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }
    json = JsonUtil.object2json(series);
    return (JsonUtil.json2str(json, pretty));
}
 
Example 10
Source Project: java-technology-stack   Source File: ResourceWebHandlerTests.java    License: MIT License 6 votes vote down vote up
private void resourceNotFound(HttpMethod httpMethod) {
	MockServerHttpRequest request = MockServerHttpRequest.method(httpMethod, "").build();
	MockServerWebExchange exchange = MockServerWebExchange.from(request);
	setPathWithinHandlerMapping(exchange, "not-there.css");
	Mono<Void> mono = this.handler.handle(exchange);

	StepVerifier.create(mono)
			.expectErrorSatisfies(err -> {
				assertThat(err, instanceOf(ResponseStatusException.class));
				assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus());
			}).verify(TIMEOUT);

	// SPR-17475
	AtomicReference<Throwable> exceptionRef = new AtomicReference<>();
	StepVerifier.create(mono).consumeErrorWith(exceptionRef::set).verify();
	StepVerifier.create(mono).consumeErrorWith(ex -> assertNotSame(exceptionRef.get(), ex)).verify();
}
 
Example 11
@Override
@Nullable
protected ModelAndView doResolveException(
		HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {

	try {
		if (ex instanceof ResponseStatusException) {
			return resolveResponseStatusException((ResponseStatusException) ex, request, response, handler);
		}

		ResponseStatus status = AnnotatedElementUtils.findMergedAnnotation(ex.getClass(), ResponseStatus.class);
		if (status != null) {
			return resolveResponseStatus(status, request, response, handler, ex);
		}

		if (ex.getCause() instanceof Exception) {
			return doResolveException(request, response, handler, (Exception) ex.getCause());
		}
	}
	catch (Exception resolveEx) {
		if (logger.isWarnEnabled()) {
			logger.warn("Failure while trying to resolve exception [" + ex.getClass().getName() + "]", resolveEx);
		}
	}
	return null;
}
 
Example 12
Source Project: openvsx   Source File: UpstreamRegistryService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private byte[] getFile(String url) {
    var headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
    var response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<String>(headers), byte[].class);
    switch (response.getStatusCode()) {
        case OK:
            return response.getBody();
        case NOT_FOUND:
            throw new NotFoundException();
        default:
            throw new ResponseStatusException(response.getStatusCode(),
                    "Upstream registry responded with status \"" + response.getStatusCode().getReasonPhrase() + "\".");
    }
}
 
Example 13
Source Project: openvsx   Source File: VSCodeAdapter.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@GetMapping("/vscode/item")
public ModelAndView getItemUrl(@RequestParam String itemName, ModelMap model) {
    var dotIndex = itemName.indexOf('.');
    if (dotIndex < 0) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Expecting an item of the form `{publisher}.{name}`");
    }
    var namespace = itemName.substring(0, dotIndex);
    var extension = itemName.substring(dotIndex + 1);
    return new ModelAndView("redirect:" + UrlUtil.createApiUrl(webuiUrl, "extension", namespace, extension), model);
}
 
Example 14
Source Project: openvsx   Source File: AdminAPI.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@GetMapping(
    path = "/admin/log",
    produces = MediaType.TEXT_PLAIN_VALUE
)
public String getLog(@RequestParam("token") String tokenValue,
                     @RequestParam(name = "period", required = false) String periodString) {
    var token = users.useAccessToken(tokenValue);
    if (token == null) {
        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Invalid access token.");
    }
    if (!UserData.ROLE_ADMIN.equals(token.getUser().getRole())) {
        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Administration role is required.");
    }

    Streamable<PersistedLog> logs;
    if (Strings.isNullOrEmpty(periodString)) {
        logs = repositories.findAllPersistedLogs();
    } else {
        try {
            var period = Period.parse(periodString);
            var now = TimeUtil.getCurrentUTC();
            logs = repositories.findPersistedLogsAfter(now.minus(period));
        } catch (DateTimeParseException exc) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid period");
        }
    }
    return logs.stream()
            .map(this::toString)
            .collect(Collectors.joining("\n")) + "\n";
}
 
Example 15
Source Project: openvsx   Source File: LocalRegistryService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Transactional(rollbackOn = ResponseStatusException.class)
public ResultJson postReview(ReviewJson review, String namespace, String extensionName) {
    var principal = users.getOAuth2Principal();
    if (principal == null) {
        throw new ResponseStatusException(HttpStatus.FORBIDDEN);
    }
    var extension = repositories.findExtension(extensionName, namespace);
    if (extension == null) {
        return ResultJson.error("Extension not found: " + namespace + "." + extensionName);
    }
    var user = users.updateUser(principal);
    var activeReviews = repositories.findActiveReviews(extension, user);
    if (!activeReviews.isEmpty()) {
        return ResultJson.error("You must not submit more than one review for an extension.");
    }

    var extReview = new ExtensionReview();
    extReview.setExtension(extension);
    extReview.setActive(true);
    extReview.setTimestamp(TimeUtil.getCurrentUTC());
    extReview.setUser(user);
    extReview.setTitle(review.title);
    extReview.setComment(review.comment);
    extReview.setRating(review.rating);
    entityManager.persist(extReview);
    extension.setAverageRating(computeAverageRating(extension));
    search.updateSearchEntry(extension);
    return ResultJson.success("Added review for " + extension.getNamespace().getName() + "." + extension.getName());
}
 
Example 16
Source Project: tutorials   Source File: ActorController.java    License: MIT License 5 votes vote down vote up
@PutMapping("/actor/{id}/{name}")
public String updateActorName(@PathVariable("id") int id, @PathVariable("name") String name) {
    try {
        return actorService.updateActor(id, name);
    } catch (ActorNotFoundException ex) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Provide correct Actor Id", ex);
    }
}
 
Example 17
Source Project: quarkus   Source File: ResponseStatusExceptionMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(ResponseStatusException exception) {
    Response.ResponseBuilder responseBuilder = new ResponseBuilderImpl().status(exception.getStatus().value());
    addHeaders(responseBuilder, exception.getResponseHeaders());
    return responseBuilder.entity(exception.getMessage())
            .type(MediaType.TEXT_PLAIN).build();
}
 
Example 18
Source Project: gaia   Source File: TerraformStateController.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@GetMapping("/api/state/{id}")
public Map<String, Object> getState(@PathVariable String id){
    return repository.findById(id)
            .orElseThrow(
                    () -> new ResponseStatusException(HttpStatus.NOT_FOUND))
            .getValue();
}
 
Example 19
Source Project: problem-spring-web   Source File: ResponseStatusAdviceTrait.java    License: MIT License 5 votes vote down vote up
@API(status = INTERNAL)
@ExceptionHandler
default Mono<ResponseEntity<Problem>> handleResponseStatusException(
        final ResponseStatusException exception,
        final ServerWebExchange request) {
    return create(exception.getStatus(), exception, request);
}
 
Example 20
Source Project: kafka-graphs   Source File: GraphAlgorithmHandler.java    License: Apache License 2.0 5 votes vote down vote up
private String getConfig(Map<String, String> configs, String key, boolean isRequired) {
    String value = configs != null ? configs.get(key) : null;
    if (isRequired && value == null) {
        throw new ResponseStatusException(BAD_REQUEST, "Missing param: " + key);
    }
    return value;
}
 
Example 21
Source Project: syndesis   Source File: MetadataServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSchemaSingleLevel() throws AdminException {
    assertThatThrownBy(() -> metadataService.getSourceSchema("source3"))
        .isInstanceOf(ResponseStatusException.class);

    //add the data source, and schema
    DefaultSyndesisDataSource sds = DataVirtualizationServiceTest.createH2DataSource("source3");
    metadataInstance.registerDataSource(sds);


    repositoryManagerImpl.createSchema("someid", "source3",
            "create foreign table tbl (col string) options (\"teiid_rel:fqn\" 'collection=bar');"
            + "create foreign table tbl1 (col string) options (\"teiid_rel:fqn\" 'collection=bar1');");

    List<RestSchemaNode> nodes = metadataService.getSourceSchema("source3");
    assertEquals(
        "[ {\n" +
        "  \"children\" : [ {\n" +
        "    \"children\" : [ ],\n" +
        "    \"name\" : \"bar\",\n" +
        "    \"teiidName\" : \"tbl\",\n" +
        "    \"connectionName\" : \"source3\",\n" +
        "    \"type\" : \"collection\",\n" +
        "    \"queryable\" : true\n" +
        "  }, {\n" +
        "    \"children\" : [ ],\n" +
        "    \"name\" : \"bar1\",\n" +
        "    \"teiidName\" : \"tbl1\",\n" +
        "    \"connectionName\" : \"source3\",\n" +
        "    \"type\" : \"collection\",\n" +
        "    \"queryable\" : true\n" +
        "  } ],\n" +
        "  \"name\" : \"source3\",\n" +
        "  \"type\" : \"teiidSource\",\n" +
        "  \"queryable\" : false\n" +
        "} ]", JsonMarshaller.marshall(nodes));
}
 
Example 22
@DataProvider(value = {
    "400    |   INVALID_REQUEST",
    "401    |   UNAUTHORIZED",
    "403    |   FORBIDDEN",
    "404    |   NOT_FOUND",
    "405    |   METHOD_NOT_ALLOWED",
    "406    |   NO_ACCEPTABLE_REPRESENTATION",
    "415    |   UNSUPPORTED_MEDIA_TYPE",
    "429    |   TOO_MANY_REQUESTS",
    "500    |   GENERIC_SERVICE_ERROR",
    "503    |   TEMPORARY_SERVICE_PROBLEM",
}, splitBy = "\\|")
@Test
public void verify_generic_ResponseStatusCode_exceptions_result_in_ApiError_from_project_if_status_code_is_known(
    int desiredStatusCode, SampleCoreApiError expectedError
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .log().all()
            .when()
            .header("desired-status-code", desiredStatusCode)
            .get(RESPONSE_STATUS_EX_FOR_SPECIFIC_STATUS_CODE_ENDPOINT)
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, expectedError);
    ResponseStatusException ex = verifyResponseStatusExceptionSeenByBackstopper(
        ResponseStatusException.class, desiredStatusCode
    );
    verifyHandlingResult(
        expectedError,
        Pair.of("exception_message", quotesToApostrophes(ex.getMessage()))
    );
}
 
Example 23
@DataProvider(value = {
    "400    |   GENERIC_BAD_REQUEST",
    "401    |   UNAUTHORIZED",
    "403    |   FORBIDDEN",
    "404    |   NOT_FOUND",
    "405    |   METHOD_NOT_ALLOWED",
    "406    |   NO_ACCEPTABLE_REPRESENTATION",
    "415    |   UNSUPPORTED_MEDIA_TYPE",
    "429    |   TOO_MANY_REQUESTS",
    "500    |   GENERIC_SERVICE_ERROR",
    "503    |   TEMPORARY_SERVICE_PROBLEM",
}, splitBy = "\\|")
@Test
public void handleFluxExceptions_handles_generic_ResponseStatusException_by_returning_ApiError_from_project_if_status_code_is_known(
    int desiredStatusCode, BarebonesCoreApiErrorForTesting expectedError
) {
    // given
    ResponseStatusException ex = new ResponseStatusException(
        HttpStatus.resolve(desiredStatusCode), "Some ResponseStatusException reason"
    );
    List<Pair<String, String>> expectedExtraDetailsForLogging = new ArrayList<>();
    ApiExceptionHandlerUtils.DEFAULT_IMPL.addBaseExceptionMessageToExtraDetailsForLogging(
        ex, expectedExtraDetailsForLogging
    );

    // when
    ApiExceptionHandlerListenerResult result = listener.handleSpringMvcOrWebfluxSpecificFrameworkExceptions(ex);

    // then
    validateResponse(
        result,
        true,
        singleton(expectedError),
        expectedExtraDetailsForLogging
    );
}
 
Example 24
@GetMapping("/milestones/{name}/duedate")
public SpringCloudInfoService.Milestone milestoneDueDate(@PathVariable String name)
		throws IOException {
	try {
		return versionService.getMilestoneDueDate(name);
	}
	catch (SpringCloudMilestoneNotFoundException e) {
		throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
	}
}
 
Example 25
Source Project: spring-analysis-note   Source File: ResourceWebHandlerTests.java    License: MIT License 5 votes vote down vote up
private void testInvalidPath(String requestPath, ResourceWebHandler handler) {
	ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
	setPathWithinHandlerMapping(exchange, requestPath);

	StepVerifier.create(handler.handle(exchange))
			.expectErrorSatisfies(err -> {
				assertThat(err, instanceOf(ResponseStatusException.class));
				assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus());
			}).verify(TIMEOUT);
}
 
Example 26
Source Project: synapse   Source File: JournalRestController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns an application/hal+json representation of the event journal of a single event-sourced entity.
 *
 * @param repositoryName the name of the {@link Journal}
 * @param entityId the id of the requested entity
 * @param uriComponentsBuilder builder used to create hrefs
 *
 * @return HalRepresentation the representation of the journal
 */
@GetMapping(
        path = "${edison.application.management.base-path:internal}/journals/{repositoryName}/{entityId}",
        produces = {"application/hal+json", "application/json"}
)
@ResponseBody
public HalRepresentation getEntityJournalJson(final @PathVariable String repositoryName,
                                              final @PathVariable String entityId,
                                              final UriComponentsBuilder uriComponentsBuilder) {
    final String baseUri = uriComponentsBuilder.pathSegment(managementBasePath).toUriString();
    final String selfUri = baseUri + "/journals/" + repositoryName + "/" + entityId;

    if (journals.hasJournal(repositoryName)) {
        final List<MessageStoreEntryRepresentation> messages =
            journals.getJournal(repositoryName)
                    .map(journal -> journal.getJournalFor(entityId)
                            .map(MessageStoreEntryRepresentation::new)
                            .collect(toList()))
                    .orElse(emptyList());
        final Links.Builder links = linkingTo()
                .self(selfUri);
        if (stateRepositories.containsKey(repositoryName)) {
            links
                    .single(
                            link("working-copy", baseUri + "/staterepositories/" + repositoryName + "/" + entityId))
                    .single(
                            collection(baseUri + "/staterepositories/" + repositoryName + "{?page,pageSize}"));
        }
        return new JournalHalRepresentation(
                links.build(),
                messages);
    } else {
        throw new ResponseStatusException(NOT_FOUND, "No such Journal " + repositoryName);
    }
}
 
Example 27
Source Project: tutorials   Source File: FooController.java    License: MIT License 5 votes vote down vote up
@GetMapping(value = "/{id}")
public Foo findById(@PathVariable("id") final Long id, final HttpServletResponse response) {
    try {
        final Foo resourceById = RestPreconditions.checkFound(service.findById(id));

        eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
        return resourceById;
    }
    catch (MyResourceNotFoundException exc) {
        throw new ResponseStatusException(
            HttpStatus.NOT_FOUND, "Foo Not Found", exc);
    }

}
 
Example 28
Source Project: spring-analysis-note   Source File: ResourceWebHandlerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void missingResourcePath() {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
	setPathWithinHandlerMapping(exchange, "");
	StepVerifier.create(this.handler.handle(exchange))
			.expectErrorSatisfies(err -> {
				assertThat(err, instanceOf(ResponseStatusException.class));
				assertEquals(HttpStatus.NOT_FOUND, ((ResponseStatusException) err).getStatus());
			}).verify(TIMEOUT);
}
 
Example 29
Source Project: spring-analysis-note   Source File: RouterFunctionsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void toHttpHandlerHandlerResponseStatusException() {
	HandlerFunction<ServerResponse> handlerFunction =
			request -> Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found"));
	RouterFunction<ServerResponse> routerFunction =
			RouterFunctions.route(RequestPredicates.all(), handlerFunction);

	HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
	assertNotNull(result);

	MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
	MockServerHttpResponse httpResponse = new MockServerHttpResponse();
	result.handle(httpRequest, httpResponse).block();
	assertEquals(HttpStatus.NOT_FOUND, httpResponse.getStatusCode());
}
 
Example 30
Source Project: spring-analysis-note   Source File: RouterFunctionsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void toHttpHandlerHandlerReturnResponseStatusExceptionInResponseWriteTo() {
	HandlerFunction<ServerResponse> handlerFunction =
			// Mono.<ServerResponse> is required for compilation in Eclipse
			request -> Mono.just(new ServerResponse() {
				@Override
				public HttpStatus statusCode() {
					return HttpStatus.OK;
				}
				@Override
				public HttpHeaders headers() {
					return new HttpHeaders();
				}
				@Override
				public MultiValueMap<String, ResponseCookie> cookies() {
					return new LinkedMultiValueMap<>();
				}
				@Override
				public Mono<Void> writeTo(ServerWebExchange exchange, Context context) {
					return Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found"));
				}
			});
	RouterFunction<ServerResponse> routerFunction =
			RouterFunctions.route(RequestPredicates.all(), handlerFunction);

	HttpHandler result = RouterFunctions.toHttpHandler(routerFunction);
	assertNotNull(result);

	MockServerHttpRequest httpRequest = MockServerHttpRequest.get("http://localhost").build();
	MockServerHttpResponse httpResponse = new MockServerHttpResponse();
	result.handle(httpRequest, httpResponse).block();
	assertEquals(HttpStatus.NOT_FOUND, httpResponse.getStatusCode());
}