Turn off auto-formatting where it reduces readability

This commit is contained in:
Rossen Stoyanchev
2021-06-15 14:01:52 +01:00
parent a5f56ca3cb
commit 43f9e34c81
27 changed files with 534 additions and 283 deletions

View File

@@ -5,7 +5,6 @@ import java.util.Map;
import graphql.schema.idl.RuntimeWiring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.graphql.boot.RuntimeWiringCustomizer;
import org.springframework.stereotype.Component;

View File

@@ -1,9 +1,13 @@
package io.spring.sample.graphql;
import graphql.ErrorClassification;
import java.util.Arrays;
import java.util.List;
import graphql.GraphQLError;
import graphql.GraphqlErrorBuilder;
import graphql.schema.DataFetchingEnvironment;
import reactor.core.publisher.Mono;
import org.springframework.graphql.execution.DataFetcherExceptionResolver;
import org.springframework.graphql.execution.ErrorType;
import org.springframework.security.access.AccessDeniedException;
@@ -13,19 +17,18 @@ import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import java.util.Arrays;
import java.util.List;
// @formatter:off
@Component
public class SecurityDataFetcherExceptionResolver implements DataFetcherExceptionResolver {
private AuthenticationTrustResolver authenticationTrustResolver = new AuthenticationTrustResolverImpl();
@Override
public Mono<List<GraphQLError>> resolveException(Throwable exception, DataFetchingEnvironment environment) {
if (exception instanceof AuthenticationException) {
// TOTO: should this be empty ?
}
if (exception instanceof AccessDeniedException) {
return ReactiveSecurityContextHolder.getContext()
@@ -38,10 +41,19 @@ public class SecurityDataFetcherExceptionResolver implements DataFetcherExceptio
}
private Mono<List<GraphQLError>> unauthorized(DataFetchingEnvironment environment) {
return Mono.fromCallable(() -> Arrays.asList(GraphqlErrorBuilder.newError(environment).errorType(ErrorType.UNAUTHORIZED).message("Unauthorized").build()));
return Mono.fromCallable(() -> Arrays.asList(
GraphqlErrorBuilder.newError(environment)
.errorType(ErrorType.UNAUTHORIZED)
.message("Unauthorized")
.build()));
}
private Mono<List<GraphQLError>> forbidden(DataFetchingEnvironment environment) {
return Mono.fromCallable(() -> Arrays.asList(GraphqlErrorBuilder.newError(environment).errorType(ErrorType.FORBIDDEN).message("Forbidden").build()));
return Mono.fromCallable(() -> Arrays.asList(
GraphqlErrorBuilder.newError(environment)
.errorType(ErrorType.FORBIDDEN)
.message("Forbidden")
.build()));
}
}

View File

@@ -1,7 +1,10 @@
package io.spring.sample.graphql;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext;
@@ -10,7 +13,7 @@ import org.springframework.security.test.web.reactive.server.SecurityMockServerC
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.function.client.ExchangeFilterFunctions;
import java.util.Collections;
// @formatter:off
@SpringBootTest()
class SampleApplicationTests {

View File

@@ -24,24 +24,20 @@ import org.springframework.stereotype.Component;
@Component
public class SampleWiring implements RuntimeWiringCustomizer {
private final DataRepository dataRepository;
private final DataRepository repository;
public SampleWiring(@Autowired DataRepository dataRepository) {
this.dataRepository = dataRepository;
this.repository = dataRepository;
}
@Override
public void customize(RuntimeWiring.Builder builder) {
builder.type("Query", typeBuilder -> typeBuilder.dataFetcher("greeting", this.dataRepository::getBasic));
builder.type("Query", typeBuilder -> typeBuilder.dataFetcher("greetingMono", this.dataRepository::getGreeting));
builder.type("Query",
typeBuilder -> typeBuilder.dataFetcher("greetingsFlux", this.dataRepository::getGreetings));
builder.type("Subscription",
typeBuilder -> typeBuilder.dataFetcher("greetings", this.dataRepository::getGreetingsStream));
public void customize(RuntimeWiring.Builder wiringBuilder) {
// @formatter:off
wiringBuilder.type("Query", builder -> builder.dataFetcher("greeting", this.repository::getBasic));
wiringBuilder.type("Query", builder -> builder.dataFetcher("greetingMono", this.repository::getGreeting));
wiringBuilder.type("Query", builder -> builder.dataFetcher("greetingsFlux", this.repository::getGreetings));
wiringBuilder.type("Subscription", builder -> builder.dataFetcher("greetings", this.repository::getGreetingsStream));
// @formatter:on
}
}

View File

@@ -21,8 +21,10 @@ import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.graphql.web.WebGraphQlHandler;
import org.springframework.graphql.test.tester.GraphQlTester;
import org.springframework.graphql.web.WebGraphQlHandler;
// @formatter:off
/**
* GraphQL query tests directly via {@link GraphQL}.
@@ -34,19 +36,25 @@ public class QueryTests {
@BeforeEach
public void setUp(@Autowired WebGraphQlHandler handler) {
this.graphQlTester = GraphQlTester
.create(webInput -> handler.handle(webInput).contextWrite(context -> context.put("name", "James")));
this.graphQlTester = GraphQlTester.create(webInput ->
handler.handle(webInput).contextWrite(context -> context.put("name", "James")));
}
@Test
void greetingMono() {
this.graphQlTester.query("{greetingMono}").execute().path("greetingMono").entity(String.class)
this.graphQlTester.query("{greetingMono}")
.execute()
.path("greetingMono")
.entity(String.class)
.isEqualTo("Hello James");
}
@Test
void greetingsFlux() {
this.graphQlTester.query("{greetingsFlux}").execute().path("greetingsFlux").entityList(String.class)
this.graphQlTester.query("{greetingsFlux}")
.execute()
.path("greetingsFlux")
.entityList(String.class)
.containsExactly("Hi James", "Bonjour James", "Hola James", "Ciao James", "Zdravo James");
}

View File

@@ -23,8 +23,10 @@ import reactor.test.StepVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.graphql.web.WebGraphQlHandler;
import org.springframework.graphql.test.tester.GraphQlTester;
import org.springframework.graphql.web.WebGraphQlHandler;
// @formatter:off
/**
* GraphQL subscription tests directly via {@link GraphQL}.
@@ -36,29 +38,36 @@ public class SubscriptionTests {
@BeforeEach
public void setUp(@Autowired WebGraphQlHandler handler) {
this.graphQlTester = GraphQlTester
.create(webInput -> handler.handle(webInput).contextWrite(context -> context.put("name", "James")));
this.graphQlTester = GraphQlTester.create(webInput ->
handler.handle(webInput).contextWrite(context -> context.put("name", "James")));
}
@Test
void subscriptionWithEntityPath() {
String query = "subscription { greetings }";
Flux<String> result = this.graphQlTester.query("subscription { greetings }")
.executeSubscription()
.toFlux("greetings", String.class);
Flux<String> result = this.graphQlTester.query(query).executeSubscription().toFlux("greetings", String.class);
StepVerifier.create(result).expectNext("Hi James").expectNext("Bonjour James").expectNext("Hola James")
.expectNext("Ciao James").expectNext("Zdravo James").verifyComplete();
StepVerifier.create(result)
.expectNext("Hi James")
.expectNext("Bonjour James")
.expectNext("Hola James")
.expectNext("Ciao James")
.expectNext("Zdravo James")
.verifyComplete();
}
@Test
void subscriptionWithResponseSpec() {
String query = "subscription { greetings }";
Flux<GraphQlTester.ResponseSpec> result = this.graphQlTester.query("subscription { greetings }")
.executeSubscription()
.toFlux();
Flux<GraphQlTester.ResponseSpec> result = this.graphQlTester.query(query).executeSubscription().toFlux();
StepVerifier.create(result).consumeNextWith(spec -> spec.path("greetings").valueExists())
StepVerifier.create(result)
.consumeNextWith(spec -> spec.path("greetings").valueExists())
.consumeNextWith(spec -> spec.path("greetings").matchesJson("\"Bonjour James\""))
.consumeNextWith(spec -> spec.path("greetings").matchesJson("\"Hola James\"")).expectNextCount(2)
.consumeNextWith(spec -> spec.path("greetings").matchesJson("\"Hola James\""))
.expectNextCount(2)
.verifyComplete();
}

View File

@@ -10,8 +10,12 @@ public enum ProjectStatus {
@JsonCreator
public static ProjectStatus fromName(String name) {
return Arrays.stream(ProjectStatus.values()).filter(type -> type.name().equals(name)).findFirst()
// @formatter:off
return Arrays.stream(ProjectStatus.values())
.filter(type -> type.name().equals(name))
.findFirst()
.orElse(ProjectStatus.ACTIVE);
// @formatter:on
}
}

View File

@@ -10,8 +10,12 @@ public enum ReleaseStatus {
@JsonCreator
public static ReleaseStatus fromName(String name) {
return Arrays.stream(ReleaseStatus.values()).filter(type -> type.name().equals(name)).findFirst()
// @formatter:off
return Arrays.stream(ReleaseStatus.values())
.filter(type -> type.name().equals(name))
.findFirst()
.orElse(ReleaseStatus.GENERAL_AVAILABILITY);
// @formatter:on
}
}

View File

@@ -2,10 +2,7 @@ package io.spring.sample.graphql.project;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.hateoas.CollectionModel;
@@ -13,27 +10,35 @@ import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.client.Hop;
import org.springframework.hateoas.client.Traverson;
import org.springframework.hateoas.server.core.TypeReferences;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@Component
public class SpringProjectsClient {
private static final TypeReferences.CollectionModelType<Release> releaseCollection = new TypeReferences.CollectionModelType<Release>() {
};
// @formatter:off
private static final TypeReferences.CollectionModelType<Release> releaseCollection =
new TypeReferences.CollectionModelType<Release>() {};
// @formatter:on
private final Traverson traverson;
public SpringProjectsClient(RestTemplateBuilder builder) {
RestTemplate restTemplate = builder
.messageConverters(Traverson.getDefaultMessageConverters(MediaTypes.HAL_JSON)).build();
List<HttpMessageConverter<?>> converters = Traverson.getDefaultMessageConverters(MediaTypes.HAL_JSON);
RestTemplate restTemplate = builder.messageConverters(converters).build();
this.traverson = new Traverson(URI.create("https://spring.io/api/"), MediaTypes.HAL_JSON);
this.traverson.setRestOperations(restTemplate);
}
public Project fetchProject(String projectSlug) {
return this.traverson.follow("projects").follow(Hop.rel("project").withParameter("id", projectSlug))
// @formatter:off
return this.traverson.follow("projects")
.follow(Hop.rel("project").withParameter("id", projectSlug))
.toObject(Project.class);
// @formatter:on
}
public List<Release> fetchProjectReleases(String projectSlug) {

View File

@@ -18,12 +18,12 @@ public class ArtifactRepositoriesInitializer implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
// @formatter:off
List<ArtifactRepository> repositoryList = Arrays.asList(
new ArtifactRepository("spring-releases", "Spring Releases", "https://repo.spring.io/libs-releases"),
new ArtifactRepository("spring-milestones", "Spring Milestones",
"https://repo.spring.io/libs-milestones"),
new ArtifactRepository("spring-snapshots", "Spring Snapshots",
"https://repo.spring.io/libs-snapshots"));
new ArtifactRepository("spring-milestones", "Spring Milestones", "https://repo.spring.io/libs-milestones"),
new ArtifactRepository("spring-snapshots", "Spring Snapshots", "https://repo.spring.io/libs-snapshots"));
// @formatter:on
repositories.saveAll(repositoryList);
}

View File

@@ -26,6 +26,8 @@ import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
// @formatter:off
/**
* GraphQL requests via {@link GraphQlTester} connecting to {@link MockMvc}.
*/
@@ -39,28 +41,50 @@ public class MockMvcGraphQlTests {
@Test
void jsonPath() {
String query = "{" + " project(slug:\"spring-framework\") {" + " releases {" + " version" + " }"
+ " }" + "}";
String query = "{" +
" project(slug:\"spring-framework\") {" +
" releases {" +
" version" +
" }"+
" }" +
"}";
this.graphQlTester.query(query).execute().path("project.releases[*].version").entityList(String.class)
this.graphQlTester.query(query)
.execute()
.path("project.releases[*].version")
.entityList(String.class)
.hasSizeGreaterThan(1);
}
@Test
void jsonContent() {
String query = "{" + " project(slug:\"spring-framework\") {" + " repositoryUrl" + " }" + "}";
String query = "{" +
" project(slug:\"spring-framework\") {" +
" repositoryUrl" +
" }" +
"}";
this.graphQlTester.query(query).execute().path("project")
this.graphQlTester.query(query)
.execute()
.path("project")
.matchesJson("{\"repositoryUrl\":\"http://github.com/spring-projects/spring-framework\"}");
}
@Test
void decodedResponse() {
String query = "{" + " project(slug:\"spring-framework\") {" + " releases {" + " version" + " }"
+ " }" + "}";
String query = "{" +
" project(slug:\"spring-framework\") {" +
" releases {" +
" version" +
" }" +
" }" +
"}";
this.graphQlTester.query(query).execute().path("project").entity(Project.class)
this.graphQlTester.query(query)
.execute()
.path("project")
.entity(Project.class)
.satisfies(project -> assertThat(project.getReleases()).hasSizeGreaterThan(1));
}