diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae1673f3..a4cd2a3c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,6 +12,34 @@ jobs: steps: - uses: actions/checkout@v2 - uses: gradle/wrapper-validation-action@v1 + + verify-google-java-format: + name: Google Java Format Verification + runs-on: ubuntu-latest + needs: validation + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Java + uses: actions/setup-java@v2 + with: + distribution: 'zulu' + java-version: 15 + - name: Cache Gradle + uses: actions/cache@v2 + env: + java-version: 15 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-${{ env.java-version }}-gradle-${{ hashFiles('**/*.gradle*') }} + restore-keys: ${{ runner.os }}-${{ env.java-version }}-gradle- + - name: Make gradlew executable + run: chmod +x ./gradlew + - name: Gradle Check + run: ./gradlew --info build -x test + test: name: Test run needs: validation @@ -38,7 +66,8 @@ jobs: - name: Make gradlew executable run: chmod +x ./gradlew - name: Gradle Check - run: ./gradlew --info check + run: ./gradlew --info check -x verifyGoogleJavaFormat + build: name: Publish snapshot needs: test @@ -69,7 +98,8 @@ jobs: env: OSS_USER_TOKEN_KEY: ${{ secrets.OSS_USER_TOKEN_KEY }} OSS_USER_TOKEN_PASS: ${{ secrets.OSS_USER_TOKEN_PASS }} - run: ./gradlew clean build publish -x test + run: ./gradlew clean build publish -x test -x verifyGoogleJavaFormat + sonar: name: Sonar analysis needs: validation @@ -100,4 +130,4 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} if: env.SONAR_TOKEN != null - run: ./gradlew build jacocoTestReport sonarqube --info + run: ./gradlew build jacocoTestReport sonarqube --info -x verifyGoogleJavaFormat diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 543f915c..dd09d092 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -10,6 +10,34 @@ jobs: steps: - uses: actions/checkout@v2 - uses: gradle/wrapper-validation-action@v1 + + verify-google-java-format: + name: Google Java Format Verification + runs-on: ubuntu-latest + needs: validation + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Java + uses: actions/setup-java@v2 + with: + distribution: 'zulu' + java-version: 15 + - name: Cache Gradle + uses: actions/cache@v2 + env: + java-version: 15 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-${{ env.java-version }}-gradle-${{ hashFiles('**/*.gradle*') }} + restore-keys: ${{ runner.os }}-${{ env.java-version }}-gradle- + - name: Make gradlew executable + run: chmod +x ./gradlew + - name: Gradle Check + run: ./gradlew --info build -x test + test: name: Test run strategy: @@ -36,18 +64,18 @@ jobs: ~/.gradle/caches ~/.gradle/wrapper key: ${{ runner.os }}-${{ env.java-version }}-gradle-${{ hashFiles('**/*.gradle*') }} - restore-keys: | - ${{ runner.os }}-${{ env.java-version }}-gradle- + restore-keys: ${{ runner.os }}-${{ env.java-version }}-gradle- - name: Make gradlew executable (non-Windows only) if: matrix.os != 'windows-latest' run: chmod +x ./gradlew - name: Gradle Check (non-Windows) if: matrix.os != 'windows-latest' - run: ./gradlew --info check + run: ./gradlew --info check -x verifyGoogleJavaFormat - name: Gradle Check (Windows) if: matrix.os == 'windows-latest' shell: cmd - run: gradlew --info check + run: gradlew --info check -x verifyGoogleJavaFormat + build: name: Sonar analysis needs: validation @@ -84,4 +112,4 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: ./gradlew build jacocoTestReport sonarqube --info + run: ./gradlew build jacocoTestReport sonarqube --info -x verifyGoogleJavaFormat diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index eea5e7f6..407451bf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,6 +8,7 @@ jobs: steps: - uses: actions/checkout@v2 - uses: gradle/wrapper-validation-action@v1 + test: name: Test run needs: validation @@ -34,7 +35,8 @@ jobs: - name: Make gradlew executable run: chmod +x ./gradlew - name: Gradle Check - run: ./gradlew --info check + run: ./gradlew --info check -x verifyGoogleJavaFormat + build: name: Publish release needs: test diff --git a/.gitignore b/.gitignore index d42f002d..a5e29758 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,8 @@ build bin ## Directory-based project format: -.idea/ +.idea/* +!.idea/codeStyles/ # if you remove the above rule, at least ignore the following: # User-specific stuff: diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 00000000..4809a830 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,583 @@ + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 00000000..79ee123c --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/externalDependencies.xml b/.idea/externalDependencies.xml new file mode 100644 index 00000000..68eda26b --- /dev/null +++ b/.idea/externalDependencies.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/google-java-format.xml b/.idea/google-java-format.xml new file mode 100644 index 00000000..8b57f452 --- /dev/null +++ b/.idea/google-java-format.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..07a2ef8f --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,53 @@ +# How to contribute + +We're really glad you're reading this, because we need more volunteer developers to help with this +project! + +We can use all the help we can get on each of +our [GraphQL Java Kickstart](https://github.com/graphql-java-kickstart) +projects. This work ranges from adding new features, fixing bugs, and answering questions to writing +documentation. + +## Answering questions and writing documentation + +A lot of the questions asked on GitHub are caused by a lack of documentation. We should +strive from now on to answer questions by adding content to +our [documentation](https://github.com/graphql-java-kickstart/documentation) and referring them to +the newly created content. + +Continuous integration will make sure that the changes are automatically deployed to +https://www.graphql-java-kickstart.com. + +## Submitting changes + +Please send a Pull Request with a clear list of what you've done using the +[GitHub flow](https://guides.github.com/introduction/flow/). We can always use more test coverage, +so we'd love to see that in the pull requests too. And make sure to follow our coding conventions ( +below) and make sure all your commits are atomic +(one feature per commit). + +## Coding conventions + +We use Google Java Style guide for our projects. See the +[Java Style Guide](https://google.github.io/styleguide/javaguide.html) for a detailed description. +The code style is enforced in our CI workflows. This means you'll have to make sure that your +commits have the same formatting. + +Best way to do this is to install the +[google java format plugin](https://plugins.jetbrains.com/plugin/8527-google-java-format). Once +installed you'll have to enable it for the project. From that point on you can hit CTRL+ALT+L to +reformat the code. Or even better configure the commit options in IntelliJ IDEA to Reformat Code +before commit: + +![screenshot-reformat-code-before-commit.png](screenshot-reformat-code-before-commit.png) + +**Warning** +There's also an XML code style file available that you could import in your IDE. That approach will +never be exactly in line with the checks and formatting that the google-java-format plugin applies. + +### SonarLint + +It would also be very helpful to install the SonarLint plugin in your IDE and fix any relevant +SonarLint issues before pushing a PR. We're aware that the current state of the code raises a lot of +SonarLint issues out of the box, but any help in reducing that is appreciated. More importantly we +don't increase that technical debt. diff --git a/README.md b/README.md index 2543ddd0..8d115862 100644 --- a/README.md +++ b/README.md @@ -28,12 +28,16 @@ and join the team! - [Enable GraphQL Servlet](#enable-graphql-servlet) - [Enable Graph*i*QL](#enable-graphiql) - [Enable Altair](#enable-altair) -- [Enable GraphQL Playground](#enable-graphql-playground) +- [Enable GraphQL Playground](#enable-graphql-voyager) - [Basic settings](#basic-settings) - [CDN](#cdn) - [Custom static resources](#custom-static-resources) - [Customizing GraphQL Playground](#customizing-graphql-playground) - [Tabs](#tabs) +- [Enable GraphQL Voyager](#enable-graphql-playground) + - [Basic settings](#graphql-voyager-basic-settings) + - [CDN](#graphql-voyager-cdn) + - [Customizing GraphQL Voyager](#customizing-graphql-voyager) - [Supported GraphQL-Java Libraries](#supported-graphql-java-libraries) - [GraphQL Java Tools](#graphql-java-tools) - [GraphQL Annotations](#graphql-annotations) @@ -433,6 +437,62 @@ You can configure the query, variables, headers and even supply sample responses , `variables` and `responses` are expected to be resources of the appropriate format (GraphQL for `query`, JSON for `variables` and `responses`). + +# Enable GraphQL Voyager + +**GraphQL Voyager** becomes accessible at root `/voyager` (or as configured +in `voyager.mapping`) +if `voyager-spring-boot-starter` is added as a dependency to a boot application. + +Available Spring Boot configuration parameters (either `application.yml` +or `application.properties`): + +```yaml +voyager: + enabled: true + basePath: / + mapping: /voyager + endpoint: /graphql + cdn: + enabled: false + version: latest + pageTitle: Voyager + displayOptions: + skipRelay: true + skipDeprecated: true + rootType: Query + sortByAlphabet: false + showLeafFields: true + hideRoot: false + hideDocs: false + hideSettings: false +``` + +## GraphQL Voyager Basic settings + +`mapping` and `endpoint` will default to `/voyager` and `/graphql`, respectively. Note that these values may not be empty. + +`enabled` defaults to `true`, and therefor **GraphQL Voyager** will be available by default if the dependency +is added to a Spring Boot Web Application project. + +`pageTitle` defaults to `Voyager`. + +All other properties default to the same as documented on the official [GraphQL Voyager readme](https://github.com/APIs-guru/graphql-voyager#properties) + +## GraphQL Voyager CDN + +The currently bundled version is `1.0.0-rc31`, which is - as of writing this - the latest release +of **GraphQL Voyager**. The CDN option uses `jsDelivr` CDN, if enabled. By default, it will +load the latest available release. Available CDN versions can be found on the project's +[jsDelivr page](https://www.jsdelivr.com/package/npm/graphql-voyager). The CDN option is +disabled by default. + +## Customizing GraphQL Voyager + +Further **GraphQL Voyager** `displayOptions`, `hideDocs` and `hideSettings` customizations can be configured, as documented in the official +[GraphQL Voyager readme](https://github.com/APIs-guru/graphql-voyager#properties). + + # Supported GraphQL-Java Libraries The following libraries have auto-configuration classes for creating a `GraphQLSchema`. diff --git a/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairAutoConfiguration.java b/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairAutoConfiguration.java index 6f789bc7..f2ceb991 100644 --- a/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairAutoConfiguration.java +++ b/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairAutoConfiguration.java @@ -8,9 +8,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.DispatcherServlet; -/** - * @author Moncef AOUDIA - */ +/** @author Moncef AOUDIA */ @Configuration @ConditionalOnWebApplication @EnableConfigurationProperties(AltairProperties.class) @@ -22,5 +20,4 @@ public class AltairAutoConfiguration { AltairController altairController() { return new AltairController(); } - } diff --git a/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairController.java b/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairController.java index 3cb0280d..aaaa6cee 100644 --- a/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairController.java +++ b/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairController.java @@ -24,20 +24,16 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; -/** - * @author Moncef AOUDIA - */ +/** @author Moncef AOUDIA */ @Controller public class AltairController { private static final String CDN_UNPKG = "//unpkg.com/"; private static final String ALTAIR = "altair-static"; - @Autowired - private AltairProperties altairProperties; + @Autowired private AltairProperties altairProperties; - @Autowired - private Environment environment; + @Autowired private Environment environment; private String template; private String props; @@ -67,31 +63,36 @@ private void loadHeaders() throws JsonProcessingException { } @GetMapping(value = "${altair.mapping:/altair}") - public void altair(HttpServletRequest request, HttpServletResponse response, - @PathVariable Map params) throws IOException { + public void altair( + HttpServletRequest request, + HttpServletResponse response, + @PathVariable Map params) + throws IOException { response.setContentType("text/html; charset=UTF-8"); - Map replacements = getReplacements( - constructGraphQlEndpoint(request, params), - request.getContextPath() + altairProperties.getEndpoint().getSubscriptions() - ); + Map replacements = + getReplacements( + constructGraphQlEndpoint(request, params), + request.getContextPath() + altairProperties.getEndpoint().getSubscriptions()); String populatedTemplate = StringSubstitutor.replace(template, replacements); response.getOutputStream().write(populatedTemplate.getBytes(Charset.defaultCharset())); } - private Map getReplacements(String graphqlEndpoint, - String subscriptionsEndpoint) { + private Map getReplacements( + String graphqlEndpoint, String subscriptionsEndpoint) { Map replacements = new HashMap<>(); replacements.put("graphqlEndpoint", graphqlEndpoint); replacements.put("subscriptionsEndpoint", subscriptionsEndpoint); replacements.put("pageTitle", altairProperties.getPageTitle()); replacements.put("pageFavicon", getResourceUrl("favicon.ico", "favicon.ico")); - replacements.put("altairBaseUrl", getResourceUrl( - StringUtils.join(altairProperties.getBasePath(), "/vendor/altair/"), - joinJsUnpkgPath(ALTAIR, altairProperties.getCdn().getVersion(), "build/dist/"))); - replacements - .put("altairLogoUrl", getResourceUrl("assets/img/logo_350.svg", "assets/img/logo_350.svg")); + replacements.put( + "altairBaseUrl", + getResourceUrl( + StringUtils.join(altairProperties.getBasePath(), "/vendor/altair/"), + joinJsUnpkgPath(ALTAIR, altairProperties.getCdn().getVersion(), "build/dist/"))); + replacements.put( + "altairLogoUrl", getResourceUrl("assets/img/logo_350.svg", "assets/img/logo_350.svg")); replacements.put("altairCssUrl", getResourceUrl("styles.css", "styles.css")); replacements.put("altairMainJsUrl", getResourceUrl("main.js", "main.js")); replacements.put("altairPolyfillsJsUrl", getResourceUrl("polyfills.js", "polyfills.js")); @@ -112,17 +113,16 @@ private String joinJsUnpkgPath(String library, String cdnVersion, String cdnFile return CDN_UNPKG + library + "@" + cdnVersion + "/" + cdnFileName; } - private String constructGraphQlEndpoint(HttpServletRequest request, - @RequestParam Map params) { + private String constructGraphQlEndpoint( + HttpServletRequest request, @RequestParam Map params) { String endpoint = altairProperties.getEndpoint().getGraphql(); for (Map.Entry param : params.entrySet()) { endpoint = endpoint.replaceAll("\\{" + param.getKey() + "}", param.getValue()); } - if (StringUtils.isNotBlank(request.getContextPath()) && !endpoint - .startsWith(request.getContextPath())) { + if (StringUtils.isNotBlank(request.getContextPath()) + && !endpoint.startsWith(request.getContextPath())) { return request.getContextPath() + endpoint; } return endpoint; } - } diff --git a/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairProperties.java b/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairProperties.java index 8c5384de..df141f0f 100644 --- a/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairProperties.java +++ b/altair-spring-boot-autoconfigure/src/main/java/graphql/kickstart/altair/boot/AltairProperties.java @@ -27,5 +27,4 @@ static class Cdn { private boolean enabled = false; private String version = "2.4.11"; } - } diff --git a/altair-spring-boot-autoconfigure/src/test/java/graphql/kickstart/altair/boot/test/AbstractAutoConfigurationTest.java b/altair-spring-boot-autoconfigure/src/test/java/graphql/kickstart/altair/boot/test/AbstractAutoConfigurationTest.java index 264e9001..fc68d69e 100644 --- a/altair-spring-boot-autoconfigure/src/test/java/graphql/kickstart/altair/boot/test/AbstractAutoConfigurationTest.java +++ b/altair-spring-boot-autoconfigure/src/test/java/graphql/kickstart/altair/boot/test/AbstractAutoConfigurationTest.java @@ -1,15 +1,12 @@ package graphql.kickstart.altair.boot.test; -import lombok.NonNull; import org.junit.jupiter.api.AfterEach; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.AnnotationConfigRegistry; import org.springframework.context.support.AbstractApplicationContext; -/** - * @author Moncef AOUDIA - */ +/** @author Moncef AOUDIA */ public abstract class AbstractAutoConfigurationTest { private final Class contextClass; @@ -21,8 +18,8 @@ protected AbstractAutoConfigurationTest(Class autoConfiguration) { this(AnnotationConfigApplicationContext.class, autoConfiguration); } - protected AbstractAutoConfigurationTest(Class contextClass, - Class autoConfiguration) { + protected AbstractAutoConfigurationTest( + Class contextClass, Class autoConfiguration) { assert AnnotationConfigRegistry.class.isAssignableFrom(contextClass); this.contextClass = contextClass; this.autoConfiguration = autoConfiguration; diff --git a/altair-spring-boot-autoconfigure/src/test/java/graphql/kickstart/altair/boot/test/AltairControllerTest.java b/altair-spring-boot-autoconfigure/src/test/java/graphql/kickstart/altair/boot/test/AltairControllerTest.java index 15f01497..07bbee05 100644 --- a/altair-spring-boot-autoconfigure/src/test/java/graphql/kickstart/altair/boot/test/AltairControllerTest.java +++ b/altair-spring-boot-autoconfigure/src/test/java/graphql/kickstart/altair/boot/test/AltairControllerTest.java @@ -14,9 +14,7 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ class AltairControllerTest extends AbstractAutoConfigurationTest { public AltairControllerTest() { diff --git a/build.gradle b/build.gradle index a26ebd7d..cc9b5b53 100644 --- a/build.gradle +++ b/build.gradle @@ -25,6 +25,7 @@ plugins { id "org.sonarqube" version "3.2.0" id "jacoco" id 'io.codearte.nexus-staging' version '0.30.0' + id 'com.github.sherter.google-java-format' version '0.9' apply false } sonarqube { @@ -48,6 +49,7 @@ subprojects { } apply plugin: 'maven-publish' apply plugin: 'signing' + apply plugin: 'com.github.sherter.google-java-format' group "$PROJECT_GROUP" @@ -114,6 +116,8 @@ subprojects { } compileJava.dependsOn(processResources) + + compileJava.mustRunAfter verifyGoogleJavaFormat } if (!it.name.startsWith('example')) { diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/SubscriptionSampleApplication.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/SubscriptionSampleApplication.java index e397803c..3c01bc99 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/SubscriptionSampleApplication.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/SubscriptionSampleApplication.java @@ -9,5 +9,4 @@ public class SubscriptionSampleApplication { public static void main(String[] args) { SpringApplication.run(SubscriptionSampleApplication.class, args); } - } diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerReactorPublisher.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerReactorPublisher.java index c37636c4..85df1f30 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerReactorPublisher.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerReactorPublisher.java @@ -37,10 +37,13 @@ public class StockTickerReactorPublisher { private final Flux publisher; public StockTickerReactorPublisher() { - Flux stockPriceUpdateFlux = Flux.create(emitter -> { - ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); - executorService.scheduleAtFixedRate(newStockTick(emitter), 0, 2, TimeUnit.SECONDS); - }, FluxSink.OverflowStrategy.BUFFER); + Flux stockPriceUpdateFlux = + Flux.create( + emitter -> { + ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); + executorService.scheduleAtFixedRate(newStockTick(emitter), 0, 2, TimeUnit.SECONDS); + }, + FluxSink.OverflowStrategy.BUFFER); ConnectableFlux connectableFlux = stockPriceUpdateFlux.share().publish(); connectableFlux.connect(); @@ -72,8 +75,8 @@ private Runnable newStockTick(FluxSink emitter) { }; } - private void emitStocks(FluxSink emitter, - List stockPriceUpdates) { + private void emitStocks( + FluxSink emitter, List stockPriceUpdates) { for (StockPriceUpdate stockPriceUpdate : stockPriceUpdates) { try { emitter.next(stockPriceUpdate); @@ -89,8 +92,8 @@ public Flux getPublisher() { public Flux getPublisher(List stockCodes) { if (stockCodes != null) { - return publisher - .filter(stockPriceUpdate -> stockCodes.contains(stockPriceUpdate.getStockCode())); + return publisher.filter( + stockPriceUpdate -> stockCodes.contains(stockPriceUpdate.getStockCode())); } return publisher; } @@ -119,5 +122,4 @@ private StockPriceUpdate rollUpdate() { CURRENT_STOCK_PRICES.put(stockCode, newPrice); return new StockPriceUpdate(stockCode, LocalDateTime.now(), newPrice, incrementDollars); } - } diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerRxPublisher.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerRxPublisher.java index 11d4b906..52204fd5 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerRxPublisher.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/publishers/StockTickerRxPublisher.java @@ -39,15 +39,15 @@ public class StockTickerRxPublisher { private final Flowable publisher; public StockTickerRxPublisher() { - Observable stockPriceUpdateObservable = Observable.create(emitter -> { - - ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); - executorService.scheduleAtFixedRate(newStockTick(emitter), 0, 2, TimeUnit.SECONDS); - - }); - - ConnectableObservable connectableObservable = stockPriceUpdateObservable - .share().publish(); + Observable stockPriceUpdateObservable = + Observable.create( + emitter -> { + ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1); + executorService.scheduleAtFixedRate(newStockTick(emitter), 0, 2, TimeUnit.SECONDS); + }); + + ConnectableObservable connectableObservable = + stockPriceUpdateObservable.share().publish(); connectableObservable.connect(); publisher = connectableObservable.toFlowable(BackpressureStrategy.BUFFER); @@ -76,8 +76,8 @@ private Runnable newStockTick(ObservableEmitter emitter) { }; } - private void emitStocks(ObservableEmitter emitter, - List stockPriceUpdates) { + private void emitStocks( + ObservableEmitter emitter, List stockPriceUpdates) { for (StockPriceUpdate stockPriceUpdate : stockPriceUpdates) { try { emitter.onNext(stockPriceUpdate); @@ -93,8 +93,8 @@ public Flowable getPublisher() { public Flowable getPublisher(List stockCodes) { if (stockCodes != null) { - return publisher - .filter(stockPriceUpdate -> stockCodes.contains(stockPriceUpdate.getStockCode())); + return publisher.filter( + stockPriceUpdate -> stockCodes.contains(stockPriceUpdate.getStockCode())); } return publisher; } @@ -123,5 +123,4 @@ private StockPriceUpdate rollUpdate() { CURRENT_STOCK_PRICES.put(stockCode, newPrice); return new StockPriceUpdate(stockCode, LocalDateTime.now(), newPrice, incrementDollars); } - } diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Query.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Query.java index a94a2485..f1680ec9 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Query.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Query.java @@ -11,5 +11,4 @@ class Query implements GraphQLQueryResolver { String hello() { return HELLO; } - } diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/StockPriceUpdate.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/StockPriceUpdate.java index 232b6e1d..6508fc36 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/StockPriceUpdate.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/StockPriceUpdate.java @@ -11,7 +11,10 @@ public class StockPriceUpdate { private final BigDecimal stockPrice; private final BigDecimal stockPriceChange; - public StockPriceUpdate(String stockCode, LocalDateTime dateTime, BigDecimal stockPrice, + public StockPriceUpdate( + String stockCode, + LocalDateTime dateTime, + BigDecimal stockPrice, BigDecimal stockPriceChange) { this.stockCode = stockCode; this.dateTime = dateTime.format(DateTimeFormatter.ISO_DATE_TIME); diff --git a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Subscription.java b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Subscription.java index 122ae7df..e8654d8e 100644 --- a/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Subscription.java +++ b/example-graphql-subscription/src/main/java/graphql/kickstart/spring/web/boot/resolvers/Subscription.java @@ -18,5 +18,4 @@ class Subscription implements GraphQLSubscriptionResolver { Publisher stockQuotes(List stockCodes) { return stockTickerPublisher.getPublisher(stockCodes); } - } diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Comment.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Comment.java index 94d6febf..e3786329 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Comment.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Comment.java @@ -9,5 +9,4 @@ class Comment { private Long id; private String description; - } diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/GraphQLToolsSampleApplication.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/GraphQLToolsSampleApplication.java index 97e55f58..7b68eb89 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/GraphQLToolsSampleApplication.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/GraphQLToolsSampleApplication.java @@ -9,5 +9,4 @@ public class GraphQLToolsSampleApplication { public static void main(String[] args) { SpringApplication.run(GraphQLToolsSampleApplication.class, args); } - } diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Mutation.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Mutation.java index cad837a2..c62cac77 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Mutation.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Mutation.java @@ -12,5 +12,4 @@ public Post createPost(String text) { post.setText(text); return post; } - } diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/PostResolver.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/PostResolver.java index d19ecc70..a3f8bdf9 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/PostResolver.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/PostResolver.java @@ -22,5 +22,4 @@ class PostResolver implements GraphQLResolver { public List getComments(Post post) { return Optional.ofNullable(comments.get(post.getId())).orElseGet(Collections::emptyList); } - } diff --git a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Query.java b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Query.java index 7a3af309..74dfb584 100644 --- a/example-graphql-tools/src/main/java/com/graphql/sample/boot/Query.java +++ b/example-graphql-tools/src/main/java/com/graphql/sample/boot/Query.java @@ -9,5 +9,4 @@ class Query implements GraphQLQueryResolver { Post getPost(Long id) { return new Post(id); } - } diff --git a/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLToolsSampleApplicationTest.java b/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLToolsSampleApplicationTest.java index 3155356b..7c3a2848 100644 --- a/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLToolsSampleApplicationTest.java +++ b/example-graphql-tools/src/test/java/com/graphql/sample/boot/GraphQLToolsSampleApplicationTest.java @@ -20,13 +20,12 @@ @GraphQLTest class GraphQLToolsSampleApplicationTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; @Test void get_comments() throws IOException { - GraphQLResponse response = graphQLTestTemplate - .postForResource("graphql/post-get-comments.graphql"); + GraphQLResponse response = + graphQLTestTemplate.postForResource("graphql/post-get-comments.graphql"); assertNotNull(response); assertThat(response.isOk()).isTrue(); assertThat(response.get("$.data.post.id")).isEqualTo("1"); @@ -36,8 +35,9 @@ void get_comments() throws IOException { void get_comments_withFragments() throws IOException { List fragments = new ArrayList<>(); fragments.add("graphql/all-comment-fields-fragment.graphql"); - GraphQLResponse response = graphQLTestTemplate - .postForResource("graphql/post-get-comments-with-fragment.graphql", fragments); + GraphQLResponse response = + graphQLTestTemplate.postForResource( + "graphql/post-get-comments-with-fragment.graphql", fragments); assertNotNull(response); assertThat((response.isOk())).isTrue(); assertThat(response.get("$.data.post.id")).isEqualTo("1"); @@ -47,10 +47,9 @@ void get_comments_withFragments() throws IOException { void create_post() throws IOException { ObjectNode variables = new ObjectMapper().createObjectNode(); variables.put("text", "lorem ipsum dolor sit amet"); - GraphQLResponse response = graphQLTestTemplate - .perform("graphql/create-post.graphql", variables); + GraphQLResponse response = + graphQLTestTemplate.perform("graphql/create-post.graphql", variables); assertThat(response).isNotNull(); assertThat(response.get("$.data.createPost.id")).isNotNull(); } - } diff --git a/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/Application.java b/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/Application.java index 2816b331..a049d748 100644 --- a/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/Application.java +++ b/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/Application.java @@ -10,5 +10,4 @@ public class Application extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(Application.class, args); } - } diff --git a/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/CustomGraphQLContextBuilder.java b/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/CustomGraphQLContextBuilder.java index 8c78ab48..69d490f0 100644 --- a/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/CustomGraphQLContextBuilder.java +++ b/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/CustomGraphQLContextBuilder.java @@ -27,7 +27,8 @@ public CustomGraphQLContextBuilder(CustomerRepository customerRepository) { @Override public GraphQLContext build(HttpServletRequest req, HttpServletResponse response) { return DefaultGraphQLServletContext.createServletContext(buildDataLoaderRegistry(), null) - .with(req).with(response) + .with(req) + .with(response) .build(); } @@ -40,14 +41,15 @@ public GraphQLContext build() { public GraphQLContext build(Session session, HandshakeRequest request) { return DefaultGraphQLWebSocketContext.createWebSocketContext(buildDataLoaderRegistry(), null) .with(session) - .with(request).build(); + .with(request) + .build(); } private DataLoaderRegistry buildDataLoaderRegistry() { DataLoaderRegistry dataLoaderRegistry = new DataLoaderRegistry(); - DataLoader customerLoader = new DataLoader<>( - customerIds -> supplyAsync(() -> customerRepository.getUserNamesForIds(customerIds)) - ); + DataLoader customerLoader = + new DataLoader<>( + customerIds -> supplyAsync(() -> customerRepository.getUserNamesForIds(customerIds))); dataLoaderRegistry.register("customerDataLoader", customerLoader); return dataLoaderRegistry; } diff --git a/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/CustomerResolver.java b/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/CustomerResolver.java index 58fb22c9..196a99fa 100644 --- a/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/CustomerResolver.java +++ b/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/CustomerResolver.java @@ -19,5 +19,4 @@ public CompletableFuture getName(Customer customer, DataFetchingEnvironm } throw new IllegalStateException("No customer data loader found"); } - } diff --git a/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/WalmartQueryResolver.java b/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/WalmartQueryResolver.java index 3f24f942..187ce007 100644 --- a/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/WalmartQueryResolver.java +++ b/example-request-scoped-dataloader/src/main/java/graphql/servlet/examples/dataloader/requestscope/WalmartQueryResolver.java @@ -19,8 +19,8 @@ public WalmartQueryResolver() { } public List walmartCustomers(int storeNumber) { - return walmartData.get(storeNumber).parallelStream().map(Customer::new) + return walmartData.get(storeNumber).parallelStream() + .map(Customer::new) .collect(Collectors.toList()); } - } diff --git a/example-request-scoped-dataloader/src/test/java/graphql/servlet/examples/dataloader/requestscope/ApplicationTest.java b/example-request-scoped-dataloader/src/test/java/graphql/servlet/examples/dataloader/requestscope/ApplicationTest.java index 167e3286..6af4caa3 100644 --- a/example-request-scoped-dataloader/src/test/java/graphql/servlet/examples/dataloader/requestscope/ApplicationTest.java +++ b/example-request-scoped-dataloader/src/test/java/graphql/servlet/examples/dataloader/requestscope/ApplicationTest.java @@ -18,11 +18,9 @@ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class ApplicationTest { - @Autowired - private TestRestTemplate restTemplate; + @Autowired private TestRestTemplate restTemplate; - @Autowired - private CustomerRepository repository; + @Autowired private CustomerRepository repository; @Test void testSanity() { @@ -33,28 +31,31 @@ void testSanity() { @Test void testRequestScope() { - String requestGraphQL = "query {\n" + - " walmartCustomers(storeNumber:4177){\n" + - " customerId\n" + - " name\n" + - " }\n" + - "}"; + String requestGraphQL = + "query {\n" + + " walmartCustomers(storeNumber:4177){\n" + + " customerId\n" + + " name\n" + + " }\n" + + "}"; HttpHeaders headers = new HttpHeaders(); headers.add("content-type", "application/graphql"); - ResponseEntity response = this.restTemplate - .postForEntity("/graphql", new HttpEntity<>(requestGraphQL, headers), JsonNode.class); + ResponseEntity response = + this.restTemplate.postForEntity( + "/graphql", new HttpEntity<>(requestGraphQL, headers), JsonNode.class); - assertThat(response.getBody()).hasToString( - "{\"data\":{\"walmartCustomers\":[{\"customerId\":101,\"name\":\"Customer Name 1\"},{\"customerId\":102,\"name\":\"Customer Name 2\"},{\"customerId\":103,\"name\":\"Customer Name 3\"},{\"customerId\":104,\"name\":\"Customer Name 4\"}]}}"); + assertThat(response.getBody()) + .hasToString( + "{\"data\":{\"walmartCustomers\":[{\"customerId\":101,\"name\":\"Customer Name 1\"},{\"customerId\":102,\"name\":\"Customer Name 2\"},{\"customerId\":103,\"name\":\"Customer Name 3\"},{\"customerId\":104,\"name\":\"Customer Name 4\"}]}}"); repository.updateUsernameForId(101, "New Name 1"); - response = this.restTemplate - .postForEntity("/graphql", new HttpEntity<>(requestGraphQL, headers), JsonNode.class); + response = + this.restTemplate.postForEntity( + "/graphql", new HttpEntity<>(requestGraphQL, headers), JsonNode.class); - assertThat(response.getBody()).hasToString( - "{\"data\":{\"walmartCustomers\":[{\"customerId\":101,\"name\":\"New Name 1\"},{\"customerId\":102,\"name\":\"Customer Name 2\"},{\"customerId\":103,\"name\":\"Customer Name 3\"},{\"customerId\":104,\"name\":\"Customer Name 4\"}]}}"); + assertThat(response.getBody()) + .hasToString( + "{\"data\":{\"walmartCustomers\":[{\"customerId\":101,\"name\":\"New Name 1\"},{\"customerId\":102,\"name\":\"Customer Name 2\"},{\"customerId\":103,\"name\":\"Customer Name 3\"},{\"customerId\":104,\"name\":\"Customer Name 4\"}]}}"); } - - } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java index ef5f21d2..7e2f721a 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java @@ -22,9 +22,7 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ @SpringBootApplication public class ApplicationBootConfiguration { diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/SimpleListConnection.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/SimpleListConnection.java index bde31747..6d09fae7 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/SimpleListConnection.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/SimpleListConnection.java @@ -11,9 +11,7 @@ import lombok.AccessLevel; import lombok.RequiredArgsConstructor; -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ @RequiredArgsConstructor(access = AccessLevel.PROTECTED) public abstract class SimpleListConnection { @@ -22,7 +20,9 @@ public abstract class SimpleListConnection { public abstract > E createEdgeObject(); - public abstract , ? extends PageInfoObjectType>> C createConnectionObject(); + public abstract < + C extends ConnectionObjectType, ? extends PageInfoObjectType>> + C createConnectionObject(); private List> buildEdges() { List> edges = new ArrayList<>(); @@ -36,8 +36,8 @@ private List> buildEdges() { return edges; } - public , ? extends PageInfoObjectType>> C get( - DataFetchingEnvironment environment) { + public , ? extends PageInfoObjectType>> + C get(DataFetchingEnvironment environment) { List> edges = buildEdges(); int afterOffset = getOffsetFromCursor(environment.getArgument("after"), -1); @@ -76,7 +76,8 @@ private List> buildEdges() { pageInfo.setHasPreviousPage(!firstEdge.getCursor().equals(firstPresliceCursor)); pageInfo.setHasNextPage(!lastEdge.getCursor().equals(lastPresliceCursor)); - ConnectionObjectType, PageInfoObjectType> connection = createConnectionObject(); + ConnectionObjectType, PageInfoObjectType> connection = + createConnectionObject(); connection.setEdges(edges); connection.setPageInfo(pageInfo); @@ -84,8 +85,11 @@ private List> buildEdges() { return (C) connection; } - private , ? extends PageInfoObjectType>> E emptyConnection() { - ConnectionObjectType, PageInfoObjectType> connection = createConnectionObject(); + private < + E extends ConnectionObjectType, ? extends PageInfoObjectType>> + E emptyConnection() { + ConnectionObjectType, PageInfoObjectType> connection = + createConnectionObject(); connection.setPageInfo(new PageInfoObjectType()); //noinspection unchecked return (E) connection; @@ -95,8 +99,8 @@ private int getOffsetFromCursor(String cursor, int defaultValue) { if (cursor == null) { return defaultValue; } - String string = new String(java.util.Base64.getDecoder().decode(cursor), - StandardCharsets.UTF_8); + String string = + new String(java.util.Base64.getDecoder().decode(cursor), StandardCharsets.UTF_8); return Integer.parseInt(string.substring(DUMMY_CURSOR_PREFIX.length())); } @@ -104,5 +108,4 @@ private String createCursor(int offset) { byte[] lala = (DUMMY_CURSOR_PREFIX + offset).getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(lala); } - } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/TodoSimpleListConnection.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/TodoSimpleListConnection.java index a25397f8..04569065 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/TodoSimpleListConnection.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/TodoSimpleListConnection.java @@ -5,9 +5,7 @@ import graphql.kickstart.spring.web.boot.sample.schema.objecttype.TodoObjectType.TodoEdgeObjectType; import java.util.List; -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ @SuppressWarnings("unchecked") public class TodoSimpleListConnection extends SimpleListConnection { @@ -24,5 +22,4 @@ public TodoEdgeObjectType createEdgeObject() { public TodoConnectionObjectType createConnectionObject() { return new TodoObjectType.TodoConnectionObjectType(); } - } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/TodoSchema.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/TodoSchema.java index 88f6a582..8c7e1367 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/TodoSchema.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/TodoSchema.java @@ -39,8 +39,7 @@ @GraphQLSchema public class TodoSchema { - @GraphQLSchemaQuery - private RootObjectType root; + @GraphQLSchemaQuery private RootObjectType root; private UserObjectType theOnlyUser = new UserObjectType(); private List todos = new ArrayList<>(); @@ -48,7 +47,6 @@ public class TodoSchema { private TodoSimpleListConnection simpleConnectionTodo; private int nextTodoId = 0; - public TodoSchema() { addTodo("Do Something"); addTodo("Other todo"); @@ -79,20 +77,24 @@ public void renameTodo(String id, String text) { } public List removeCompletedTodos() { - List toDelete = todos.stream() - .filter(TodoObjectType::isComplete) - .map(todoObjectType -> todoObjectType.getId(todoObjectType)) - .collect(Collectors.toList()); + List toDelete = + todos.stream() + .filter(TodoObjectType::isComplete) + .map(todoObjectType -> todoObjectType.getId(todoObjectType)) + .collect(Collectors.toList()); todos.removeIf(todo -> toDelete.contains(todo.getId(todo))); return toDelete; } public List markAllTodos(boolean complete) { List changed = new ArrayList<>(); - todos.stream().filter(todo -> complete != todo.isComplete()).forEach(todo -> { - changed.add(todo.getId(todo)); - todo.setComplete(complete); - }); + todos.stream() + .filter(todo -> complete != todo.isComplete()) + .forEach( + todo -> { + changed.add(todo.getId(todo)); + todo.setComplete(complete); + }); return changed; } @@ -110,7 +112,8 @@ public TodoObjectType getTodo(String id) { } public List getTodos(List ids) { - return todos.stream().filter(todo -> ids.contains(todo.getId(todo))) + return todos.stream() + .filter(todo -> ids.contains(todo.getId(todo))) .collect(Collectors.toList()); } @@ -118,16 +121,13 @@ public UserObjectType getTheOnlyUser() { return theOnlyUser; } - public TodoSimpleListConnection getSimpleConnectionTodo() { return simpleConnectionTodo; } @GraphQLMutation @GraphQLDescription("Mutation to add new todo item") - public - @GraphQLOut("todoEdge") - TodoObjectType.TodoEdgeObjectType addTodoMutation( + public @GraphQLOut("todoEdge") TodoObjectType.TodoEdgeObjectType addTodoMutation( @GraphQLIn("addTodoInput") AddTodoIn addTodoInput) { TodoObjectType.TodoEdgeObjectType todoEdgeObjectType = new TodoObjectType.TodoEdgeObjectType(); @@ -143,11 +143,11 @@ TodoObjectType.TodoEdgeObjectType addTodoMutation( // --- mutations @GraphQLMutation - public - @GraphQLOut("filename") - String uploadFile(GraphQLServletContext graphQLContext) { - return graphQLContext.getParts().values().stream().flatMap(Collection::stream) - .map(Part::getName).collect(Collectors.joining(", ")); + public @GraphQLOut("filename") String uploadFile(GraphQLServletContext graphQLContext) { + return graphQLContext.getParts().values().stream() + .flatMap(Collection::stream) + .map(Part::getName) + .collect(Collectors.joining(", ")); } @GraphQLMutation @@ -167,5 +167,4 @@ public void setText(String text) { this.text = text; } } - } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/BaseObjectType.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/BaseObjectType.java index 98376f80..cf924d02 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/BaseObjectType.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/BaseObjectType.java @@ -23,13 +23,10 @@ import com.oembedler.moon.graphql.engine.stereotype.GraphQLIgnore; import graphql.relay.Relay; -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ public class BaseObjectType implements RelayNode { - @GraphQLIgnore - private String id; + @GraphQLIgnore private String id; public String getId(RelayNode relayNode) { BaseObjectType baseObjectType = (BaseObjectType) relayNode; diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/RootObjectType.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/RootObjectType.java index 9ef007ff..0b210c1f 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/RootObjectType.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/RootObjectType.java @@ -30,9 +30,7 @@ import graphql.kickstart.spring.web.boot.sample.schema.TodoSchema; import org.springframework.beans.factory.annotation.Autowired; -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ @GraphQLObject("Root") public class RootObjectType { @@ -41,9 +39,7 @@ public class RootObjectType { @GraphQLDescription("Root query version number") public static final String VERSION = "0.9.0.2"; - @Autowired - @GraphQLIgnore - private TodoSchema todoSchema; + @Autowired @GraphQLIgnore private TodoSchema todoSchema; @GraphQLField public UserObjectType viewer() { diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/TodoObjectType.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/TodoObjectType.java index 35753d74..b89c33ff 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/TodoObjectType.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/TodoObjectType.java @@ -24,9 +24,7 @@ import com.oembedler.moon.graphql.engine.relay.PageInfoObjectType; import com.oembedler.moon.graphql.engine.stereotype.GraphQLObject; -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ @GraphQLObject("Todo") public class TodoObjectType extends BaseObjectType { @@ -50,14 +48,9 @@ public void setComplete(boolean complete) { } @GraphQLObject - public static class TodoConnectionObjectType extends - ConnectionObjectType { - - } + public static class TodoConnectionObjectType + extends ConnectionObjectType {} @GraphQLObject - public static class TodoEdgeObjectType extends EdgeObjectType { - - } - + public static class TodoEdgeObjectType extends EdgeObjectType {} } diff --git a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/UserObjectType.java b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/UserObjectType.java index d5885e6d..3cc4ffca 100644 --- a/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/UserObjectType.java +++ b/example-spring-common/src/main/java/graphql/kickstart/spring/web/boot/sample/schema/objecttype/UserObjectType.java @@ -27,15 +27,11 @@ import graphql.schema.DataFetchingEnvironment; import org.springframework.beans.factory.annotation.Autowired; -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ @GraphQLObject("User") public class UserObjectType extends BaseObjectType { - @Autowired - @GraphQLIgnore - private TodoSchema todoSchema; + @Autowired @GraphQLIgnore private TodoSchema todoSchema; private String name = "someId"; @@ -48,12 +44,12 @@ public void setName(String name) { } @GraphQLField - public TodoObjectType.TodoConnectionObjectType todos(@GraphQLIn("before") String before, + public TodoObjectType.TodoConnectionObjectType todos( + @GraphQLIn("before") String before, @GraphQLIn("after") String after, @GraphQLIn(value = "first", defaultSpel = "1") Integer first, @GraphQLIn(value = "last", defaultProvider = "1") Integer last, DataFetchingEnvironment environment) { return todoSchema.getSimpleConnectionTodo().get(environment); } - } diff --git a/example-webflux/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationWebfluxConfiguration.java b/example-webflux/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationWebfluxConfiguration.java index cb6bf8d4..31da7c8e 100644 --- a/example-webflux/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationWebfluxConfiguration.java +++ b/example-webflux/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationWebfluxConfiguration.java @@ -30,9 +30,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.web.reactive.config.EnableWebFlux; -/** - * @author Max Günther - */ +/** @author Max Günther */ @SpringBootApplication @EnableWebFlux public class ApplicationWebfluxConfiguration { @@ -45,16 +43,15 @@ public static void main(String[] args) { GraphQLSchema schema() { DataFetcher test = env -> "response"; return GraphQLSchema.newSchema() - .query(GraphQLObjectType.newObject() - .name("query") - .field(field -> field - .name("test") - .type(Scalars.GraphQLString) - ) - .build()) - .codeRegistry(GraphQLCodeRegistry.newCodeRegistry() - .dataFetcher(FieldCoordinates.coordinates("query", "test"), test) - .build()) + .query( + GraphQLObjectType.newObject() + .name("query") + .field(field -> field.name("test").type(Scalars.GraphQLString)) + .build()) + .codeRegistry( + GraphQLCodeRegistry.newCodeRegistry() + .dataFetcher(FieldCoordinates.coordinates("query", "test"), test) + .build()) .build(); } } diff --git a/example/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java b/example/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java index 538db443..208693c6 100644 --- a/example/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java +++ b/example/src/main/java/graphql/kickstart/spring/web/boot/sample/ApplicationBootConfiguration.java @@ -40,16 +40,15 @@ public static void main(String[] args) { GraphQLSchema schema() { DataFetcher test = env -> "response"; return GraphQLSchema.newSchema() - .query(GraphQLObjectType.newObject() - .name("query") - .field(field -> field - .name("test") - .type(Scalars.GraphQLString) - ) - .build()) - .codeRegistry(GraphQLCodeRegistry.newCodeRegistry() - .dataFetcher(FieldCoordinates.coordinates("query", "test"), test) - .build()) + .query( + GraphQLObjectType.newObject() + .name("query") + .field(field -> field.name("test").type(Scalars.GraphQLString)) + .build()) + .codeRegistry( + GraphQLCodeRegistry.newCodeRegistry() + .dataFetcher(FieldCoordinates.coordinates("query", "test"), test) + .build()) .build(); } } diff --git a/github-build.sh b/github-build.sh index cfec06b2..6e9d498f 100644 --- a/github-build.sh +++ b/github-build.sh @@ -45,7 +45,7 @@ git config --global user.name "GitHub Actions" echo "Deploying release to Maven Central" removeSnapshots -./gradlew clean build publish closeAndReleaseRepository +./gradlew clean build publish closeAndReleaseRepository -x verifyGoogleJavaFormat commitRelease bumpVersion diff --git a/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/GraphiQLController.java b/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/GraphiQLController.java index d26277ec..5e4334fa 100644 --- a/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/GraphiQLController.java +++ b/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/GraphiQLController.java @@ -21,9 +21,7 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ @Slf4j public abstract class GraphiQLController { @@ -32,11 +30,9 @@ public abstract class GraphiQLController { private static final String GRAPHIQL = "graphiql"; private static final String FAVICON_GRAPHQL_ORG = "//graphql.org/img/favicon.png"; - @Autowired - private Environment environment; + @Autowired private Environment environment; - @Autowired - private GraphiQLProperties graphiQLProperties; + @Autowired private GraphiQLProperties graphiQLProperties; private String template; private String props; @@ -55,8 +51,9 @@ private void loadTemplate() throws IOException { } private void loadProps() throws IOException { - props = new PropsLoader(environment, "graphiql.props.resources.", "graphiql.props.variables.") - .load(); + props = + new PropsLoader(environment, "graphiql.props.resources.", "graphiql.props.variables.") + .load(); } private void loadHeaders() { @@ -64,65 +61,91 @@ private void loadHeaders() { headerProperties = propertyReader.load(); } - public byte[] graphiql(String contextPath, @PathVariable Map params, - Object csrf) { + public byte[] graphiql( + String contextPath, @PathVariable Map params, Object csrf) { if (csrf != null) { CsrfToken csrfToken = (CsrfToken) csrf; headerProperties.setProperty(csrfToken.getHeaderName(), csrfToken.getToken()); } - Map replacements = getReplacements( - constructGraphQlEndpoint(contextPath, params), - contextPath + graphiQLProperties.getEndpoint().getSubscriptions(), - contextPath + graphiQLProperties.getBasePath() - ); + Map replacements = + getReplacements( + constructGraphQlEndpoint(contextPath, params), + contextPath + graphiQLProperties.getEndpoint().getSubscriptions(), + contextPath + graphiQLProperties.getBasePath()); String populatedTemplate = StringSubstitutor.replace(template, replacements); return populatedTemplate.getBytes(Charset.defaultCharset()); } private Map getReplacements( - String graphqlEndpoint, - String subscriptionsEndpoint, - String staticBasePath - ) { + String graphqlEndpoint, String subscriptionsEndpoint, String staticBasePath) { Map replacements = new HashMap<>(); replacements.put("graphqlEndpoint", graphqlEndpoint); replacements.put("subscriptionsEndpoint", subscriptionsEndpoint); replacements.put("staticBasePath", staticBasePath); replacements.put("pageTitle", graphiQLProperties.getPageTitle()); - replacements - .put("pageFavicon", getResourceUrl(staticBasePath, "favicon.ico", FAVICON_GRAPHQL_ORG)); - replacements.put("es6PromiseJsUrl", getResourceUrl(staticBasePath, "es6-promise.auto.min.js", - joinCdnjsPath("es6-promise", "4.1.1", "es6-promise.auto.min.js"))); - replacements.put("fetchJsUrl", getResourceUrl(staticBasePath, "fetch.min.js", - joinCdnjsPath("fetch", "2.0.4", "fetch.min.js"))); - replacements.put("reactJsUrl", getResourceUrl(staticBasePath, "react.min.js", - joinCdnjsPath("react", "16.8.3", "umd/react.production.min.js"))); - replacements.put("reactDomJsUrl", getResourceUrl(staticBasePath, "react-dom.min.js", - joinCdnjsPath("react-dom", "16.8.3", "umd/react-dom.production.min.js"))); - replacements.put("graphiqlCssUrl", getResourceUrl(staticBasePath, "graphiql.min.css", - joinJsDelivrPath(GRAPHIQL, graphiQLProperties.getCdn().getVersion(), "graphiql.css"))); - replacements.put("graphiqlJsUrl", getResourceUrl(staticBasePath, "graphiql.min.js", - joinJsDelivrPath(GRAPHIQL, graphiQLProperties.getCdn().getVersion(), "graphiql.min.js"))); - replacements.put("subscriptionsTransportWsBrowserClientUrl", getResourceUrl(staticBasePath, - "subscriptions-transport-ws-browser-client.js", - joinJsDelivrPath("subscriptions-transport-ws", "0.8.3", "browser/client.js"))); - replacements.put("graphiqlSubscriptionsFetcherBrowserClientUrl", getResourceUrl(staticBasePath, - "graphiql-subscriptions-fetcher-browser-client.js", - joinJsDelivrPath("graphiql-subscriptions-fetcher", "0.0.2", "browser/client.js"))); + replacements.put( + "pageFavicon", getResourceUrl(staticBasePath, "favicon.ico", FAVICON_GRAPHQL_ORG)); + replacements.put( + "es6PromiseJsUrl", + getResourceUrl( + staticBasePath, + "es6-promise.auto.min.js", + joinCdnjsPath("es6-promise", "4.1.1", "es6-promise.auto.min.js"))); + replacements.put( + "fetchJsUrl", + getResourceUrl( + staticBasePath, "fetch.min.js", joinCdnjsPath("fetch", "2.0.4", "fetch.min.js"))); + replacements.put( + "reactJsUrl", + getResourceUrl( + staticBasePath, + "react.min.js", + joinCdnjsPath("react", "16.8.3", "umd/react.production.min.js"))); + replacements.put( + "reactDomJsUrl", + getResourceUrl( + staticBasePath, + "react-dom.min.js", + joinCdnjsPath("react-dom", "16.8.3", "umd/react-dom.production.min.js"))); + replacements.put( + "graphiqlCssUrl", + getResourceUrl( + staticBasePath, + "graphiql.min.css", + joinJsDelivrPath(GRAPHIQL, graphiQLProperties.getCdn().getVersion(), "graphiql.css"))); + replacements.put( + "graphiqlJsUrl", + getResourceUrl( + staticBasePath, + "graphiql.min.js", + joinJsDelivrPath( + GRAPHIQL, graphiQLProperties.getCdn().getVersion(), "graphiql.min.js"))); + replacements.put( + "subscriptionsTransportWsBrowserClientUrl", + getResourceUrl( + staticBasePath, + "subscriptions-transport-ws-browser-client.js", + joinJsDelivrPath("subscriptions-transport-ws", "0.8.3", "browser/client.js"))); + replacements.put( + "graphiqlSubscriptionsFetcherBrowserClientUrl", + getResourceUrl( + staticBasePath, + "graphiql-subscriptions-fetcher-browser-client.js", + joinJsDelivrPath("graphiql-subscriptions-fetcher", "0.0.2", "browser/client.js"))); replacements.put("props", props); try { replacements.put("headers", new ObjectMapper().writeValueAsString(headerProperties)); } catch (JsonProcessingException e) { log.error("Cannot serialize headers", e); } - replacements - .put("subscriptionClientTimeout", - String.valueOf(graphiQLProperties.getSubscriptions().getTimeout() * 1000)); - replacements - .put("subscriptionClientReconnect", - String.valueOf(graphiQLProperties.getSubscriptions().isReconnect())); + replacements.put( + "subscriptionClientTimeout", + String.valueOf(graphiQLProperties.getSubscriptions().getTimeout() * 1000)); + replacements.put( + "subscriptionClientReconnect", + String.valueOf(graphiQLProperties.getSubscriptions().isReconnect())); replacements.put("editorThemeCss", getEditorThemeCssURL()); return replacements; } @@ -132,9 +155,7 @@ private String getEditorThemeCssURL() { if (theme != null) { return String.format( "https://cdnjs.cloudflare.com/ajax/libs/codemirror/%s/theme/%s.min.css", - graphiQLProperties.getCodeMirror().getVersion(), - theme.split("\\s")[0] - ); + graphiQLProperties.getCodeMirror().getVersion(), theme.split("\\s")[0]); } return ""; } @@ -158,8 +179,8 @@ private String joinJsDelivrPath(String library, String cdnVersion, String cdnFil return CDN_JSDELIVR_NET_NPM + library + "@" + cdnVersion + "/" + cdnFileName; } - private String constructGraphQlEndpoint(String contextPath, - @RequestParam Map params) { + private String constructGraphQlEndpoint( + String contextPath, @RequestParam Map params) { String endpoint = graphiQLProperties.getEndpoint().getGraphql(); for (Map.Entry param : params.entrySet()) { endpoint = endpoint.replaceAll("\\{" + param.getKey() + "}", param.getValue()); @@ -169,5 +190,4 @@ private String constructGraphQlEndpoint(String contextPath, } return endpoint; } - } diff --git a/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/GraphiQLProperties.java b/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/GraphiQLProperties.java index 85b69d7a..ae1d6980 100644 --- a/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/GraphiQLProperties.java +++ b/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/GraphiQLProperties.java @@ -34,9 +34,7 @@ static class Props { private GraphiQLVariables variables = new GraphiQLVariables(); - /** - * See https://github.com/graphql/graphiql/tree/main/packages/graphiql#props - */ + /** See https://github.com/graphql/graphiql/tree/main/packages/graphiql#props */ @Data static class GraphiQLVariables { diff --git a/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/ReactiveGraphiQLController.java b/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/ReactiveGraphiQLController.java index 7b114bfb..78513457 100644 --- a/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/ReactiveGraphiQLController.java +++ b/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/ReactiveGraphiQLController.java @@ -27,13 +27,15 @@ public void onceConstructed() throws IOException { } @GetMapping(value = "${graphiql.mapping:/graphiql}") - public Mono graphiql(ServerHttpRequest request, ServerHttpResponse response, + public Mono graphiql( + ServerHttpRequest request, + ServerHttpResponse response, @PathVariable Map params) { response.getHeaders().setContentType(MediaType.TEXT_HTML); Object csrf = request.getQueryParams().getFirst("_csrf"); - return response.writeWith(Mono.just(request.getPath().contextPath().value()) - .map(contextPath -> super.graphiql(contextPath, params, csrf)) - .map(dataBufferFactory::wrap)); + return response.writeWith( + Mono.just(request.getPath().contextPath().value()) + .map(contextPath -> super.graphiql(contextPath, params, csrf)) + .map(dataBufferFactory::wrap)); } - } diff --git a/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/ServletGraphiQLController.java b/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/ServletGraphiQLController.java index bb126c71..0098519e 100644 --- a/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/ServletGraphiQLController.java +++ b/graphiql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/graphiql/boot/ServletGraphiQLController.java @@ -10,9 +10,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ @Slf4j @Controller public class ServletGraphiQLController extends GraphiQLController { @@ -24,12 +22,14 @@ public void onceConstructed() throws IOException { } @GetMapping(value = "${graphiql.mapping:/graphiql}") - public void graphiql(HttpServletRequest request, HttpServletResponse response, - @PathVariable Map params) throws IOException { + public void graphiql( + HttpServletRequest request, + HttpServletResponse response, + @PathVariable Map params) + throws IOException { response.setContentType("text/html; charset=UTF-8"); Object csrf = request.getAttribute("_csrf"); byte[] graphiqlBytes = super.graphiql(request.getContextPath(), params, csrf); response.getOutputStream().write(graphiqlBytes); } - } diff --git a/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/ReactiveGraphiQLControllerTest.java b/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/ReactiveGraphiQLControllerTest.java index 41aa1679..5632a910 100644 --- a/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/ReactiveGraphiQLControllerTest.java +++ b/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/ReactiveGraphiQLControllerTest.java @@ -15,22 +15,22 @@ @WebFluxTest class ReactiveGraphiQLControllerTest { - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; @Test void shouldBeAbleToAccessGraphiQL() { - webTestClient.get() + webTestClient + .get() .uri("/graphiql") .exchange() - .expectStatus().is2xxSuccessful() - .expectHeader().contentType(MediaType.TEXT_HTML); + .expectStatus() + .is2xxSuccessful() + .expectHeader() + .contentType(MediaType.TEXT_HTML); } @SpringBootConfiguration @TestPropertySource(properties = "graphiql.enabled=true") @Import(GraphiQLAutoConfiguration.class) - public static class ReactiveTestApplication { - - } + public static class ReactiveTestApplication {} } diff --git a/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/ServletGraphiQLControllerTest.java b/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/ServletGraphiQLControllerTest.java index 1dce4a81..64d6b4f7 100644 --- a/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/ServletGraphiQLControllerTest.java +++ b/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/ServletGraphiQLControllerTest.java @@ -18,12 +18,12 @@ @WebMvcTest class ServletGraphiQLControllerTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test void shouldBeAbleToAccessGraphiQL() throws Exception { - mockMvc.perform(get("/graphiql")) + mockMvc + .perform(get("/graphiql")) .andExpect(status().is2xxSuccessful()) .andExpect(content().contentType("text/html; charset=UTF-8")); } @@ -31,7 +31,5 @@ void shouldBeAbleToAccessGraphiQL() throws Exception { @SpringBootConfiguration @TestPropertySource(properties = "graphiql.enabled=true") @Import(GraphiQLAutoConfiguration.class) - public static class ServletTestApplication { - - } + public static class ServletTestApplication {} } diff --git a/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/test/AbstractAutoConfigurationTest.java b/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/test/AbstractAutoConfigurationTest.java index 84a15326..c944649c 100644 --- a/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/test/AbstractAutoConfigurationTest.java +++ b/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/test/AbstractAutoConfigurationTest.java @@ -6,9 +6,7 @@ import org.springframework.context.annotation.AnnotationConfigRegistry; import org.springframework.context.support.AbstractApplicationContext; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ public abstract class AbstractAutoConfigurationTest { private final Class contextClass; @@ -20,8 +18,8 @@ protected AbstractAutoConfigurationTest(Class autoConfiguration) { this(AnnotationConfigApplicationContext.class, autoConfiguration); } - protected AbstractAutoConfigurationTest(Class contextClass, - Class autoConfiguration) { + protected AbstractAutoConfigurationTest( + Class contextClass, Class autoConfiguration) { assert AnnotationConfigRegistry.class.isAssignableFrom(contextClass); this.contextClass = contextClass; this.autoConfiguration = autoConfiguration; diff --git a/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/test/GraphiQLControllerTest.java b/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/test/GraphiQLControllerTest.java index e6f87630..6e187d27 100644 --- a/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/test/GraphiQLControllerTest.java +++ b/graphiql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/graphiql/boot/test/GraphiQLControllerTest.java @@ -14,9 +14,7 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ class GraphiQLControllerTest extends AbstractAutoConfigurationTest { public GraphiQLControllerTest() { diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsAutoConfiguration.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsAutoConfiguration.java index 803c8feb..544dbed4 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsAutoConfiguration.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsAutoConfiguration.java @@ -57,10 +57,14 @@ public GraphQLInterfaceTypeResolver graphQLInterfaceTypeResolver() { public GraphQLAnnotations graphQLAnnotations() { GraphQLAnnotations graphQLAnnotations = new GraphQLAnnotations(); if (nonNull(graphQLAnnotationsProperties.getInputPrefix())) { - graphQLAnnotations.getContainer().setInputPrefix(graphQLAnnotationsProperties.getInputPrefix()); + graphQLAnnotations + .getContainer() + .setInputPrefix(graphQLAnnotationsProperties.getInputPrefix()); } if (nonNull(graphQLAnnotationsProperties.getInputSuffix())) { - graphQLAnnotations.getContainer().setInputSuffix(graphQLAnnotationsProperties.getInputSuffix()); + graphQLAnnotations + .getContainer() + .setInputSuffix(graphQLAnnotationsProperties.getInputSuffix()); } return graphQLAnnotations; } @@ -69,27 +73,37 @@ public GraphQLAnnotations graphQLAnnotations() { public GraphQLSchema graphQLSchema(final GraphQLAnnotations graphQLAnnotations) { log.info( "Using GraphQL Annotations library to build the schema. Schema definition files will be ignored."); - log.info("GraphQL classes are searched in the following package (including subpackages): {}", + log.info( + "GraphQL classes are searched in the following package (including subpackages): {}", graphQLAnnotationsProperties.getBasePackage()); final AnnotationsSchemaCreator.Builder builder = newAnnotationsSchema(); - final Reflections reflections = new Reflections(graphQLAnnotationsProperties.getBasePackage(), - new MethodAnnotationsScanner(), new SubTypesScanner(), new TypeAnnotationsScanner()); + final Reflections reflections = + new Reflections( + graphQLAnnotationsProperties.getBasePackage(), + new MethodAnnotationsScanner(), + new SubTypesScanner(), + new TypeAnnotationsScanner()); builder.setAlwaysPrettify(graphQLAnnotationsProperties.isAlwaysPrettify()); setQueryResolverClass(builder, reflections); setMutationResolverClass(builder, reflections); setSubscriptionResolverClass(builder, reflections); - getTypesAnnotatedWith(reflections, GraphQLDirectiveDefinition.class).forEach(directive -> { - log.info("Registering directive {}", directive); - builder.directive(directive); - }); - getTypesAnnotatedWith(reflections, GraphQLTypeExtension.class).forEach(typeExtension -> { - log.info("Registering type extension {}", typeExtension); - builder.typeExtension(typeExtension); - }); - typeFunctions.forEach(typeFunction -> { - log.info("Registering type function {}", typeFunction.getClass()); - builder.typeFunction(typeFunction); - }); + getTypesAnnotatedWith(reflections, GraphQLDirectiveDefinition.class) + .forEach( + directive -> { + log.info("Registering directive {}", directive); + builder.directive(directive); + }); + getTypesAnnotatedWith(reflections, GraphQLTypeExtension.class) + .forEach( + typeExtension -> { + log.info("Registering type extension {}", typeExtension); + builder.typeExtension(typeExtension); + }); + typeFunctions.forEach( + typeFunction -> { + log.info("Registering type function {}", typeFunction.getClass()); + builder.typeFunction(typeFunction); + }); if (!customScalarTypes.isEmpty()) { builder.typeFunction(new GraphQLScalarTypeFunction(customScalarTypes)); } @@ -99,60 +113,64 @@ public GraphQLSchema graphQLSchema(final GraphQLAnnotations graphQLAnnotations) log.info("Using custom annotation process of type {}", graphQLAnnotations.getClass()); } builder.setAnnotationsProcessor(graphQLAnnotations); - relay.ifPresent(r -> { - log.info("Registering relay {}", r.getClass()); - builder.setRelay(r); - }); + relay.ifPresent( + r -> { + log.info("Registering relay {}", r.getClass()); + builder.setRelay(r); + }); registerGraphQLInterfaceImplementations(reflections, builder); return builder.build(); } private void setSubscriptionResolverClass( - final AnnotationsSchemaCreator.Builder builder, - final Reflections reflections - ) { - final Set> subscriptionResolvers - = getTypesAnnotatedWith(reflections, GraphQLSubscriptionResolver.class); + final AnnotationsSchemaCreator.Builder builder, final Reflections reflections) { + final Set> subscriptionResolvers = + getTypesAnnotatedWith(reflections, GraphQLSubscriptionResolver.class); if (subscriptionResolvers.size() > 1) { throw new MultipleSubscriptionResolversException(); } - subscriptionResolvers.stream().findFirst().ifPresent(subscriptionClass -> { - log.info("Registering subscription resolver class: {}", subscriptionClass); - builder.subscription(subscriptionClass); - }); + subscriptionResolvers.stream() + .findFirst() + .ifPresent( + subscriptionClass -> { + log.info("Registering subscription resolver class: {}", subscriptionClass); + builder.subscription(subscriptionClass); + }); } private void setMutationResolverClass( - final AnnotationsSchemaCreator.Builder builder, - final Reflections reflections - ) { - final Set> mutationResolvers - = getTypesAnnotatedWith(reflections, GraphQLMutationResolver.class); + final AnnotationsSchemaCreator.Builder builder, final Reflections reflections) { + final Set> mutationResolvers = + getTypesAnnotatedWith(reflections, GraphQLMutationResolver.class); if (mutationResolvers.size() > 1) { throw new MultipleMutationResolversException(); } - mutationResolvers.stream().findFirst().ifPresent(mutationClass -> { - log.info("Registering mutation resolver class: {}", mutationClass); - builder.mutation(mutationClass); - }); + mutationResolvers.stream() + .findFirst() + .ifPresent( + mutationClass -> { + log.info("Registering mutation resolver class: {}", mutationClass); + builder.mutation(mutationClass); + }); } private void setQueryResolverClass( - final AnnotationsSchemaCreator.Builder builder, - final Reflections reflections - ) { - final Set> queryResolvers - = getTypesAnnotatedWith(reflections, GraphQLQueryResolver.class); + final AnnotationsSchemaCreator.Builder builder, final Reflections reflections) { + final Set> queryResolvers = + getTypesAnnotatedWith(reflections, GraphQLQueryResolver.class); if (queryResolvers.isEmpty()) { throw new MissingQueryResolverException(); } if (queryResolvers.size() > 1) { throw new MultipleQueryResolversException(); } - queryResolvers.stream().findFirst().ifPresent(queryClass -> { - log.info("Registering query resolver class: {}", queryClass); - builder.query(queryClass); - }); + queryResolvers.stream() + .findFirst() + .ifPresent( + queryClass -> { + log.info("Registering query resolver class: {}", queryClass); + builder.query(queryClass); + }); } /** @@ -162,12 +180,10 @@ private void setQueryResolverClass( * @param reflections the {@link Reflections} instance * @param annotation the annotation class * @return The set of classes annotated with the specified annotation, or an empty set if no - * annotated classes found. + * annotated classes found. */ private Set> getTypesAnnotatedWith( - final Reflections reflections, - final Class annotation - ) { + final Reflections reflections, final Class annotation) { try { return reflections.getTypesAnnotatedWith(annotation); } catch (ReflectionsException e) { @@ -179,30 +195,32 @@ private Set> getTypesAnnotatedWith( * This is required, because normally implementations of interfaces are not explicitly returned by * any resolver method, and therefor not added to the schema automatically. * - * All interfaces are considered GraphQL interfaces if they are declared in the configured package - * and have at least one {@link GraphQLField}-annotated methods. + *

All interfaces are considered GraphQL interfaces if they are declared in the configured + * package and have at least one {@link GraphQLField}-annotated methods. * * @param reflections the reflections instance. * @param builder the schema builder instance. */ private void registerGraphQLInterfaceImplementations( - final Reflections reflections, - final AnnotationsSchemaCreator.Builder builder - ) { + final Reflections reflections, final AnnotationsSchemaCreator.Builder builder) { Predicate> implementationQualifiesForInclusion = - type -> !(graphQLAnnotationsProperties.isIgnoreAbstractInterfaceImplementations() + type -> + !(graphQLAnnotationsProperties.isIgnoreAbstractInterfaceImplementations() && Modifier.isAbstract(type.getModifiers())); reflections.getMethodsAnnotatedWith(GraphQLField.class).stream() .map(Method::getDeclaringClass) .filter(Class::isInterface) - .forEach(graphQLInterface -> - reflections.getSubTypesOf(graphQLInterface).stream() - .filter(implementationQualifiesForInclusion) - .forEach(implementation -> { - log.info("Registering {} as an implementation of GraphQL interface {}", - implementation, - graphQLInterface); - builder.additionalType(implementation); - })); + .forEach( + graphQLInterface -> + reflections.getSubTypesOf(graphQLInterface).stream() + .filter(implementationQualifiesForInclusion) + .forEach( + implementation -> { + log.info( + "Registering {} as an implementation of GraphQL interface {}", + implementation, + graphQLInterface); + builder.additionalType(implementation); + })); } } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsProperties.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsProperties.java index 3de34e0e..6a37b3bb 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsProperties.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsProperties.java @@ -16,36 +16,31 @@ @ConfigurationProperties(prefix = "graphql.annotations") public class GraphQLAnnotationsProperties { - /** - * The base package where GraphQL definitions (resolvers, types etc.) are searched for. - */ + /** The base package where GraphQL definitions (resolvers, types etc.) are searched for. */ private @NotBlank String basePackage; /** * Set if fields should be globally prettified (removes get/set/is prefixes from names). Defaults * to true. */ - @Builder.Default - private boolean alwaysPrettify = true; + @Builder.Default private boolean alwaysPrettify = true; /** - * The prefix to use for input type names. - * If not configured the default prefix of the GraphQL-Java Annotations library is used. - * Configure an empty prefix for clearing the library's default prefix. + * The prefix to use for input type names. If not configured the default prefix of the + * GraphQL-Java Annotations library is used. Configure an empty prefix for clearing the library's + * default prefix. */ private String inputPrefix; /** - * The suffix to use for input type names. - * If not configured the default suffix of the GraphQL-Java Annotations library is used. + * The suffix to use for input type names. If not configured the default suffix of the + * GraphQL-Java Annotations library is used. */ private String inputSuffix; /** - * If set to true abstract classes implementing a GraphQL interface will not be added to the schema. - * Defaults to false for backward compatibility. + * If set to true abstract classes implementing a GraphQL interface will not be added + * to the schema. Defaults to false for backward compatibility. */ - @Builder.Default - private boolean ignoreAbstractInterfaceImplementations = false; - + @Builder.Default private boolean ignoreAbstractInterfaceImplementations = false; } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceTypeResolver.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceTypeResolver.java index b268170e..1aa6f1cb 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceTypeResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceTypeResolver.java @@ -11,10 +11,9 @@ * Type resolver for GraphQL interfaces. * * @see Issue with - * workaround. - * - * Apply this interface to GraphQL interfaces using the {@link graphql.annotations.annotationTypes.GraphQLTypeResolver} - * annotation. + * workaround. + *

Apply this interface to GraphQL interfaces using the {@link + * graphql.annotations.annotationTypes.GraphQLTypeResolver} annotation. */ public class GraphQLInterfaceTypeResolver implements TypeResolver, ApplicationContextAware { diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLMutationResolver.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLMutationResolver.java index af58a171..c62e6e33 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLMutationResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLMutationResolver.java @@ -7,7 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface GraphQLMutationResolver { - -} - +public @interface GraphQLMutationResolver {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLQueryResolver.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLQueryResolver.java index ab91cdc8..ae523344 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLQueryResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLQueryResolver.java @@ -7,6 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface GraphQLQueryResolver { - -} +public @interface GraphQLQueryResolver {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLScalarTypeFunction.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLScalarTypeFunction.java index aa55a7d8..1191fe88 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLScalarTypeFunction.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLScalarTypeFunction.java @@ -14,9 +14,7 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -/** - * Maps Java classes to the corresponding scalar definitions. - */ +/** Maps Java classes to the corresponding scalar definitions. */ @RequiredArgsConstructor @Slf4j public class GraphQLScalarTypeFunction implements TypeFunction { @@ -33,8 +31,7 @@ public GraphQLType buildType( final boolean input, final Class aClass, final AnnotatedType annotatedType, - final ProcessingElementsContainer container - ) { + final ProcessingElementsContainer container) { final GraphQLScalarType graphQLScalarType = getMatchingScalarDefinition(aClass).orElse(null); if (nonNull(graphQLScalarType)) { log.info("Registering scalar type {} for Java class {}", graphQLScalarType.getName(), aClass); @@ -43,13 +40,17 @@ public GraphQLType buildType( } private Optional getMatchingScalarDefinition(final Class aClass) { - return customScalarTypes.stream().filter(scalarType -> { - final Type[] genericInterfaces = scalarType.getCoercing().getClass().getGenericInterfaces(); - return genericInterfaces.length > 0 - && genericInterfaces[0] instanceof ParameterizedType - && ((ParameterizedType) genericInterfaces[0]).getActualTypeArguments().length > 0 - && ((ParameterizedType) genericInterfaces[0]).getActualTypeArguments()[0].equals(aClass); - }).findFirst(); + return customScalarTypes.stream() + .filter( + scalarType -> { + final Type[] genericInterfaces = + scalarType.getCoercing().getClass().getGenericInterfaces(); + return genericInterfaces.length > 0 + && genericInterfaces[0] instanceof ParameterizedType + && ((ParameterizedType) genericInterfaces[0]).getActualTypeArguments().length > 0 + && ((ParameterizedType) genericInterfaces[0]) + .getActualTypeArguments()[0].equals(aClass); + }) + .findFirst(); } - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLSubscriptionResolver.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLSubscriptionResolver.java index 83cc2919..581e2c3b 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLSubscriptionResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/main/java/graphql/kickstart/graphql/annotations/GraphQLSubscriptionResolver.java @@ -7,6 +7,4 @@ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) -public @interface GraphQLSubscriptionResolver { - -} +public @interface GraphQLSubscriptionResolver {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsBeanTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsBeanTest.java index 809f537e..bd36df68 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsBeanTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsBeanTest.java @@ -14,8 +14,7 @@ @ActiveProfiles({"test", "query-test"}) class GraphQLAnnotationsBeanTest { - @Autowired - private ApplicationContext applicationContext; + @Autowired private ApplicationContext applicationContext; @Test @DisplayName("Should expose the GraphQL Annotations bean.") diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomAnnotationProcessorTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomAnnotationProcessorTest.java index de98631a..a423a56e 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomAnnotationProcessorTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomAnnotationProcessorTest.java @@ -15,8 +15,7 @@ @ActiveProfiles({"test", "custom-annotation-processor-test"}) class GraphQLAnnotationsCustomAnnotationProcessorTest { - @SpyBean - private CustomAnnotationProcessor customAnnotationProcessor; + @SpyBean private CustomAnnotationProcessor customAnnotationProcessor; @Test @DisplayName("Assert that the custom annotation processor is used.") diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomRelayTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomRelayTest.java index e83464de..42990bb6 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomRelayTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomRelayTest.java @@ -20,14 +20,11 @@ @ActiveProfiles({"test", "custom-relay-test"}) class GraphQLAnnotationsCustomRelayTest { - @SpyBean - private CustomRelay customRelay; + @SpyBean private CustomRelay customRelay; - @Autowired - private GraphQLSchema schema; + @Autowired private GraphQLSchema schema; - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; @Test @DisplayName("Assert that custom relay is used.") diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomScalarTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomScalarTest.java index 75c52710..bcce243b 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomScalarTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomScalarTest.java @@ -17,15 +17,14 @@ @ActiveProfiles({"test", "custom-scalar-test"}) class GraphQLAnnotationsCustomScalarTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; @Test @DisplayName("Assert that custom scalars work properly.") void testQueryWithCustomScalar() throws IOException { // WHEN - final GraphQLResponse graphQLResponse - = graphQLTestTemplate.postForResource("queries/test-custom-scalar-query.graphql"); + final GraphQLResponse graphQLResponse = + graphQLTestTemplate.postForResource("queries/test-custom-scalar-query.graphql"); // THEN assertThat(graphQLResponse.get("$.data.randomUUID", UUID.class)).isNotNull(); } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomTypeFunctionTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomTypeFunctionTest.java index 3593cbea..04562a8e 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomTypeFunctionTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsCustomTypeFunctionTest.java @@ -16,15 +16,14 @@ @ActiveProfiles({"test", "custom-type-function-test"}) class GraphQLAnnotationsCustomTypeFunctionTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; @Test @DisplayName("Assert that custom type functions work properly.") void testCustomTypeFunction() throws IOException { // WHEN - final GraphQLResponse actual - = graphQLTestTemplate.postForResource("queries/test-custom-type-function.graphql"); + final GraphQLResponse actual = + graphQLTestTemplate.postForResource("queries/test-custom-type-function.graphql"); // THEN assertThat(actual.get("$.data.foo")).isEqualTo("foo"); } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsDirectiveTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsDirectiveTest.java index c605e4c9..de7f1e12 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsDirectiveTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsDirectiveTest.java @@ -16,15 +16,14 @@ @ActiveProfiles({"test", "directive-test"}) class GraphQLAnnotationsDirectiveTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; @Test @DisplayName("Assert that directives are properly registered.") void testDirectivesAreProperlyRegistered() throws IOException { // WHEN - final GraphQLResponse actual - = graphQLTestTemplate.postForResource("queries/test-directive-query.graphql"); + final GraphQLResponse actual = + graphQLTestTemplate.postForResource("queries/test-directive-query.graphql"); // THEN assertThat(actual.get("$.data.queryWithDirective")).isEqualTo("THIS SHOULD BE UPPERCASE"); } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMissingQueryResolverTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMissingQueryResolverTest.java index 84ab7e74..79ac5997 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMissingQueryResolverTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMissingQueryResolverTest.java @@ -12,7 +12,8 @@ class GraphQLAnnotationsErrorMissingQueryResolverTest { @Test - @DisplayName("Assert that MissingQueryResolverException is throw if no GraphQLQueryResolver classes are found.") + @DisplayName( + "Assert that MissingQueryResolverException is throw if no GraphQLQueryResolver classes are found.") void testMissingQueryResolverExceptionIfNoQueryResolverProvided() { // GIVEN final SpringApplication app = new SpringApplication(TestApplication.class); diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleMutationResolversTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleMutationResolversTest.java index 44fe9ff4..1f1d13e6 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleMutationResolversTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleMutationResolversTest.java @@ -12,7 +12,8 @@ class GraphQLAnnotationsMultipleMutationResolversTest { @Test - @DisplayName("Assert that MultipleMutationResolversException is thrown when multiple mutation resolvers are found.") + @DisplayName( + "Assert that MultipleMutationResolversException is thrown when multiple mutation resolvers are found.") void testMultipleMutationResolversExceptionIsThrown() { // GIVEN final SpringApplication app = new SpringApplication(TestApplication.class); diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleQueryResolversTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleQueryResolversTest.java index 03772fa9..4aa7d73d 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleQueryResolversTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleQueryResolversTest.java @@ -12,7 +12,8 @@ class GraphQLAnnotationsErrorMultipleQueryResolversTest { @Test - @DisplayName("Assert that MultipleQueryResolversException is thrown when multiple query resolvers are found.") + @DisplayName( + "Assert that MultipleQueryResolversException is thrown when multiple query resolvers are found.") void testMultipleQueryResolversExceptionIsThrown() { // GIVEN final SpringApplication app = new SpringApplication(TestApplication.class); diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleSubscriptionResolversTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleSubscriptionResolversTest.java index f82401f3..1210f978 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleSubscriptionResolversTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsErrorMultipleSubscriptionResolversTest.java @@ -12,7 +12,8 @@ class GraphQLAnnotationsErrorMultipleSubscriptionResolversTest { @Test - @DisplayName("Assert that MultipleSubscriptionResolversException is thrown when multiple subscription resolvers are found.") + @DisplayName( + "Assert that MultipleSubscriptionResolversException is thrown when multiple subscription resolvers are found.") void testMultipleSubscriptionResolversExceptionIsThrown() { // GIVEN final SpringApplication app = new SpringApplication(TestApplication.class); diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsExtendTypeTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsExtendTypeTest.java index 98768203..c096ab95 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsExtendTypeTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsExtendTypeTest.java @@ -16,15 +16,14 @@ @ActiveProfiles({"test", "extend-type-test"}) class GraphQLAnnotationsExtendTypeTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; @Test @DisplayName("Assert that extend types are properly registered.") void testExtendTypesAreProperlyRegistered() throws IOException { // WHEN - final GraphQLResponse actual = graphQLTestTemplate - .postForResource("queries/test-extend-type-query.graphql"); + final GraphQLResponse actual = + graphQLTestTemplate.postForResource("queries/test-extend-type-query.graphql"); // THEN assertThat(actual.get("$.data.someValue.baseTypeField")).isEqualTo("Test value"); assertThat(actual.get("$.data.someValue.extendTypeField")).isEqualTo("TEST VALUE"); diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationInputPrefixTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationInputPrefixTest.java index 0551ca94..e0ccdde8 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationInputPrefixTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationInputPrefixTest.java @@ -1,5 +1,7 @@ package graphql.kickstart.graphql.annotations; +import static org.assertj.core.api.Assertions.assertThat; + import graphql.schema.GraphQLSchema; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,20 +9,14 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; -import static org.assertj.core.api.Assertions.assertThat; - @DisplayName("Testing input prefix") -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "graphql.annotations.input-prefix=Prefix", - "graphql.annotations.input-suffix=" - } -) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = {"graphql.annotations.input-prefix=Prefix", "graphql.annotations.input-suffix="}) @ActiveProfiles({"test", "mutation-test"}) class GraphQLAnnotationsMutationInputPrefixTest { - @Autowired - private GraphQLSchema graphQLSchema; + @Autowired private GraphQLSchema graphQLSchema; @Test @DisplayName("Assert that input prefix is used.") diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationInputSuffixTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationInputSuffixTest.java index 104ba76e..ad27605d 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationInputSuffixTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationInputSuffixTest.java @@ -1,5 +1,7 @@ package graphql.kickstart.graphql.annotations; +import static org.assertj.core.api.Assertions.assertThat; + import graphql.schema.GraphQLSchema; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -7,20 +9,14 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; -import static org.assertj.core.api.Assertions.assertThat; - @DisplayName("Testing input suffix") -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = { - "graphql.annotations.input-prefix=", - "graphql.annotations.input-suffix=Suffix" - } -) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = {"graphql.annotations.input-prefix=", "graphql.annotations.input-suffix=Suffix"}) @ActiveProfiles({"test", "mutation-test"}) class GraphQLAnnotationsMutationInputSuffixTest { - @Autowired - private GraphQLSchema graphQLSchema; + @Autowired private GraphQLSchema graphQLSchema; @Test @DisplayName("Assert that input suffix is used.") diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationTest.java index ff7492af..65834c09 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsMutationTest.java @@ -4,8 +4,8 @@ import com.graphql.spring.boot.test.GraphQLResponse; import com.graphql.spring.boot.test.GraphQLTestTemplate; -import java.io.IOException; import graphql.schema.GraphQLSchema; +import java.io.IOException; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -17,18 +17,16 @@ @ActiveProfiles({"test", "mutation-test"}) class GraphQLAnnotationsMutationTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; - @Autowired - private GraphQLSchema graphQLSchema; + @Autowired private GraphQLSchema graphQLSchema; @Test @DisplayName("Assert that mutation resolver is properly registered.") void testMutationResolver() throws IOException { // WHEN - final GraphQLResponse actual = graphQLTestTemplate - .postForResource("mutations/test-mutation.graphql"); + final GraphQLResponse actual = + graphQLTestTemplate.postForResource("mutations/test-mutation.graphql"); // THEN assertThat(actual.get("$.data.performSomeOperation.testField")).isEqualTo("Test value"); } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyDefaultTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyDefaultTest.java index 4494b6c2..32f0dac9 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyDefaultTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyDefaultTest.java @@ -16,15 +16,14 @@ @ActiveProfiles({"test", "prettify-default-test"}) class GraphQLAnnotationsPrettifyDefaultTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; @Test @DisplayName("By default, it should always prettify fields.") void testDefaultPrettifySettings() throws IOException { // WHEN - final GraphQLResponse graphQLResponse - = graphQLTestTemplate.postForResource("queries/test-prettified-query.graphql"); + final GraphQLResponse graphQLResponse = + graphQLTestTemplate.postForResource("queries/test-prettified-query.graphql"); // THEN assertThat(graphQLResponse.get("$.data.someValue")).isEqualTo("some value"); } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyDisabledTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyDisabledTest.java index 1695c179..960a4353 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyDisabledTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyDisabledTest.java @@ -16,15 +16,14 @@ @ActiveProfiles({"test", "prettify-disabled-test"}) class GraphQLAnnotationsPrettifyDisabledTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; @Test @DisplayName("If disabled, fields should not be prettified.") void testDefaultPrettifySettings() throws IOException { // WHEN - final GraphQLResponse graphQLResponse - = graphQLTestTemplate.postForResource("queries/test-not-prettified-query.graphql"); + final GraphQLResponse graphQLResponse = + graphQLTestTemplate.postForResource("queries/test-not-prettified-query.graphql"); // THEN assertThat(graphQLResponse.get("$.data.getSomeValue")).isEqualTo("some value"); } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyEnabledTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyEnabledTest.java index 6e5765e5..50f244fb 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyEnabledTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsPrettifyEnabledTest.java @@ -16,15 +16,14 @@ @ActiveProfiles({"test", "prettify-enabled-test"}) class GraphQLAnnotationsPrettifyEnabledTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; @Test @DisplayName("If enabled, it should always prettify fields.") void testDefaultPrettifySettings() throws IOException { // WHEN - final GraphQLResponse graphQLResponse - = graphQLTestTemplate.postForResource("queries/test-prettified-query.graphql"); + final GraphQLResponse graphQLResponse = + graphQLTestTemplate.postForResource("queries/test-prettified-query.graphql"); // THEN assertThat(graphQLResponse.get("$.data.someValue")).isEqualTo("some value"); } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsQueryTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsQueryTest.java index a78c7725..e61022fb 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsQueryTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsQueryTest.java @@ -15,14 +15,14 @@ @DisplayName("Testing query resolver registration.") @ActiveProfiles({"test", "query-test"}) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = TestApplication.class) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + classes = TestApplication.class) class GraphQLAnnotationsQueryTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; @Test @DisplayName("Assert that query resolver is properly detected.") @@ -31,8 +31,8 @@ void testHelloQuery() throws IOException { final ObjectNode params = objectMapper.createObjectNode(); params.put("who", "John"); // WHEN - final GraphQLResponse graphQLResponse = graphQLTestTemplate - .perform("queries/hello.graphql", params); + final GraphQLResponse graphQLResponse = + graphQLTestTemplate.perform("queries/hello.graphql", params); // THEN assertThat(graphQLResponse.get("$.data.hello")).isEqualTo("Hello, John!"); assertThat(graphQLResponse.get("$.data.helloWorld")).isEqualTo("Hello, World!"); diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsSubscriptionTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsSubscriptionTest.java index 3801561e..3d873f3c 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsSubscriptionTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLAnnotationsSubscriptionTest.java @@ -15,16 +15,17 @@ @ActiveProfiles({"test", "subscription-test"}) class GraphQLAnnotationsSubscriptionTest { - @Autowired - private GraphQLTestSubscription graphQLTestSubscription; + @Autowired private GraphQLTestSubscription graphQLTestSubscription; @Test @DisplayName("Assert that subscription resolver is properly registered.") void testSubscription() { // GIVEN - final GraphQLResponse graphQLResponse = graphQLTestSubscription.init() - .start("subscriptions/test-subscription.graphql") - .awaitAndGetNextResponse(10000); + final GraphQLResponse graphQLResponse = + graphQLTestSubscription + .init() + .start("subscriptions/test-subscription.graphql") + .awaitAndGetNextResponse(10000); // THEN assertThat(graphQLResponse.get("$.data.testSubscription")).isEqualTo("some value"); } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceQueryIgnoreAbstractInterfaceImplementationsTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceQueryIgnoreAbstractInterfaceImplementationsTest.java index 2c24b6bf..438f66f5 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceQueryIgnoreAbstractInterfaceImplementationsTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceQueryIgnoreAbstractInterfaceImplementationsTest.java @@ -1,5 +1,7 @@ package graphql.kickstart.graphql.annotations; +import static org.assertj.core.api.Assertions.assertThat; + import com.graphql.spring.boot.test.GraphQLResponse; import com.graphql.spring.boot.test.GraphQLTestTemplate; import graphql.kickstart.graphql.annotations.test.interfaces.Car; @@ -7,58 +9,57 @@ import graphql.schema.GraphQLNamedType; import graphql.schema.GraphQLScalarType; import graphql.schema.GraphQLSchema; +import java.io.IOException; +import java.util.Set; +import java.util.stream.Collectors; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; -import java.io.IOException; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; - @DisplayName("Testing interface handling (ignore abstract implementations).") -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - properties = "graphql.annotations.ignore-abstract-interface-implementations=true") +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + properties = "graphql.annotations.ignore-abstract-interface-implementations=true") @ActiveProfiles({"test", "interface-test"}) class GraphQLInterfaceQueryIgnoreAbstractInterfaceImplementationsTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; - @Autowired - private GraphQLSchema graphQLSchema; + @Autowired private GraphQLSchema graphQLSchema; @Test @DisplayName("Assert that GraphQL interfaces and their implementations are registered correctly.") void testInterfaceQuery() throws IOException { // WHEN - final GraphQLResponse actual = graphQLTestTemplate - .postForResource("queries/test-interface-query.graphql"); + final GraphQLResponse actual = + graphQLTestTemplate.postForResource("queries/test-interface-query.graphql"); // THEN assertThat(actual.get("$.data.vehicles[0]", Car.class)) - .usingRecursiveComparison().ignoringAllOverriddenEquals() + .usingRecursiveComparison() + .ignoringAllOverriddenEquals() .isEqualTo(Car.builder().numberOfSeats(4).registrationNumber("ABC-123").build()); assertThat(actual.get("$.data.vehicles[1]", Truck.class)) - .usingRecursiveComparison().ignoringAllOverriddenEquals() + .usingRecursiveComparison() + .ignoringAllOverriddenEquals() .isEqualTo(Truck.builder().cargoWeightCapacity(12).registrationNumber("CBA-321").build()); } @Test - @DisplayName("Assert that abstract GraphQL interface implementations are excluded from the schema.") + @DisplayName( + "Assert that abstract GraphQL interface implementations are excluded from the schema.") void testInterfaceImplementationDetection() { // THEN - Set vehicleDomainTypes = graphQLSchema.getAllTypesAsList().stream() - .filter(type -> !(type instanceof GraphQLScalarType)) - .map(GraphQLNamedType::getName) - .filter(name -> !name.startsWith("__")) - .filter(name -> !"PageInfo".equals(name)) - .collect(Collectors.toSet()); + Set vehicleDomainTypes = + graphQLSchema.getAllTypesAsList().stream() + .filter(type -> !(type instanceof GraphQLScalarType)) + .map(GraphQLNamedType::getName) + .filter(name -> !name.startsWith("__")) + .filter(name -> !"PageInfo".equals(name)) + .collect(Collectors.toSet()); // Must not contain "AbstractVehicle" assertThat(vehicleDomainTypes) .containsExactlyInAnyOrder("InterfaceQuery", "Vehicle", "Car", "Truck"); } } - diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceQueryTest.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceQueryTest.java index 9ed3039b..d9c50cde 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceQueryTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/GraphQLInterfaceQueryTest.java @@ -6,12 +6,12 @@ import com.graphql.spring.boot.test.GraphQLTestTemplate; import graphql.kickstart.graphql.annotations.test.interfaces.Car; import graphql.kickstart.graphql.annotations.test.interfaces.Truck; -import java.io.IOException; -import java.util.Set; -import java.util.stream.Collectors; import graphql.schema.GraphQLNamedType; import graphql.schema.GraphQLScalarType; import graphql.schema.GraphQLSchema; +import java.io.IOException; +import java.util.Set; +import java.util.stream.Collectors; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -23,24 +23,24 @@ @ActiveProfiles({"test", "interface-test"}) class GraphQLInterfaceQueryTest { - @Autowired - private GraphQLTestTemplate graphQLTestTemplate; + @Autowired private GraphQLTestTemplate graphQLTestTemplate; - @Autowired - private GraphQLSchema graphQLSchema; + @Autowired private GraphQLSchema graphQLSchema; @Test @DisplayName("Assert that GraphQL interfaces and their implementations are registered correctly.") void testInterfaceQuery() throws IOException { // WHEN - final GraphQLResponse actual = graphQLTestTemplate - .postForResource("queries/test-interface-query.graphql"); + final GraphQLResponse actual = + graphQLTestTemplate.postForResource("queries/test-interface-query.graphql"); // THEN assertThat(actual.get("$.data.vehicles[0]", Car.class)) - .usingRecursiveComparison().ignoringAllOverriddenEquals() + .usingRecursiveComparison() + .ignoringAllOverriddenEquals() .isEqualTo(Car.builder().numberOfSeats(4).registrationNumber("ABC-123").build()); assertThat(actual.get("$.data.vehicles[1]", Truck.class)) - .usingRecursiveComparison().ignoringAllOverriddenEquals() + .usingRecursiveComparison() + .ignoringAllOverriddenEquals() .isEqualTo(Truck.builder().cargoWeightCapacity(12).registrationNumber("CBA-321").build()); } @@ -48,15 +48,15 @@ void testInterfaceQuery() throws IOException { @DisplayName("Assert that abstract GraphQL interface implementations are added to the schema.") void testInterfaceImplementationDetection() { // THEN - Set vehicleDomainTypes = graphQLSchema.getAllTypesAsList().stream() - .filter(type -> !(type instanceof GraphQLScalarType)) - .map(GraphQLNamedType::getName) - .filter(name -> !name.startsWith("__")) - .filter(name -> !"PageInfo".equals(name)) - .collect(Collectors.toSet()); + Set vehicleDomainTypes = + graphQLSchema.getAllTypesAsList().stream() + .filter(type -> !(type instanceof GraphQLScalarType)) + .map(GraphQLNamedType::getName) + .filter(name -> !name.startsWith("__")) + .filter(name -> !"PageInfo".equals(name)) + .collect(Collectors.toSet()); // Should contain "AbstractVehicle" assertThat(vehicleDomainTypes) .containsExactlyInAnyOrder("InterfaceQuery", "Vehicle", "AbstractVehicle", "Car", "Truck"); } } - diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/TestApplication.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/TestApplication.java index 5e419a4b..21b0880c 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/TestApplication.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/TestApplication.java @@ -9,5 +9,4 @@ public class TestApplication { public static void main(final String[] args) { SpringApplication.run(TestApplication.class, args); } - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/annotation/processor/CustomAnnotationProcessor.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/annotation/processor/CustomAnnotationProcessor.java index 5c43a70e..fd5bfb4d 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/annotation/processor/CustomAnnotationProcessor.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/annotation/processor/CustomAnnotationProcessor.java @@ -11,10 +11,10 @@ @Service public class CustomAnnotationProcessor extends GraphQLAnnotations { - public CustomAnnotationProcessor() { - } + public CustomAnnotationProcessor() {} - public CustomAnnotationProcessor(TypeFunction defaultTypeFunction, + public CustomAnnotationProcessor( + TypeFunction defaultTypeFunction, GraphQLObjectHandler graphQLObjectHandler, GraphQLExtensionsHandler graphQLExtensionsHandler) { super(defaultTypeFunction, graphQLObjectHandler, graphQLExtensionsHandler); diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/CustomRelay.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/CustomRelay.java index babc2db8..aa0d0308 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/CustomRelay.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/CustomRelay.java @@ -6,6 +6,4 @@ @Service @Profile("custom-relay-test") -public class CustomRelay extends Relay { - -} +public class CustomRelay extends Relay {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/TestModel.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/TestModel.java index b3b5d63a..87f81df0 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/TestModel.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/TestModel.java @@ -6,6 +6,5 @@ @Value public class TestModel { - @GraphQLField - String someField; + @GraphQLField String someField; } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/TestQuery.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/TestQuery.java index 4f2918f9..76064647 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/TestQuery.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/relay/TestQuery.java @@ -13,8 +13,8 @@ public class TestQuery { @GraphQLField @GraphQLConnection public static PaginatedData somePaginatedValue() { - return new AbstractPaginatedData(false, false, - Collections.singletonList(new TestModel("some value"))) { + return new AbstractPaginatedData( + false, false, Collections.singletonList(new TestModel("some value"))) { @Override public String getCursor(final TestModel entity) { return "test cursor"; diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/type/function/Foo.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/type/function/Foo.java index c976df7f..aa1ad29c 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/type/function/Foo.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/type/function/Foo.java @@ -1,5 +1,3 @@ package graphql.kickstart.graphql.annotations.test.custom.type.function; -public class Foo { - -} +public class Foo {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/type/function/FooTypeFunction.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/type/function/FooTypeFunction.java index 36e63fbb..01e1af2c 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/type/function/FooTypeFunction.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/custom/type/function/FooTypeFunction.java @@ -23,30 +23,31 @@ public boolean canBuildType(final Class aClass, final AnnotatedType annotated } @Override - public GraphQLType buildType(boolean input, + public GraphQLType buildType( + boolean input, final Class aClass, final AnnotatedType annotatedType, - final ProcessingElementsContainer container - ) { + final ProcessingElementsContainer container) { return newScalar() .name("Foo") - .coercing(new Coercing() { - @Override - public String serialize(final Object dataFetcherResult) - throws CoercingSerializeException { - return "foo"; - } + .coercing( + new Coercing() { + @Override + public String serialize(final Object dataFetcherResult) + throws CoercingSerializeException { + return "foo"; + } - @Override - public Foo parseValue(final Object input) throws CoercingParseValueException { - return new Foo(); - } + @Override + public Foo parseValue(final Object input) throws CoercingParseValueException { + return new Foo(); + } - @Override - public Foo parseLiteral(final Object input) throws CoercingParseLiteralException { - return new Foo(); - } - }) + @Override + public Foo parseLiteral(final Object input) throws CoercingParseLiteralException { + return new Foo(); + } + }) .build(); } } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/directive/UpperCaseDirective.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/directive/UpperCaseDirective.java index d79a4a76..9e1d9906 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/directive/UpperCaseDirective.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/directive/UpperCaseDirective.java @@ -13,6 +13,4 @@ @GraphQLDirectiveDefinition(wiring = UpperCaseDirectiveWiring.class) @DirectiveLocations({Introspection.DirectiveLocation.FIELD_DEFINITION}) @Retention(RetentionPolicy.RUNTIME) -public @interface UpperCaseDirective { - -} +public @interface UpperCaseDirective {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/directive/UpperCaseDirectiveWiring.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/directive/UpperCaseDirectiveWiring.java index 7a17aaf8..51ed5dca 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/directive/UpperCaseDirectiveWiring.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/directive/UpperCaseDirectiveWiring.java @@ -12,12 +12,15 @@ public class UpperCaseDirectiveWiring implements AnnotationsDirectiveWiring { @Override public GraphQLFieldDefinition onField(final AnnotationsWiringEnvironment environment) { final GraphQLFieldDefinition field = (GraphQLFieldDefinition) environment.getElement(); - CodeRegistryUtil.wrapDataFetcher(field, environment, (((dataFetchingEnvironment, value) -> { - if (value instanceof String) { - return ((String) value).toUpperCase(); - } - return value; - }))); + CodeRegistryUtil.wrapDataFetcher( + field, + environment, + (((dataFetchingEnvironment, value) -> { + if (value instanceof String) { + return ((String) value).toUpperCase(); + } + return value; + }))); return field; } } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/FirstMutationResolver.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/FirstMutationResolver.java index b439093f..660855da 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/FirstMutationResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/FirstMutationResolver.java @@ -3,6 +3,4 @@ import graphql.kickstart.graphql.annotations.GraphQLMutationResolver; @GraphQLMutationResolver -public class FirstMutationResolver { - -} +public class FirstMutationResolver {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/SecondMutationResolver.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/SecondMutationResolver.java index 3681dc56..4d28e83f 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/SecondMutationResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/SecondMutationResolver.java @@ -3,6 +3,4 @@ import graphql.kickstart.graphql.annotations.GraphQLMutationResolver; @GraphQLMutationResolver -public class SecondMutationResolver { - -} +public class SecondMutationResolver {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/TestQuery.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/TestQuery.java index a0c595b2..a1d96e34 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/TestQuery.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/mutation/TestQuery.java @@ -3,6 +3,4 @@ import graphql.kickstart.graphql.annotations.GraphQLQueryResolver; @GraphQLQueryResolver -public class TestQuery { - -} +public class TestQuery {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/query/FirstQueryResolver.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/query/FirstQueryResolver.java index 2825537a..5baecfe8 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/query/FirstQueryResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/query/FirstQueryResolver.java @@ -3,6 +3,4 @@ import graphql.kickstart.graphql.annotations.GraphQLQueryResolver; @GraphQLQueryResolver -public class FirstQueryResolver { - -} +public class FirstQueryResolver {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/query/SecondQueryResolver.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/query/SecondQueryResolver.java index dd1ca894..803fc543 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/query/SecondQueryResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/query/SecondQueryResolver.java @@ -3,6 +3,4 @@ import graphql.kickstart.graphql.annotations.GraphQLQueryResolver; @GraphQLQueryResolver -public class SecondQueryResolver { - -} +public class SecondQueryResolver {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/FirstSubscriptionResolver.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/FirstSubscriptionResolver.java index ff734308..a72d6934 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/FirstSubscriptionResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/FirstSubscriptionResolver.java @@ -3,6 +3,4 @@ import graphql.kickstart.graphql.annotations.GraphQLSubscriptionResolver; @GraphQLSubscriptionResolver -public class FirstSubscriptionResolver { - -} +public class FirstSubscriptionResolver {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/SecondSubscriptionResolver.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/SecondSubscriptionResolver.java index a950dc3d..2c8431c5 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/SecondSubscriptionResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/SecondSubscriptionResolver.java @@ -3,6 +3,4 @@ import graphql.kickstart.graphql.annotations.GraphQLSubscriptionResolver; @GraphQLSubscriptionResolver -public class SecondSubscriptionResolver { - -} +public class SecondSubscriptionResolver {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/TestQuery.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/TestQuery.java index 76df4012..ef9c74ed 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/TestQuery.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/error/multiple/subscription/TestQuery.java @@ -3,6 +3,4 @@ import graphql.kickstart.graphql.annotations.GraphQLQueryResolver; @GraphQLQueryResolver -public class TestQuery { - -} +public class TestQuery {} diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/extend/type/model/BaseType.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/extend/type/model/BaseType.java index 1f2efd61..af43b677 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/extend/type/model/BaseType.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/extend/type/model/BaseType.java @@ -8,6 +8,5 @@ @AllArgsConstructor public class BaseType { - @GraphQLField - private String baseTypeField; + @GraphQLField private String baseTypeField; } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/AbstractVehicle.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/AbstractVehicle.java index dad3a501..2bb35814 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/AbstractVehicle.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/AbstractVehicle.java @@ -13,10 +13,6 @@ @NoArgsConstructor public abstract class AbstractVehicle implements Vehicle { - /** - * Note that you have to repeat the annotations from the interface method! - */ - @GraphQLField - @GraphQLNonNull - private String registrationNumber; + /** Note that you have to repeat the annotations from the interface method! */ + @GraphQLField @GraphQLNonNull private String registrationNumber; } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/Car.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/Car.java index 5c836a5c..7b283d99 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/Car.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/Car.java @@ -17,9 +17,7 @@ // because otherwise GraphQL-Java Annotations would not find this class. public class Car extends AbstractVehicle implements Vehicle { - @GraphQLField - @GraphQLNonNull - private int numberOfSeats; + @GraphQLField @GraphQLNonNull private int numberOfSeats; public Car(String registrationNumber, int numberOfSeats) { super(registrationNumber); diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/Truck.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/Truck.java index f1f7fbf8..72d5de32 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/Truck.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/interfaces/Truck.java @@ -15,14 +15,8 @@ // hierarchy free from abstract classes. public class Truck implements Vehicle { - /** - * Note that you have to repeat the annotations from the interface method! - */ - @GraphQLField - @GraphQLNonNull - private String registrationNumber; + /** Note that you have to repeat the annotations from the interface method! */ + @GraphQLField @GraphQLNonNull private String registrationNumber; - @GraphQLField - @GraphQLNonNull - private int cargoWeightCapacity; + @GraphQLField @GraphQLNonNull private int cargoWeightCapacity; } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/mutation/model/TestModel.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/mutation/model/TestModel.java index 4f100ab9..cc8ea8aa 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/mutation/model/TestModel.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/mutation/model/TestModel.java @@ -12,6 +12,5 @@ @NoArgsConstructor public class TestModel { - @GraphQLField - private String testField; + @GraphQLField private String testField; } diff --git a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/scalar/CustomScalarConfig.java b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/scalar/CustomScalarConfig.java index 384d5ecc..206e22c3 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/scalar/CustomScalarConfig.java +++ b/graphql-kickstart-spring-boot-autoconfigure-graphql-annotations/src/test/java/graphql/kickstart/graphql/annotations/test/scalar/CustomScalarConfig.java @@ -24,30 +24,31 @@ public GraphQLScalarType uuidScalar() { return newScalar() .name("UUID") .description("Standard UUID") - .coercing(new Coercing() { - @Override - public String serialize(Object dataFetcherResult) throws CoercingSerializeException { - return String.valueOf(dataFetcherResult); - } + .coercing( + new Coercing() { + @Override + public String serialize(Object dataFetcherResult) throws CoercingSerializeException { + return String.valueOf(dataFetcherResult); + } - @Override - public UUID parseValue(Object input) throws CoercingParseValueException { - try { - return UUID.fromString(String.valueOf(input)); - } catch (IllegalArgumentException e) { - throw new CoercingParseValueException(e); - } - } + @Override + public UUID parseValue(Object input) throws CoercingParseValueException { + try { + return UUID.fromString(String.valueOf(input)); + } catch (IllegalArgumentException e) { + throw new CoercingParseValueException(e); + } + } - @Override - public UUID parseLiteral(Object input) throws CoercingParseLiteralException { - try { - return UUID.fromString(((StringValue) input).getValue()); - } catch (IllegalArgumentException e) { - throw new CoercingParseLiteralException(e); - } - } - }) + @Override + public UUID parseLiteral(Object input) throws CoercingParseLiteralException { + try { + return UUID.fromString(((StringValue) input).getValue()); + } catch (IllegalArgumentException e) { + throw new CoercingParseLiteralException(e); + } + } + }) .build(); } } diff --git a/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/ClasspathResourceSchemaStringProvider.java b/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/ClasspathResourceSchemaStringProvider.java index 9d1bcf54..a1b27a51 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/ClasspathResourceSchemaStringProvider.java +++ b/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/ClasspathResourceSchemaStringProvider.java @@ -16,8 +16,7 @@ public class ClasspathResourceSchemaStringProvider implements SchemaStringProvider { - @Autowired - private ApplicationContext applicationContext; + @Autowired private ApplicationContext applicationContext; private String schemaLocationPattern; public ClasspathResourceSchemaStringProvider(String schemaLocationPattern) { @@ -34,22 +33,17 @@ public List schemaStrings() throws IOException { + "'. Please add a graphql schema to the classpath or add a SchemaParser bean to your application context."); } - return Arrays.stream(resources) - .map(this::readSchema) - .collect(Collectors.toList()); + return Arrays.stream(resources).map(this::readSchema).collect(Collectors.toList()); } private String readSchema(Resource resource) { - try ( - InputStream inputStream = resource.getInputStream(); - InputStreamReader bufferedInputStream = new InputStreamReader(inputStream, - StandardCharsets.UTF_8.name()); - BufferedReader reader = new BufferedReader(bufferedInputStream) - ) { + try (InputStream inputStream = resource.getInputStream(); + InputStreamReader bufferedInputStream = + new InputStreamReader(inputStream, StandardCharsets.UTF_8.name()); + BufferedReader reader = new BufferedReader(bufferedInputStream)) { return reader.lines().collect(joining("\n")); } catch (IOException e) { throw new IllegalStateException("Cannot read graphql schema from resource " + resource, e); } } - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/GraphQLJavaToolsAutoConfiguration.java b/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/GraphQLJavaToolsAutoConfiguration.java index 43eb34f6..1367e978 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/GraphQLJavaToolsAutoConfiguration.java +++ b/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/GraphQLJavaToolsAutoConfiguration.java @@ -38,9 +38,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ @Slf4j @Configuration @ConditionalOnClass(SchemaParser.class) @@ -64,8 +62,7 @@ public SchemaParserOptions.Builder optionsBuilder( @Autowired(required = false) List proxyHandlers, @Autowired(required = false) CoroutineContextProvider coroutineContextProvider, @Autowired(required = false) List typeDefinitionFactories, - @Autowired(required = false) GraphqlFieldVisibility fieldVisibility - ) { + @Autowired(required = false) GraphqlFieldVisibility fieldVisibility) { SchemaParserOptions.Builder optionsBuilder = SchemaParserOptions.newOptions(); if (perFieldObjectMapperProvider != null) { @@ -102,8 +99,8 @@ public SchemaParser schemaParser( @Autowired(required = false) SchemaParserDictionary dictionary, @Autowired(required = false) GraphQLScalarType[] scalars, @Autowired(required = false) List directives, - @Autowired(required = false) List directiveWirings - ) throws IOException { + @Autowired(required = false) List directiveWirings) + throws IOException { SchemaParserBuilder builder = new SchemaParserBuilder(); if (nonNull(dictionary)) { builder.dictionary(dictionary.getDictionary()); @@ -125,18 +122,17 @@ public SchemaParser schemaParser( directiveWirings.forEach(builder::directiveWiring); } - return builder - .resolvers(resolvers) - .build(); + return builder.resolvers(resolvers).build(); } @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(value = "graphql.tools.use-default-objectmapper", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty( + value = "graphql.tools.use-default-objectmapper", + havingValue = "true", + matchIfMissing = true) public PerFieldObjectMapperProvider perFieldObjectMapperProvider(ObjectMapper objectMapper) { - objectMapper - .registerModule(new Jdk8Module()) - .registerModule(new KotlinModule()); + objectMapper.registerModule(new Jdk8Module()).registerModule(new KotlinModule()); return fieldDefinition -> objectMapper; } @@ -150,8 +146,9 @@ public GraphQLSchema graphQLSchema(SchemaParser schemaParser) { @Bean @ConditionalOnProperty(value = "graphql.tools.introspection-enabled", havingValue = "false") GraphqlFieldVisibility disableIntrospection() { - log.warn("GraphQL introspection query disabled! This puts your server in contravention of the " - + "GraphQL specification and expectations of most clients, so use this option with caution"); + log.warn( + "GraphQL introspection query disabled! This puts your server in contravention of the " + + "GraphQL specification and expectations of most clients, so use this option with caution"); return new NoIntrospectionGraphqlFieldVisibility(); } } diff --git a/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/GraphQLToolsProperties.java b/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/GraphQLToolsProperties.java index d47ee0c4..f61b6ade 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/GraphQLToolsProperties.java +++ b/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/GraphQLToolsProperties.java @@ -13,6 +13,6 @@ class GraphQLToolsProperties { * the GraphQL specification and expectations of most clients, so use this option with caution */ private boolean introspectionEnabled = true; - private boolean useDefaultObjectmapper = true; + private boolean useDefaultObjectmapper = true; } diff --git a/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/SchemaDirective.java b/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/SchemaDirective.java index 914a591e..ee3ead34 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/SchemaDirective.java +++ b/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/SchemaDirective.java @@ -19,5 +19,4 @@ public String getName() { public SchemaDirectiveWiring getDirective() { return directive; } - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/SchemaStringProvider.java b/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/SchemaStringProvider.java index f609a4c7..2d1b16ef 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/SchemaStringProvider.java +++ b/graphql-kickstart-spring-boot-autoconfigure-tools/src/main/java/graphql/kickstart/tools/boot/SchemaStringProvider.java @@ -6,5 +6,4 @@ public interface SchemaStringProvider { List schemaStrings() throws IOException; - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/AbstractAutoConfigurationTest.java b/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/AbstractAutoConfigurationTest.java index f26281ef..5c8ec70e 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/AbstractAutoConfigurationTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/AbstractAutoConfigurationTest.java @@ -13,9 +13,7 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ public abstract class AbstractAutoConfigurationTest { private final Class contextClass; @@ -27,8 +25,8 @@ protected AbstractAutoConfigurationTest(Class autoConfiguration) { this(AnnotationConfigApplicationContext.class, autoConfiguration); } - protected AbstractAutoConfigurationTest(Class contextClass, - Class autoConfiguration) { + protected AbstractAutoConfigurationTest( + Class contextClass, Class autoConfiguration) { assert AnnotationConfigRegistry.class.isAssignableFrom(contextClass); this.contextClass = contextClass; this.autoConfiguration = autoConfiguration; diff --git a/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/ClasspathResourceSchemaStringProviderTest.java b/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/ClasspathResourceSchemaStringProviderTest.java index 5edd9a32..6b7043a4 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/ClasspathResourceSchemaStringProviderTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/ClasspathResourceSchemaStringProviderTest.java @@ -29,8 +29,8 @@ public void clear() { @Test void schemaStrings() throws IOException { load(BaseConfiguration.class); - ClasspathResourceSchemaStringProvider schemaStringProvider = getContext() - .getBean(ClasspathResourceSchemaStringProvider.class); + ClasspathResourceSchemaStringProvider schemaStringProvider = + getContext().getBean(ClasspathResourceSchemaStringProvider.class); List schemaStrings = schemaStringProvider.schemaStrings(); assertThat(schemaStrings).hasSize(1); @@ -46,6 +46,5 @@ String schemaLocationTest(String id) { return id; } } - } } diff --git a/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/GraphQLJavaToolsAutoConfigurationTest.java b/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/GraphQLJavaToolsAutoConfigurationTest.java index 4bd8afa7..c24d1126 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/GraphQLJavaToolsAutoConfigurationTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/GraphQLJavaToolsAutoConfigurationTest.java @@ -9,9 +9,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ class GraphQLJavaToolsAutoConfigurationTest extends AbstractAutoConfigurationTest { public GraphQLJavaToolsAutoConfigurationTest() { @@ -47,15 +45,16 @@ static class InterfaceConfiguration { @Bean public SchemaStringProvider schemaStringProvider() { ListSchemaStringProvider schemaStringProvider = new ListSchemaStringProvider(); - schemaStringProvider.add("type Query {" - + " theInterface:Interface!" - + "} " - + "interface Interface {" - + " method:String!" - + "}" - + "type Implementation implements Interface {" - + " method:String!" - + "}"); + schemaStringProvider.add( + "type Query {" + + " theInterface:Interface!" + + "} " + + "interface Interface {" + + " method:String!" + + "}" + + "type Implementation implements Interface {" + + " method:String!" + + "}"); return schemaStringProvider; } @@ -92,6 +91,4 @@ public String method() { } } } - - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/GraphQLToolsDirectiveTest.java b/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/GraphQLToolsDirectiveTest.java index 3af35cd6..b5e7b3e5 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/GraphQLToolsDirectiveTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/GraphQLToolsDirectiveTest.java @@ -26,8 +26,8 @@ public void clear() { @Test void directiveIsLoaded() { - System.setProperty("graphql.tools.schemaLocationPattern", - "graphql/schema-directive-test.graphql"); + System.setProperty( + "graphql.tools.schemaLocationPattern", "graphql/schema-directive-test.graphql"); load(BaseConfiguration.class); assertThat(this.getContext().getBean(GraphQLSchema.class)).isNotNull(); } @@ -37,13 +37,15 @@ static class BaseConfiguration { @Bean public SchemaDirective uppercaseDirective() { - return new SchemaDirective("uppercase", new SchemaDirectiveWiring() { - @Override - public GraphQLObjectType onObject( - SchemaDirectiveWiringEnvironment environment) { - return null; - } - }); + return new SchemaDirective( + "uppercase", + new SchemaDirectiveWiring() { + @Override + public GraphQLObjectType onObject( + SchemaDirectiveWiringEnvironment environment) { + return null; + } + }); } @Component diff --git a/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/Query.java b/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/Query.java index 0038a9d1..39292148 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/Query.java +++ b/graphql-kickstart-spring-boot-autoconfigure-tools/src/test/java/graphql/kickstart/tools/boot/Query.java @@ -3,9 +3,7 @@ import graphql.kickstart.tools.GraphQLQueryResolver; import org.springframework.stereotype.Component; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ @Component public class Query implements GraphQLQueryResolver { diff --git a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/main/java/graphql/kickstart/spring/webflux/boot/GraphQLSpringWebfluxAutoConfiguration.java b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/main/java/graphql/kickstart/spring/webflux/boot/GraphQLSpringWebfluxAutoConfiguration.java index f1e71c11..592f341b 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/main/java/graphql/kickstart/spring/webflux/boot/GraphQLSpringWebfluxAutoConfiguration.java +++ b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/main/java/graphql/kickstart/spring/webflux/boot/GraphQLSpringWebfluxAutoConfiguration.java @@ -72,8 +72,8 @@ public GraphQLErrorStartupListener graphQLErrorStartupListener( @Bean @ConditionalOnMissingBean - public GraphQLObjectMapper graphQLObjectMapper(ObjectProvider provider, - ErrorHandlerSupplier errorHandlerSupplier) { + public GraphQLObjectMapper graphQLObjectMapper( + ObjectProvider provider, ErrorHandlerSupplier errorHandlerSupplier) { GraphQLObjectMapper.Builder builder = newBuilder(); builder.withGraphQLErrorHandler(errorHandlerSupplier); provider.ifAvailable(builder::withObjectMapperProvider); @@ -103,10 +103,9 @@ public GraphQLSchemaProvider graphQLSchemaProvider(GraphQLSchema schema) { public GraphQLSpringWebfluxInvocationInputFactory graphQLSpringInvocationInputFactory( GraphQLSchemaProvider graphQLSchemaProvider, @Autowired(required = false) GraphQLSpringWebfluxContextBuilder contextBuilder, - @Autowired(required = false) GraphQLSpringWebfluxRootObjectBuilder rootObjectBuilder - ) { - return new GraphQLSpringWebfluxInvocationInputFactory(graphQLSchemaProvider, contextBuilder, - rootObjectBuilder); + @Autowired(required = false) GraphQLSpringWebfluxRootObjectBuilder rootObjectBuilder) { + return new GraphQLSpringWebfluxInvocationInputFactory( + graphQLSchemaProvider, contextBuilder, rootObjectBuilder); } @Bean @@ -118,14 +117,15 @@ public GraphQLBuilder graphQLBuilder() { @Bean @ConditionalOnMissingBean public BatchedDataLoaderGraphQLBuilder batchedDataLoaderGraphQLBuilder( - @Autowired(required = false) Supplier optionsSupplier - ) { + @Autowired(required = false) + Supplier optionsSupplier) { return new BatchedDataLoaderGraphQLBuilder(optionsSupplier); } @Bean @ConditionalOnMissingBean - public GraphQLInvoker graphQLInvoker(GraphQLBuilder graphQLBuilder, + public GraphQLInvoker graphQLInvoker( + GraphQLBuilder graphQLBuilder, BatchedDataLoaderGraphQLBuilder batchedDataLoaderGraphQLBuilder) { return new GraphQLInvoker(graphQLBuilder, batchedDataLoaderGraphQLBuilder); } @@ -136,8 +136,8 @@ public ReactiveSubscriptionsProtocolFactory subscriptionProtocolFactory( GraphQLObjectMapper graphQLObjectMapper, GraphQLSubscriptionInvocationInputFactory invocationInputFactory, GraphQLInvoker graphQLInvoker, - @Autowired(required = false) Collection connectionListeners - ) { + @Autowired(required = false) + Collection connectionListeners) { Set listeners = new HashSet<>(); if (connectionListeners != null) { listeners.addAll(connectionListeners); @@ -146,11 +146,7 @@ public ReactiveSubscriptionsProtocolFactory subscriptionProtocolFactory( listeners.add(new KeepAliveSubscriptionConnectionListener()); } return new ReactiveApolloSubscriptionProtocolFactory( - graphQLObjectMapper, - invocationInputFactory, - graphQLInvoker, - listeners - ); + graphQLObjectMapper, invocationInputFactory, graphQLInvoker, listeners); } @Bean @@ -171,5 +167,4 @@ public HandlerMapping webSocketHandlerMapping( WebSocketHandlerAdapter webSocketHandlerAdapter() { return new WebSocketHandlerAdapter(); } - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/main/java/graphql/kickstart/spring/webflux/boot/MonoAutoConfiguration.java b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/main/java/graphql/kickstart/spring/webflux/boot/MonoAutoConfiguration.java index 11a89c18..953c13c4 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/main/java/graphql/kickstart/spring/webflux/boot/MonoAutoConfiguration.java +++ b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/main/java/graphql/kickstart/spring/webflux/boot/MonoAutoConfiguration.java @@ -23,19 +23,13 @@ public class MonoAutoConfiguration { @Bean GenericWrapper monoWrapper(@Autowired(required = false) List genericWrappers) { if (notWrapsMono(genericWrappers)) { - return GenericWrapper.withTransformer( - Mono.class, - 0, - Mono::toFuture, - t -> t - ); + return GenericWrapper.withTransformer(Mono.class, 0, Mono::toFuture, t -> t); } return null; } private boolean notWrapsMono(List genericWrappers) { - return genericWrappers == null || - genericWrappers.stream().noneMatch(it -> it.getType().isAssignableFrom(Mono.class)); + return genericWrappers == null + || genericWrappers.stream().noneMatch(it -> it.getType().isAssignableFrom(Mono.class)); } - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/HelloQuery.java b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/HelloQuery.java index e93efcd9..74bfad8c 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/HelloQuery.java +++ b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/HelloQuery.java @@ -10,5 +10,4 @@ class HelloQuery implements GraphQLQueryResolver { public Mono hello() { return Mono.just("Hello world"); } - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MonoAutoConfigurationTest.java b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MonoAutoConfigurationTest.java index e3604074..38aa8129 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MonoAutoConfigurationTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MonoAutoConfigurationTest.java @@ -20,20 +20,20 @@ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class MonoAutoConfigurationTest { - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; @Test void monoWrapper() throws JSONException { - val result = webTestClient.post() - .uri("/graphql") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue("{ \"query\": \"query { hello } \"}") - .exchange() - .returnResult(String.class); + val result = + webTestClient + .post() + .uri("/graphql") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue("{ \"query\": \"query { hello } \"}") + .exchange() + .returnResult(String.class); val response = result.getResponseBody().blockFirst(); val json = new JSONObject(response); assertThat(json.getJSONObject("data").get("hello")).isEqualTo("Hello world"); } - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MonoGenericWrapperAlreadyDefinedTest.java b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MonoGenericWrapperAlreadyDefinedTest.java index e497b4a4..afb898e9 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MonoGenericWrapperAlreadyDefinedTest.java +++ b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MonoGenericWrapperAlreadyDefinedTest.java @@ -24,17 +24,18 @@ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class MonoGenericWrapperAlreadyDefinedTest { - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; @Test void monoWrapper() throws JSONException { - val result = webTestClient.post() - .uri("/graphql") - .contentType(MediaType.APPLICATION_JSON) - .bodyValue("{ \"query\": \"query { hello } \"}") - .exchange() - .returnResult(String.class); + val result = + webTestClient + .post() + .uri("/graphql") + .contentType(MediaType.APPLICATION_JSON) + .bodyValue("{ \"query\": \"query { hello } \"}") + .exchange() + .returnResult(String.class); val response = result.getResponseBody().blockFirst(); val json = new JSONObject(response); assertThat(json.getJSONObject("data").get("hello")).isEqualTo("Hello world"); @@ -44,13 +45,7 @@ void monoWrapper() throws JSONException { static class MonoConfiguration { @Bean GenericWrapper genericWrapper() { - return GenericWrapper.withTransformer( - Mono.class, - 0, - Mono::toFuture, - t -> t - ); + return GenericWrapper.withTransformer(Mono.class, 0, Mono::toFuture, t -> t); } } - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MySubscriptionResolver.java b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MySubscriptionResolver.java index 70e4995f..bce88263 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MySubscriptionResolver.java +++ b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/MySubscriptionResolver.java @@ -13,5 +13,4 @@ class MySubscriptionResolver implements GraphQLSubscriptionResolver { Publisher hello(DataFetchingEnvironment env) { return Flux.range(0, 100).delayElements(Duration.ofSeconds(1)); } - } diff --git a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/WebfluxApplication.java b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/WebfluxApplication.java index a53983f2..5b731dd7 100644 --- a/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/WebfluxApplication.java +++ b/graphql-kickstart-spring-boot-autoconfigure-webflux/src/test/java/graphql/kickstart/spring/webflux/boot/WebfluxApplication.java @@ -9,5 +9,4 @@ public class WebfluxApplication { public static void main(String[] args) { SpringApplication.run(WebfluxApplication.class, args); } - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/AbstractGraphQLController.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/AbstractGraphQLController.java index aeaec083..1d3c14b8 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/AbstractGraphQLController.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/AbstractGraphQLController.java @@ -24,15 +24,18 @@ public abstract class AbstractGraphQLController { private final GraphQLObjectMapper objectMapper; - @PostMapping(value = "${graphql.url:graphql}", - consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + @PostMapping( + value = "${graphql.url:graphql}", + consumes = MediaType.ALL_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) public Object graphqlPOST( @RequestHeader(HttpHeaders.CONTENT_TYPE) final MediaType contentType, @Nullable @RequestParam(value = "query", required = false) String query, @Nullable @RequestParam(value = "operationName", required = false) String operationName, @Nullable @RequestParam(value = "variables", required = false) String variablesJson, @Nullable @RequestBody(required = false) String body, - ServerWebExchange serverWebExchange) throws IOException { + ServerWebExchange serverWebExchange) + throws IOException { body = Optional.ofNullable(body).orElse(""); @@ -41,7 +44,10 @@ public Object graphqlPOST( if (request.getQuery() == null) { request.setQuery(""); } - return executeRequest(request.getQuery(), request.getOperationName(), request.getVariables(), + return executeRequest( + request.getQuery(), + request.getOperationName(), + request.getVariables(), serverWebExchange); } @@ -51,20 +57,20 @@ public Object graphqlPOST( // it should be parsed and handled in the same way as the HTTP GET case. if (query != null) { - return executeRequest(query, operationName, convertVariablesJson(variablesJson), - serverWebExchange); + return executeRequest( + query, operationName, convertVariablesJson(variablesJson), serverWebExchange); } // * If the "application/graphql" Content-Type header is present, // treat the HTTP POST body contents as the GraphQL query string. - if ("application/graphql".equals(contentType.toString()) || "application/graphql; charset=utf-8" - .equals(contentType.toString())) { + if ("application/graphql".equals(contentType.toString()) + || "application/graphql; charset=utf-8".equals(contentType.toString())) { return executeRequest(body, null, Collections.emptyMap(), serverWebExchange); } - throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, - "Could not process GraphQL request"); + throw new ResponseStatusException( + HttpStatus.UNPROCESSABLE_ENTITY, "Could not process GraphQL request"); } @GetMapping(value = "${graphql.url:graphql}", produces = MediaType.APPLICATION_JSON_VALUE) @@ -74,12 +80,13 @@ public Object graphqlGET( @Nullable @RequestParam(value = "variables", required = false) String variablesJson, ServerWebExchange serverWebExchange) { - return executeRequest(query, operationName, convertVariablesJson(variablesJson), - serverWebExchange); + return executeRequest( + query, operationName, convertVariablesJson(variablesJson), serverWebExchange); } private Map convertVariablesJson(String jsonMap) { - return Optional.ofNullable(jsonMap).map(objectMapper::deserializeVariables) + return Optional.ofNullable(jsonMap) + .map(objectMapper::deserializeVariables) .orElseGet(Collections::emptyMap); } @@ -87,7 +94,5 @@ protected abstract Object executeRequest( String query, String operationName, Map variables, - ServerWebExchange serverWebExchange - ); - + ServerWebExchange serverWebExchange); } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/DefaultGraphQLSpringInvocationInputFactory.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/DefaultGraphQLSpringInvocationInputFactory.java index ce9fe1ae..6ff7870d 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/DefaultGraphQLSpringInvocationInputFactory.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/DefaultGraphQLSpringInvocationInputFactory.java @@ -12,18 +12,19 @@ import org.springframework.web.server.ServerWebExchange; @Getter(AccessLevel.PROTECTED) -public class DefaultGraphQLSpringInvocationInputFactory implements - GraphQLSpringInvocationInputFactory { +public class DefaultGraphQLSpringInvocationInputFactory + implements GraphQLSpringInvocationInputFactory { private final Supplier schemaProviderSupplier; - private Supplier contextBuilderSupplier = () -> (GraphQLSpringServerWebExchangeContext::new); - private Supplier rootObjectBuilderSupplier = () -> (serverWebExchange -> new Object()); + private Supplier contextBuilderSupplier = + () -> (GraphQLSpringServerWebExchangeContext::new); + private Supplier rootObjectBuilderSupplier = + () -> (serverWebExchange -> new Object()); public DefaultGraphQLSpringInvocationInputFactory( GraphQLSchemaProvider schemaProvider, GraphQLSpringContextBuilder contextBuilder, - GraphQLSpringRootObjectBuilder rootObjectBuilder - ) { + GraphQLSpringRootObjectBuilder rootObjectBuilder) { Objects.requireNonNull(schemaProvider, "GraphQLSchemaProvider is required"); this.schemaProviderSupplier = () -> schemaProvider; if (contextBuilder != null) { @@ -37,10 +38,9 @@ public DefaultGraphQLSpringInvocationInputFactory( public DefaultGraphQLSpringInvocationInputFactory( Supplier schemaProviderSupplier, Supplier contextBuilderSupplier, - Supplier rootObjectBuilderSupplier - ) { - this.schemaProviderSupplier = Objects - .requireNonNull(schemaProviderSupplier, "GraphQLSchemaProvider is required"); + Supplier rootObjectBuilderSupplier) { + this.schemaProviderSupplier = + Objects.requireNonNull(schemaProviderSupplier, "GraphQLSchemaProvider is required"); if (contextBuilderSupplier != null) { this.contextBuilderSupplier = contextBuilderSupplier; } @@ -50,20 +50,18 @@ public DefaultGraphQLSpringInvocationInputFactory( } @Override - public GraphQLSingleInvocationInput create(GraphQLRequest graphQLRequest, - ServerWebExchange serverWebExchange) { + public GraphQLSingleInvocationInput create( + GraphQLRequest graphQLRequest, ServerWebExchange serverWebExchange) { return new GraphQLSingleInvocationInput( graphQLRequest, schemaProviderSupplier.get().getSchema(), contextBuilderSupplier.get().build(serverWebExchange), - rootObjectBuilderSupplier.get().build(serverWebExchange) - ); + rootObjectBuilderSupplier.get().build(serverWebExchange)); } @Override - public GraphQLBatchedInvocationInput create(Collection graphQLRequests, - ServerWebExchange serverWebExchange) { + public GraphQLBatchedInvocationInput create( + Collection graphQLRequests, ServerWebExchange serverWebExchange) { throw new UnsupportedOperationException("Batch queries not suppoprted yet"); } - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringContext.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringContext.java index 326441a8..4b74df86 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringContext.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringContext.java @@ -6,5 +6,4 @@ public interface GraphQLSpringContext extends GraphQLContext { ServerWebExchange getServerWebExchange(); - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringContextBuilder.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringContextBuilder.java index 5264ea05..aad1f9dd 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringContextBuilder.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringContextBuilder.java @@ -5,5 +5,4 @@ public interface GraphQLSpringContextBuilder { GraphQLSpringContext build(ServerWebExchange serverWebExchange); - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringInvocationInputFactory.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringInvocationInputFactory.java index df5a7661..d7028fc9 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringInvocationInputFactory.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringInvocationInputFactory.java @@ -8,10 +8,9 @@ public interface GraphQLSpringInvocationInputFactory { - GraphQLSingleInvocationInput create(GraphQLRequest graphQLRequest, - ServerWebExchange serverWebExchange); - - GraphQLBatchedInvocationInput create(Collection graphQLRequests, - ServerWebExchange serverWebExchange); + GraphQLSingleInvocationInput create( + GraphQLRequest graphQLRequest, ServerWebExchange serverWebExchange); + GraphQLBatchedInvocationInput create( + Collection graphQLRequests, ServerWebExchange serverWebExchange); } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringRootObjectBuilder.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringRootObjectBuilder.java index 786650a0..2016dd62 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringRootObjectBuilder.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringRootObjectBuilder.java @@ -5,5 +5,4 @@ public interface GraphQLSpringRootObjectBuilder { Object build(ServerWebExchange serverWebExchange); - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringServerWebExchangeContext.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringServerWebExchangeContext.java index 3186421d..d3d57d69 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringServerWebExchangeContext.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/GraphQLSpringServerWebExchangeContext.java @@ -5,8 +5,8 @@ import org.dataloader.DataLoaderRegistry; import org.springframework.web.server.ServerWebExchange; -public class GraphQLSpringServerWebExchangeContext extends DefaultGraphQLContext implements - GraphQLSpringContext { +public class GraphQLSpringServerWebExchangeContext extends DefaultGraphQLContext + implements GraphQLSpringContext { private final ServerWebExchange serverWebExchange; @@ -14,16 +14,15 @@ public GraphQLSpringServerWebExchangeContext(ServerWebExchange serverWebExchange this(new DataLoaderRegistry(), serverWebExchange); } - public GraphQLSpringServerWebExchangeContext(DataLoaderRegistry dataLoaderRegistry, - ServerWebExchange serverWebExchange) { + public GraphQLSpringServerWebExchangeContext( + DataLoaderRegistry dataLoaderRegistry, ServerWebExchange serverWebExchange) { super(dataLoaderRegistry, null); - this.serverWebExchange = Objects - .requireNonNull(serverWebExchange, "Server web exchange cannot be null"); + this.serverWebExchange = + Objects.requireNonNull(serverWebExchange, "Server web exchange cannot be null"); } @Override public ServerWebExchange getServerWebExchange() { return serverWebExchange; } - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ErrorContext.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ErrorContext.java index c12ecb2e..2492e86c 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ErrorContext.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ErrorContext.java @@ -12,7 +12,8 @@ public class ErrorContext { private final Map extensions; private final ErrorClassification errorType; - public ErrorContext(List locations, + public ErrorContext( + List locations, List path, Map extensions, ErrorClassification errorType) { diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ErrorHandlerSupplier.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ErrorHandlerSupplier.java index 24780615..c99bf4b3 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ErrorHandlerSupplier.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ErrorHandlerSupplier.java @@ -23,5 +23,4 @@ public boolean isPresent() { public void setErrorHandler(GraphQLErrorHandler errorHandler) { this.errorHandler = errorHandler; } - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorFactory.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorFactory.java index eea38442..71113acb 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorFactory.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorFactory.java @@ -14,5 +14,4 @@ static GraphQLErrorFactory withReflection(Object object, Method method) { Optional> mostConcrete(Throwable t); Collection create(Throwable t, ErrorContext errorContext); - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorFromExceptionHandler.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorFromExceptionHandler.java index 7c0b66d9..e24e56b4 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorFromExceptionHandler.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorFromExceptionHandler.java @@ -30,18 +30,18 @@ class GraphQLErrorFromExceptionHandler extends DefaultGraphQLErrorHandler { @Override protected List filterGraphQLErrors(List errors) { - return errors.stream().map(this::transform).flatMap(Collection::stream) + return errors.stream() + .map(this::transform) + .flatMap(Collection::stream) .collect(Collectors.toList()); } private Collection transform(GraphQLError error) { - ErrorContext errorContext = new ErrorContext( - error.getLocations(), - error.getPath(), - error.getExtensions(), - error.getErrorType() - ); - return extractException(error).map(throwable -> transform(throwable, errorContext)) + ErrorContext errorContext = + new ErrorContext( + error.getLocations(), error.getPath(), error.getExtensions(), error.getErrorType()); + return extractException(error) + .map(throwable -> transform(throwable, errorContext)) .orElse(singletonList(new GenericGraphQLError(error.getMessage()))); } @@ -68,16 +68,14 @@ private Collection transform(Throwable throwable, ErrorContext err } private Collection withThrowable(Throwable throwable, ErrorContext errorContext) { - Map extensions = Optional.ofNullable(errorContext.getExtensions()) - .orElseGet(HashMap::new); + Map extensions = + Optional.ofNullable(errorContext.getExtensions()).orElseGet(HashMap::new); extensions.put("type", throwable.getClass().getSimpleName()); - GraphqlErrorBuilder builder = GraphqlErrorBuilder.newError() - .extensions(extensions); + GraphqlErrorBuilder builder = GraphqlErrorBuilder.newError().extensions(extensions); Optional.ofNullable(throwable.getMessage()).ifPresent(builder::message); Optional.ofNullable(errorContext.getErrorType()).ifPresent(builder::errorType); Optional.ofNullable(errorContext.getLocations()).ifPresent(builder::locations); Optional.ofNullable(errorContext.getPath()).ifPresent(builder::path); return singletonList(builder.build()); } - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorHandlerFactory.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorHandlerFactory.java index aa3c4ed1..1b044e1b 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorHandlerFactory.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorHandlerFactory.java @@ -17,17 +17,19 @@ @Slf4j public class GraphQLErrorHandlerFactory { - public GraphQLErrorHandler create(ConfigurableApplicationContext applicationContext, - boolean exceptionHandlersEnabled) { + public GraphQLErrorHandler create( + ConfigurableApplicationContext applicationContext, boolean exceptionHandlersEnabled) { ConfigurableListableBeanFactory beanFactory = applicationContext.getBeanFactory(); - List factories = Arrays.stream(beanFactory.getBeanDefinitionNames()) - .filter(applicationContext::containsBean) - .map(name -> scanForExceptionHandlers(applicationContext, name)) - .flatMap(List::stream) - .collect(toList()); + List factories = + Arrays.stream(beanFactory.getBeanDefinitionNames()) + .filter(applicationContext::containsBean) + .map(name -> scanForExceptionHandlers(applicationContext, name)) + .flatMap(List::stream) + .collect(toList()); if (!factories.isEmpty() || exceptionHandlersEnabled) { - log.debug("Handle GraphQL errors using exception handlers defined in {} custom factories", + log.debug( + "Handle GraphQL errors using exception handlers defined in {} custom factories", factories.size()); return new GraphQLErrorFromExceptionHandler(factories); } @@ -36,8 +38,8 @@ public GraphQLErrorHandler create(ConfigurableApplicationContext applicationCont return new DefaultGraphQLErrorHandler(); } - private List scanForExceptionHandlers(ApplicationContext context, - String name) { + private List scanForExceptionHandlers( + ApplicationContext context, String name) { try { Class objClz = context.getType(name); if (objClz == null) { @@ -53,5 +55,4 @@ private List scanForExceptionHandlers(ApplicationContext co return emptyList(); } } - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorStartupListener.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorStartupListener.java index 5ce302d8..403b1a9f 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorStartupListener.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/GraphQLErrorStartupListener.java @@ -11,8 +11,8 @@ public class GraphQLErrorStartupListener implements ApplicationListener) collectionType.getActualTypeArguments()[0]); + return GraphQLError.class.isAssignableFrom( + (Class) collectionType.getActualTypeArguments()[0]); } } return false; } - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ThrowableComparator.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ThrowableComparator.java index 49d1511f..128d0423 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ThrowableComparator.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ThrowableComparator.java @@ -11,5 +11,4 @@ public int compare(Class t1, Class t2) } return t1.isAssignableFrom(t2) ? 1 : -1; } - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ThrowableGraphQLError.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ThrowableGraphQLError.java index 65947c31..3ebfecfb 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ThrowableGraphQLError.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/ThrowableGraphQLError.java @@ -30,13 +30,12 @@ public final boolean equals(Object o) { return false; } ThrowableGraphQLError that = (ThrowableGraphQLError) o; - return Objects.equals(throwable, that.throwable) && Objects - .equals(getMessage(), that.getMessage()); + return Objects.equals(throwable, that.throwable) + && Objects.equals(getMessage(), that.getMessage()); } @Override public final int hashCode() { return Objects.hash(throwable, getMessage()); } - } diff --git a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/Throwables.java b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/Throwables.java index d77e7fa4..13039b1b 100644 --- a/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/Throwables.java +++ b/graphql-kickstart-spring-support/src/main/java/graphql/kickstart/spring/error/Throwables.java @@ -17,5 +17,4 @@ Optional> mostConcrete(Throwable throwable) { .filter(t -> t.isAssignableFrom(throwable.getClass())) .min(new ThrowableComparator()); } - } diff --git a/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorFromExceptionHandlerTest.java b/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorFromExceptionHandlerTest.java index 724c4135..83bc4131 100644 --- a/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorFromExceptionHandlerTest.java +++ b/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorFromExceptionHandlerTest.java @@ -1,5 +1,7 @@ package graphql.kickstart.spring.error; +import static org.junit.jupiter.api.Assertions.assertEquals; + import graphql.ErrorType; import graphql.GraphQLError; import graphql.GraphqlErrorException; @@ -8,24 +10,24 @@ import java.util.List; import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertEquals; - class GraphQLErrorFromExceptionHandlerTest { @Test void allows_errors_with_null_path() { GraphQLErrorFromExceptionHandler sut = new GraphQLErrorFromExceptionHandler(new ArrayList<>()); List errors = new ArrayList<>(); - errors.add(GraphqlErrorException.newErrorException() - .message("Error without a path") - .sourceLocation(new SourceLocation(0, 0)) - .build()); - errors.add(GraphqlErrorException.newErrorException() - .message("Error with path") - .sourceLocation(new SourceLocation(0, 0)) - .errorClassification(ErrorType.ValidationError) - .path(new ArrayList<>()) - .build()); + errors.add( + GraphqlErrorException.newErrorException() + .message("Error without a path") + .sourceLocation(new SourceLocation(0, 0)) + .build()); + errors.add( + GraphqlErrorException.newErrorException() + .message("Error with path") + .sourceLocation(new SourceLocation(0, 0)) + .errorClassification(ErrorType.ValidationError) + .path(new ArrayList<>()) + .build()); List processedErrors = sut.filterGraphQLErrors(errors); diff --git a/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorHandlerFactoryTest.java b/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorHandlerFactoryTest.java index 3946d086..edf1f475 100644 --- a/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorHandlerFactoryTest.java +++ b/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorHandlerFactoryTest.java @@ -19,17 +19,15 @@ @ExtendWith(MockitoExtension.class) class GraphQLErrorHandlerFactoryTest { - @Mock - private ConfigurableApplicationContext applicationContext; - @Mock - private ConfigurableListableBeanFactory beanFactory; + @Mock private ConfigurableApplicationContext applicationContext; + @Mock private ConfigurableListableBeanFactory beanFactory; private GraphQLErrorHandlerFactory errorHandlerFactory; @BeforeEach public void setup() { Mockito.when(applicationContext.getBeanFactory()).thenReturn(beanFactory); - Mockito.when(beanFactory.getBeanDefinitionNames()).thenReturn(new String[]{"Test"}); + Mockito.when(beanFactory.getBeanDefinitionNames()).thenReturn(new String[] {"Test"}); Mockito.when(applicationContext.containsBean("Test")).thenReturn(true); Mockito.doReturn(TestClass.class).when(applicationContext).getType("Test"); @@ -41,7 +39,8 @@ void createFindsCollectionHandler() { GraphQLErrorHandler handler = errorHandlerFactory.create(applicationContext, true); assertThat(handler).isInstanceOf(GraphQLErrorFromExceptionHandler.class); GraphQLErrorFromExceptionHandler errorHandler = (GraphQLErrorFromExceptionHandler) handler; - assertThat(errorHandler.getFactories()).as("handler.factories should not be empty") + assertThat(errorHandler.getFactories()) + .as("handler.factories should not be empty") .isNotEmpty(); } @@ -51,7 +50,5 @@ public static class TestClass { List handle(IllegalArgumentException e) { return singletonList(new ThrowableGraphQLError(e, "Illegal argument")); } - } - } diff --git a/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorStartupListenerTest.java b/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorStartupListenerTest.java index 78cf7fe0..f3bddc7b 100644 --- a/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorStartupListenerTest.java +++ b/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorStartupListenerTest.java @@ -14,8 +14,8 @@ class GraphQLErrorStartupListenerTest { void error_handler_is_not_overridden_when_present() { GraphQLErrorHandler expectedErrorHandler = Mockito.mock(GraphQLErrorHandler.class); ErrorHandlerSupplier errorHandlerSupplier = new ErrorHandlerSupplier(expectedErrorHandler); - GraphQLErrorStartupListener graphQLErrorStartupListener = new GraphQLErrorStartupListener( - errorHandlerSupplier, false); + GraphQLErrorStartupListener graphQLErrorStartupListener = + new GraphQLErrorStartupListener(errorHandlerSupplier, false); graphQLErrorStartupListener.onApplicationEvent(getApplicationReadyEvent()); Assertions.assertThat(errorHandlerSupplier.get()).isEqualTo(expectedErrorHandler); } @@ -23,17 +23,17 @@ void error_handler_is_not_overridden_when_present() { @Test void error_handler_is_set_when_not_present() { ErrorHandlerSupplier errorHandlerSupplier = new ErrorHandlerSupplier(null); - GraphQLErrorStartupListener graphQLErrorStartupListener = new GraphQLErrorStartupListener( - errorHandlerSupplier, false); + GraphQLErrorStartupListener graphQLErrorStartupListener = + new GraphQLErrorStartupListener(errorHandlerSupplier, false); graphQLErrorStartupListener.onApplicationEvent(getApplicationReadyEvent()); Assertions.assertThat(errorHandlerSupplier.get()).isNotNull(); } private ApplicationReadyEvent getApplicationReadyEvent() { - AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext(); + AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = + new AnnotationConfigWebApplicationContext(); annotationConfigWebApplicationContext.refresh(); - return new ApplicationReadyEvent(new SpringApplication(), new String[0], - annotationConfigWebApplicationContext); + return new ApplicationReadyEvent( + new SpringApplication(), new String[0], annotationConfigWebApplicationContext); } - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebSocketSessionContext.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebSocketSessionContext.java index 2596ec7e..9a0de7f8 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebSocketSessionContext.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebSocketSessionContext.java @@ -5,8 +5,8 @@ import org.dataloader.DataLoaderRegistry; import org.springframework.web.reactive.socket.WebSocketSession; -public class DefaultGraphQLSpringWebSocketSessionContext extends DefaultGraphQLContext implements - GraphQLSpringWebSocketSessionContext { +public class DefaultGraphQLSpringWebSocketSessionContext extends DefaultGraphQLContext + implements GraphQLSpringWebSocketSessionContext { private final WebSocketSession webSocketSession; @@ -14,16 +14,15 @@ public DefaultGraphQLSpringWebSocketSessionContext(WebSocketSession webSocketSes this(new DataLoaderRegistry(), webSocketSession); } - public DefaultGraphQLSpringWebSocketSessionContext(DataLoaderRegistry dataLoaderRegistry, - WebSocketSession webSocketSession) { + public DefaultGraphQLSpringWebSocketSessionContext( + DataLoaderRegistry dataLoaderRegistry, WebSocketSession webSocketSession) { super(dataLoaderRegistry, null); - this.webSocketSession = Objects - .requireNonNull(webSocketSession, "WebSocketSession is required"); + this.webSocketSession = + Objects.requireNonNull(webSocketSession, "WebSocketSession is required"); } @Override public WebSocketSession getWebSocketSession() { return webSocketSession; } - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebfluxContextBuilder.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebfluxContextBuilder.java index 8cb3900e..bee326bb 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebfluxContextBuilder.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebfluxContextBuilder.java @@ -5,8 +5,8 @@ import org.springframework.web.reactive.socket.WebSocketSession; import org.springframework.web.server.ServerWebExchange; -public class DefaultGraphQLSpringWebfluxContextBuilder implements - GraphQLSpringWebfluxContextBuilder { +public class DefaultGraphQLSpringWebfluxContextBuilder + implements GraphQLSpringWebfluxContextBuilder { @Override public GraphQLSpringWebSocketSessionContext build(WebSocketSession webSocketSession) { @@ -17,5 +17,4 @@ public GraphQLSpringWebSocketSessionContext build(WebSocketSession webSocketSess public GraphQLSpringContext build(ServerWebExchange serverWebExchange) { return new GraphQLSpringServerWebExchangeContext(serverWebExchange); } - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebfluxRootObjectBuilder.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebfluxRootObjectBuilder.java index 3d7f1a31..c2888f1b 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebfluxRootObjectBuilder.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/DefaultGraphQLSpringWebfluxRootObjectBuilder.java @@ -16,5 +16,4 @@ public Object build(ServerWebExchange serverWebExchange) { public Object build(WebSocketSession webSocketSession) { return new Object(); } - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLController.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLController.java index a59e6b77..0420028b 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLController.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLController.java @@ -19,7 +19,9 @@ public class GraphQLController extends AbstractGraphQLController { private final GraphQLInvoker graphQLInvoker; private final GraphQLSpringInvocationInputFactory invocationInputFactory; - public GraphQLController(GraphQLObjectMapper objectMapper, GraphQLInvoker graphQLInvoker, + public GraphQLController( + GraphQLObjectMapper objectMapper, + GraphQLInvoker graphQLInvoker, GraphQLSpringInvocationInputFactory invocationInputFactory) { super(objectMapper); this.objectMapper = objectMapper; @@ -32,11 +34,11 @@ protected Object executeRequest( String operationName, Map variables, ServerWebExchange serverWebExchange) { - GraphQLSingleInvocationInput invocationInput = invocationInputFactory - .create(new GraphQLRequest(query, variables, operationName), serverWebExchange); - Mono executionResult = Mono - .fromCompletionStage(graphQLInvoker.executeAsync(invocationInput)); + GraphQLSingleInvocationInput invocationInput = + invocationInputFactory.create( + new GraphQLRequest(query, variables, operationName), serverWebExchange); + Mono executionResult = + Mono.fromCompletionStage(graphQLInvoker.executeAsync(invocationInput)); return executionResult.map(objectMapper::createResultFromExecutionResult); } - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebSocketSessionContext.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebSocketSessionContext.java index 4706010e..4d913b78 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebSocketSessionContext.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebSocketSessionContext.java @@ -6,5 +6,4 @@ public interface GraphQLSpringWebSocketSessionContext extends GraphQLContext { WebSocketSession getWebSocketSession(); - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxContextBuilder.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxContextBuilder.java index bf26a088..49b50fb9 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxContextBuilder.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxContextBuilder.java @@ -6,5 +6,4 @@ public interface GraphQLSpringWebfluxContextBuilder extends GraphQLSpringContextBuilder { GraphQLSpringWebSocketSessionContext build(WebSocketSession webSocketSession); - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxInvocationInputFactory.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxInvocationInputFactory.java index c6ac37d2..e8d245c5 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxInvocationInputFactory.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxInvocationInputFactory.java @@ -15,7 +15,8 @@ public class GraphQLSpringWebfluxInvocationInputFactory extends DefaultGraphQLSpringInvocationInputFactory implements GraphQLSubscriptionInvocationInputFactory { - public GraphQLSpringWebfluxInvocationInputFactory(GraphQLSchemaProvider schemaProvider, + public GraphQLSpringWebfluxInvocationInputFactory( + GraphQLSchemaProvider schemaProvider, GraphQLSpringContextBuilder contextBuilder, GraphQLSpringRootObjectBuilder rootObjectBuilder) { super(schemaProvider, contextBuilder, rootObjectBuilder); @@ -29,16 +30,14 @@ public GraphQLSpringWebfluxInvocationInputFactory( } @Override - public GraphQLSingleInvocationInput create(GraphQLRequest graphQLRequest, - SubscriptionSession session) { + public GraphQLSingleInvocationInput create( + GraphQLRequest graphQLRequest, SubscriptionSession session) { return new GraphQLSingleInvocationInput( graphQLRequest, getSchemaProviderSupplier().get().getSchema(), ((GraphQLSpringWebfluxContextBuilder) getContextBuilderSupplier().get()) .build((WebSocketSession) session.unwrap()), ((GraphQLSpringWebfluxRootObjectBuilder) getRootObjectBuilderSupplier().get()) - .build((WebSocketSession) session.unwrap()) - ); + .build((WebSocketSession) session.unwrap())); } - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxRootObjectBuilder.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxRootObjectBuilder.java index 348511f8..a2a2d644 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxRootObjectBuilder.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/GraphQLSpringWebfluxRootObjectBuilder.java @@ -6,5 +6,4 @@ public interface GraphQLSpringWebfluxRootObjectBuilder extends GraphQLSpringRootObjectBuilder { Object build(WebSocketSession webSocketSession); - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveSubscriptionsProtocolFactory.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveSubscriptionsProtocolFactory.java index e093adad..40161ee7 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveSubscriptionsProtocolFactory.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveSubscriptionsProtocolFactory.java @@ -9,5 +9,4 @@ public interface ReactiveSubscriptionsProtocolFactory { Consumer createConsumer(SubscriptionSession session); SubscriptionSession createSession(WebSocketSession session); - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveWebSocketSubscriptionSession.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveWebSocketSubscriptionSession.java index 405d5a4f..ba97408d 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveWebSocketSubscriptionSession.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveWebSocketSubscriptionSession.java @@ -9,8 +9,8 @@ public class ReactiveWebSocketSubscriptionSession extends DefaultSubscriptionSes private final WebSocketSession webSocketSession; - public ReactiveWebSocketSubscriptionSession(GraphQLSubscriptionMapper mapper, - WebSocketSession webSocketSession) { + public ReactiveWebSocketSubscriptionSession( + GraphQLSubscriptionMapper mapper, WebSocketSession webSocketSession) { super(mapper); this.webSocketSession = webSocketSession; } @@ -34,5 +34,4 @@ public String getId() { public WebSocketSession unwrap() { return webSocketSession; } - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveWebSocketSubscriptionsHandler.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveWebSocketSubscriptionsHandler.java index 703e8008..ad08ea91 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveWebSocketSubscriptionsHandler.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/ReactiveWebSocketSubscriptionsHandler.java @@ -28,21 +28,22 @@ public List getSubProtocols() { @Override public Mono handle(WebSocketSession webSocketSession) { - SubscriptionSession subscriptionSession = subscriptionProtocolFactory - .createSession(webSocketSession); + SubscriptionSession subscriptionSession = + subscriptionProtocolFactory.createSession(webSocketSession); Consumer consumer = subscriptionProtocolFactory.createConsumer(subscriptionSession); - Mono input = webSocketSession.receive() - .map(WebSocketMessage::getPayloadAsText) - .doOnNext(consumer) - .doFinally(type -> subscriptionSession.close(null)) - .then(); + Mono input = + webSocketSession + .receive() + .map(WebSocketMessage::getPayloadAsText) + .doOnNext(consumer) + .doFinally(type -> subscriptionSession.close(null)) + .then(); - Mono sender = webSocketSession.send( - Flux.from(subscriptionSession.getPublisher()).map(webSocketSession::textMessage) - ); + Mono sender = + webSocketSession.send( + Flux.from(subscriptionSession.getPublisher()).map(webSocketSession::textMessage)); return Mono.zip(input, sender).then(); } - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/apollo/ReactiveApolloSubscriptionProtocolFactory.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/apollo/ReactiveApolloSubscriptionProtocolFactory.java index 60798a4b..67ea5722 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/apollo/ReactiveApolloSubscriptionProtocolFactory.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/apollo/ReactiveApolloSubscriptionProtocolFactory.java @@ -12,42 +12,49 @@ import java.util.Collection; import org.springframework.web.reactive.socket.WebSocketSession; -public class ReactiveApolloSubscriptionProtocolFactory - extends ApolloSubscriptionProtocolFactory +public class ReactiveApolloSubscriptionProtocolFactory extends ApolloSubscriptionProtocolFactory implements ReactiveSubscriptionsProtocolFactory { - public ReactiveApolloSubscriptionProtocolFactory(GraphQLObjectMapper objectMapper, + public ReactiveApolloSubscriptionProtocolFactory( + GraphQLObjectMapper objectMapper, GraphQLSubscriptionInvocationInputFactory invocationInputFactory, GraphQLInvoker graphQLInvoker) { super(objectMapper, invocationInputFactory, graphQLInvoker); } - public ReactiveApolloSubscriptionProtocolFactory(GraphQLObjectMapper objectMapper, + public ReactiveApolloSubscriptionProtocolFactory( + GraphQLObjectMapper objectMapper, GraphQLSubscriptionInvocationInputFactory invocationInputFactory, - GraphQLInvoker graphQLInvoker, Duration keepAliveInterval) { + GraphQLInvoker graphQLInvoker, + Duration keepAliveInterval) { super(objectMapper, invocationInputFactory, graphQLInvoker, keepAliveInterval); } - public ReactiveApolloSubscriptionProtocolFactory(GraphQLObjectMapper objectMapper, + public ReactiveApolloSubscriptionProtocolFactory( + GraphQLObjectMapper objectMapper, GraphQLSubscriptionInvocationInputFactory invocationInputFactory, GraphQLInvoker graphQLInvoker, Collection connectionListeners) { super(objectMapper, invocationInputFactory, graphQLInvoker, connectionListeners); } - public ReactiveApolloSubscriptionProtocolFactory(GraphQLObjectMapper objectMapper, + public ReactiveApolloSubscriptionProtocolFactory( + GraphQLObjectMapper objectMapper, GraphQLSubscriptionInvocationInputFactory invocationInputFactory, GraphQLInvoker graphQLInvoker, Collection connectionListeners, Duration keepAliveInterval) { - super(objectMapper, invocationInputFactory, graphQLInvoker, connectionListeners, + super( + objectMapper, + invocationInputFactory, + graphQLInvoker, + connectionListeners, keepAliveInterval); } @Override public SubscriptionSession createSession(WebSocketSession session) { - return new ReactiveApolloSubscriptionSession(new GraphQLSubscriptionMapper(getObjectMapper()), - session); + return new ReactiveApolloSubscriptionSession( + new GraphQLSubscriptionMapper(getObjectMapper()), session); } - } diff --git a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/apollo/ReactiveApolloSubscriptionSession.java b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/apollo/ReactiveApolloSubscriptionSession.java index f2b42868..b03497c8 100644 --- a/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/apollo/ReactiveApolloSubscriptionSession.java +++ b/graphql-kickstart-spring-webflux/src/main/java/graphql/kickstart/spring/webflux/apollo/ReactiveApolloSubscriptionSession.java @@ -10,8 +10,8 @@ public class ReactiveApolloSubscriptionSession extends ApolloSubscriptionSession private final ReactiveWebSocketSubscriptionSession session; - public ReactiveApolloSubscriptionSession(GraphQLSubscriptionMapper mapper, - WebSocketSession webSocketSession) { + public ReactiveApolloSubscriptionSession( + GraphQLSubscriptionMapper mapper, WebSocketSession webSocketSession) { super(mapper); session = new ReactiveWebSocketSubscriptionSession(mapper, webSocketSession); } @@ -35,5 +35,4 @@ public String getId() { public WebSocketSession unwrap() { return session.unwrap(); } - } diff --git a/graphql-kickstart-starter-utils/src/main/java/graphql/kickstart/util/PropertyGroupReader.java b/graphql-kickstart-starter-utils/src/main/java/graphql/kickstart/util/PropertyGroupReader.java index 6c9431e8..058306da 100644 --- a/graphql-kickstart-starter-utils/src/main/java/graphql/kickstart/util/PropertyGroupReader.java +++ b/graphql-kickstart-starter-utils/src/main/java/graphql/kickstart/util/PropertyGroupReader.java @@ -32,17 +32,19 @@ public Properties load() { } private void loadProps() { - streamOfPropertySources().forEach(propertySource -> - Arrays.stream(propertySource.getPropertyNames()) - .filter(this::isWanted) - .forEach(key -> add(propertySource, key))); + streamOfPropertySources() + .forEach( + propertySource -> + Arrays.stream(propertySource.getPropertyNames()) + .filter(this::isWanted) + .forEach(key -> add(propertySource, key))); } @SuppressWarnings("unchecked") private Stream> streamOfPropertySources() { if (environment instanceof ConfigurableEnvironment) { - Iterator> iterator = ((ConfigurableEnvironment) environment) - .getPropertySources().iterator(); + Iterator> iterator = + ((ConfigurableEnvironment) environment).getPropertySources().iterator(); Iterable> iterable = () -> iterator; return StreamSupport.stream(iterable.spliterator(), false) .filter(EnumerablePropertySource.class::isInstance) @@ -62,6 +64,4 @@ private boolean isWanted(String key) { private void add(EnumerablePropertySource propertySource, String key) { props.put(withoutPrefix(key), propertySource.getProperty(key)); } - } - diff --git a/graphql-kickstart-starter-utils/src/main/java/graphql/kickstart/util/PropsLoader.java b/graphql-kickstart-starter-utils/src/main/java/graphql/kickstart/util/PropsLoader.java index f093114d..4c52c42f 100644 --- a/graphql-kickstart-starter-utils/src/main/java/graphql/kickstart/util/PropsLoader.java +++ b/graphql-kickstart-starter-utils/src/main/java/graphql/kickstart/util/PropsLoader.java @@ -48,5 +48,4 @@ private String loadResource(Resource resource) { return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); } } - } diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLExtendedScalarsInitializer.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLExtendedScalarsInitializer.java index 3d9eb64d..c88309bf 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLExtendedScalarsInitializer.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLExtendedScalarsInitializer.java @@ -2,67 +2,68 @@ import graphql.scalars.ExtendedScalars; import graphql.schema.GraphQLScalarType; -import lombok.NoArgsConstructor; -import org.springframework.context.ApplicationContextException; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.util.ReflectionUtils; - import java.lang.reflect.Modifier; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; +import lombok.NoArgsConstructor; +import org.springframework.context.ApplicationContextException; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.util.ReflectionUtils; @NoArgsConstructor -public class GraphQLExtendedScalarsInitializer implements ApplicationContextInitializer { +public class GraphQLExtendedScalarsInitializer + implements ApplicationContextInitializer { - @Override - public void initialize(final GenericApplicationContext applicationContext) { - final Collection enabledExtendedScalars = getEnabledExtendedScalars(applicationContext); - final Collection validScalarNames = new HashSet<>(); - ReflectionUtils.doWithFields(ExtendedScalars.class, scalarField -> { - if (Modifier.isPublic(scalarField.getModifiers()) && Modifier.isStatic(scalarField.getModifiers()) - && scalarField.getType().equals(GraphQLScalarType.class)) { - final GraphQLScalarType graphQLScalarType = (GraphQLScalarType) scalarField.get(null); - if (enabledExtendedScalars.contains(graphQLScalarType.getName())) { - applicationContext.registerBean( - graphQLScalarType.getName(), - GraphQLScalarType.class, - () -> graphQLScalarType - ); - } - validScalarNames.add(graphQLScalarType.getName()); + @Override + public void initialize(final GenericApplicationContext applicationContext) { + final Collection enabledExtendedScalars = getEnabledExtendedScalars(applicationContext); + final Collection validScalarNames = new HashSet<>(); + ReflectionUtils.doWithFields( + ExtendedScalars.class, + scalarField -> { + if (Modifier.isPublic(scalarField.getModifiers()) + && Modifier.isStatic(scalarField.getModifiers()) + && scalarField.getType().equals(GraphQLScalarType.class)) { + final GraphQLScalarType graphQLScalarType = (GraphQLScalarType) scalarField.get(null); + if (enabledExtendedScalars.contains(graphQLScalarType.getName())) { + applicationContext.registerBean( + graphQLScalarType.getName(), GraphQLScalarType.class, () -> graphQLScalarType); } + validScalarNames.add(graphQLScalarType.getName()); + } }); - verifyEnabledScalars(enabledExtendedScalars, validScalarNames); - } + verifyEnabledScalars(enabledExtendedScalars, validScalarNames); + } - private void verifyEnabledScalars( - final Collection enabledExtendedScalars, - final Collection validScalarNames - ) { - final Collection invalidScalarNames = new HashSet<>(enabledExtendedScalars); - invalidScalarNames.removeAll(validScalarNames); - if (!invalidScalarNames.isEmpty()) { - throw new ApplicationContextException(String.format( - "Invalid extended scalar name(s) found: %s. Valid names are: %s.", - joinNames(invalidScalarNames), - joinNames(validScalarNames) - ) - ); - } + private void verifyEnabledScalars( + final Collection enabledExtendedScalars, final Collection validScalarNames) { + final Collection invalidScalarNames = new HashSet<>(enabledExtendedScalars); + invalidScalarNames.removeAll(validScalarNames); + if (!invalidScalarNames.isEmpty()) { + throw new ApplicationContextException( + String.format( + "Invalid extended scalar name(s) found: %s. Valid names are: %s.", + joinNames(invalidScalarNames), joinNames(validScalarNames))); } + } - private String joinNames(final Collection names) { - return names.stream().sorted().collect(Collectors.joining(", ")); - } + private String joinNames(final Collection names) { + return names.stream().sorted().collect(Collectors.joining(", ")); + } - @SuppressWarnings("unchecked") - private Set getEnabledExtendedScalars(final GenericApplicationContext applicationContext) { - return (Set) applicationContext.getEnvironment() + @SuppressWarnings("unchecked") + private Set getEnabledExtendedScalars( + final GenericApplicationContext applicationContext) { + return (Set) + applicationContext + .getEnvironment() .getProperty("graphql.extended-scalars", Collection.class, Collections.emptySet()) - .stream().map(String::valueOf).collect(Collectors.toSet()); - } + .stream() + .map(String::valueOf) + .collect(Collectors.toSet()); + } } diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLInstrumentationAutoConfiguration.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLInstrumentationAutoConfiguration.java index 9a60f8a3..65fd7bd4 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLInstrumentationAutoConfiguration.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLInstrumentationAutoConfiguration.java @@ -21,32 +21,38 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -/** - * @author Marcel Overdijk - */ +/** @author Marcel Overdijk */ @Configuration @RequiredArgsConstructor @ConditionalOnClass(MetricsAutoConfiguration.class) -@AutoConfigureAfter({MetricsAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class, - GraphQLWebsocketAutoConfiguration.class}) +@AutoConfigureAfter({ + MetricsAutoConfiguration.class, + SimpleMetricsExportAutoConfiguration.class, + GraphQLWebsocketAutoConfiguration.class +}) @EnableConfigurationProperties(GraphQLServletProperties.class) -@ConditionalOnProperty(value = "graphql.servlet.enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty( + value = "graphql.servlet.enabled", + havingValue = "true", + matchIfMissing = true) public class GraphQLInstrumentationAutoConfiguration { private final GraphQLServletProperties graphqlServletProperties; @Bean @ConditionalOnMissingBean({TracingInstrumentation.class, MetricsInstrumentation.class}) - @ConditionalOnExpression("'${graphql.servlet.tracing-enabled:false}' == 'metrics-only' " - + "|| '${graphql.servlet.tracing-enabled:false}' == 'true'") + @ConditionalOnExpression( + "'${graphql.servlet.tracing-enabled:false}' == 'metrics-only' " + + "|| '${graphql.servlet.tracing-enabled:false}' == 'true'") public TracingInstrumentation tracingInstrumentation() { return new TracingInstrumentation(); } @Bean @ConditionalOnMissingBean - @ConditionalOnExpression("${graphql.servlet.actuator-metrics:false} " - + "&& '${graphql.servlet.tracing-enabled:false}' == 'false'") + @ConditionalOnExpression( + "${graphql.servlet.actuator-metrics:false} " + + "&& '${graphql.servlet.tracing-enabled:false}' == 'false'") public TracingNoResolversInstrumentation tracingNoResolversInstrumentation() { return new TracingNoResolversInstrumentation(); } @@ -70,7 +76,8 @@ public MaxQueryDepthInstrumentation maxQueryDepthInstrumentation() { @ConditionalOnBean({MeterRegistry.class, TracingInstrumentation.class}) @ConditionalOnMissingBean public MetricsInstrumentation metricsInstrumentation(MeterRegistry meterRegistry) { - return new MetricsInstrumentation(meterRegistry, + return new MetricsInstrumentation( + meterRegistry, Boolean.TRUE.toString().equalsIgnoreCase(graphqlServletProperties.getTracingEnabled())); } @@ -78,9 +85,8 @@ public MetricsInstrumentation metricsInstrumentation(MeterRegistry meterRegistry @ConditionalOnProperty(value = "graphql.servlet.actuator-metrics", havingValue = "true") @ConditionalOnBean({MeterRegistry.class, GraphQLWebsocketServlet.class}) @ConditionalOnMissingBean - public WebsocketMetrics websocketMetrics(MeterRegistry meterRegistry, - GraphQLWebsocketServlet websocketServlet) { + public WebsocketMetrics websocketMetrics( + MeterRegistry meterRegistry, GraphQLWebsocketServlet websocketServlet) { return new WebsocketMetrics(meterRegistry, websocketServlet); } - } diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLServletProperties.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLServletProperties.java index f9b41941..6d147009 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLServletProperties.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLServletProperties.java @@ -22,9 +22,7 @@ import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ @Data @ConfigurationProperties(prefix = "graphql.servlet") public class GraphQLServletProperties { @@ -58,7 +56,7 @@ public String getServletMapping() { /** * @return the servlet mapping, coercing into an appropriate wildcard for CORS, which uses ant - * matchers (ending in /**) + * matchers (ending in /**) */ public String getCorsMapping() { final String originalMapping = getMapping(); @@ -78,5 +76,4 @@ private boolean mappingIsServletWildcard() { private boolean mappingIsAntWildcard() { return getMapping().endsWith("/**"); } - } diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLSubscriptionApolloProperties.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLSubscriptionApolloProperties.java index cc045e8e..27e7c780 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLSubscriptionApolloProperties.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLSubscriptionApolloProperties.java @@ -10,5 +10,4 @@ class GraphQLSubscriptionApolloProperties { private boolean keepAliveEnabled = true; private int keepAliveIntervalSeconds = 15; - } diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLSubscriptionWebsocketProperties.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLSubscriptionWebsocketProperties.java index 281c7da3..442ed5db 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLSubscriptionWebsocketProperties.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLSubscriptionWebsocketProperties.java @@ -8,5 +8,4 @@ class GraphQLSubscriptionWebsocketProperties { private String path = "/subscriptions"; - } diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWebAutoConfiguration.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWebAutoConfiguration.java index b58242bd..0aeb27d3 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWebAutoConfiguration.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWebAutoConfiguration.java @@ -86,10 +86,7 @@ import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.DispatcherServlet; - -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ @Slf4j @Configuration @RequiredArgsConstructor @@ -97,7 +94,10 @@ @ConditionalOnClass(DispatcherServlet.class) @Conditional(OnSchemaOrSchemaProviderBean.class) @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") -@ConditionalOnProperty(value = "graphql.servlet.enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty( + value = "graphql.servlet.enabled", + havingValue = "true", + matchIfMissing = true) @AutoConfigureAfter({GraphQLJavaToolsAutoConfiguration.class, JacksonAutoConfiguration.class}) @EnableConfigurationProperties({GraphQLServletProperties.class}) public class GraphQLWebAutoConfiguration { @@ -113,8 +113,8 @@ public class GraphQLWebAutoConfiguration { public GraphQLErrorStartupListener graphQLErrorStartupListener( @Autowired(required = false) GraphQLErrorHandler errorHandler) { errorHandlerSupplier.setErrorHandler(errorHandler); - return new GraphQLErrorStartupListener(errorHandlerSupplier, - graphQLServletProperties.isExceptionHandlersEnabled()); + return new GraphQLErrorStartupListener( + errorHandlerSupplier, graphQLServletProperties.isExceptionHandlersEnabled()); } @Bean @@ -126,7 +126,10 @@ public CorsConfiguration corsConfiguration() { @Bean @ConditionalOnClass(CorsFilter.class) - @ConditionalOnProperty(value = "graphql.servlet.corsEnabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty( + value = "graphql.servlet.corsEnabled", + havingValue = "true", + matchIfMissing = true) public CorsFilter corsConfigurer(CorsConfiguration corsConfiguration) { Map corsConfigurations = new LinkedHashMap<>(1); if (corsConfiguration.getAllowedMethods() == null) { @@ -151,32 +154,30 @@ public GraphQLSchemaServletProvider graphQLSchemaProvider(GraphQLSchema schema) @Bean @ConditionalOnMissingBean public ExecutionStrategyProvider executionStrategyProvider( - @Autowired(required = false) Map executionStrategies - ) { + @Autowired(required = false) Map executionStrategies) { if (executionStrategies == null || executionStrategies.isEmpty()) { - return new DefaultExecutionStrategyProvider(new AsyncExecutionStrategy(), null, - new SubscriptionExecutionStrategy()); + return new DefaultExecutionStrategyProvider( + new AsyncExecutionStrategy(), null, new SubscriptionExecutionStrategy()); } else if (executionStrategies.entrySet().size() == 1) { return new DefaultExecutionStrategyProvider( executionStrategies.entrySet().stream() .findFirst() .map(Entry::getValue) - .orElseThrow(IllegalStateException::new) - ); + .orElseThrow(IllegalStateException::new)); } else { if (!executionStrategies.containsKey(QUERY_EXECUTION_STRATEGY)) { throwIncorrectExecutionStrategyNameException(); } - if (executionStrategies.size() == 2 && !( - executionStrategies.containsKey(MUTATION_EXECUTION_STRATEGY) + if (executionStrategies.size() == 2 + && !(executionStrategies.containsKey(MUTATION_EXECUTION_STRATEGY) || executionStrategies.containsKey(SUBSCRIPTION_EXECUTION_STRATEGY))) { throwIncorrectExecutionStrategyNameException(); } - if (executionStrategies.size() >= 3 && !( - executionStrategies.containsKey(MUTATION_EXECUTION_STRATEGY) + if (executionStrategies.size() >= 3 + && !(executionStrategies.containsKey(MUTATION_EXECUTION_STRATEGY) && executionStrategies.containsKey(SUBSCRIPTION_EXECUTION_STRATEGY))) { throwIncorrectExecutionStrategyNameException(); } @@ -184,15 +185,16 @@ public ExecutionStrategyProvider executionStrategyProvider( return new DefaultExecutionStrategyProvider( executionStrategies.get(QUERY_EXECUTION_STRATEGY), executionStrategies.get(MUTATION_EXECUTION_STRATEGY), - executionStrategies.get(SUBSCRIPTION_EXECUTION_STRATEGY) - ); + executionStrategies.get(SUBSCRIPTION_EXECUTION_STRATEGY)); } } private void throwIncorrectExecutionStrategyNameException() { - throw new IllegalStateException(String - .format("When defining more than one execution strategy, they must be named %s, %s, or %s", - QUERY_EXECUTION_STRATEGY, MUTATION_EXECUTION_STRATEGY, + throw new IllegalStateException( + String.format( + "When defining more than one execution strategy, they must be named %s, %s, or %s", + QUERY_EXECUTION_STRATEGY, + MUTATION_EXECUTION_STRATEGY, SUBSCRIPTION_EXECUTION_STRATEGY)); } @@ -202,8 +204,8 @@ public GraphQLInvocationInputFactory invocationInputFactory( GraphQLSchemaServletProvider schemaProvider, @Autowired(required = false) GraphQLServletContextBuilder contextBuilder, @Autowired(required = false) GraphQLServletRootObjectBuilder graphQLRootObjectBuilder) { - GraphQLInvocationInputFactory.Builder builder = GraphQLInvocationInputFactory - .newBuilder(schemaProvider); + GraphQLInvocationInputFactory.Builder builder = + GraphQLInvocationInputFactory.newBuilder(schemaProvider); if (graphQLRootObjectBuilder != null) { builder.withGraphQLRootObjectBuilder(graphQLRootObjectBuilder); @@ -230,7 +232,8 @@ public GraphQLBuilder graphQLBuilder( if (instrumentations.size() == 1) { graphQLBuilder.instrumentation(() -> instrumentations.get(0)); } else { - // Metrics instrumentation should be the last to run (we need that from TracingInstrumentation) + // Metrics instrumentation should be the last to run (we need that from + // TracingInstrumentation) instrumentations.sort((a, b) -> a instanceof MetricsInstrumentation ? 1 : 0); graphQLBuilder.instrumentation(() -> new ChainedInstrumentation(instrumentations)); } @@ -250,14 +253,15 @@ public GraphQLBuilder graphQLBuilder( @Bean @ConditionalOnMissingBean public BatchedDataLoaderGraphQLBuilder batchedDataLoaderGraphQLBuilder( - @Autowired(required = false) Supplier optionsSupplier - ) { + @Autowired(required = false) + Supplier optionsSupplier) { return new BatchedDataLoaderGraphQLBuilder(optionsSupplier); } @Bean @ConditionalOnMissingBean - public GraphQLInvoker graphQLInvoker(GraphQLBuilder graphQLBuilder, + public GraphQLInvoker graphQLInvoker( + GraphQLBuilder graphQLBuilder, BatchedDataLoaderGraphQLBuilder batchedDataLoaderGraphQLBuilder) { return new GraphQLInvoker(graphQLBuilder, batchedDataLoaderGraphQLBuilder); } @@ -282,7 +286,9 @@ public GraphQLObjectMapper graphQLObjectMapper( @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(value = "graphql.servlet.use-default-objectmapper", havingValue = "true", + @ConditionalOnProperty( + value = "graphql.servlet.use-default-objectmapper", + havingValue = "true", matchIfMissing = true) public ObjectMapperProvider objectMapperProvider(ObjectMapper objectMapper) { InjectableValues.Std injectableValues = new InjectableValues.Std(); @@ -332,5 +338,4 @@ public ServletRegistrationBean graphQLServletRegistr registration.setAsyncSupported(graphQLServletProperties.isAsyncModeEnabled()); return registration; } - } diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWebsocketAutoConfiguration.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWebsocketAutoConfiguration.java index 7a47f2ee..2959273f 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWebsocketAutoConfiguration.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWebsocketAutoConfiguration.java @@ -34,10 +34,15 @@ @ConditionalOnClass(DispatcherServlet.class) @Conditional(OnSchemaOrSchemaProviderBean.class) @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") -@ConditionalOnProperty(value = "graphql.servlet.websocket.enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty( + value = "graphql.servlet.websocket.enabled", + havingValue = "true", + matchIfMissing = true) @AutoConfigureAfter({GraphQLJavaToolsAutoConfiguration.class, GraphQLWebAutoConfiguration.class}) -@EnableConfigurationProperties({GraphQLSubscriptionApolloProperties.class, - GraphQLSubscriptionWebsocketProperties.class}) +@EnableConfigurationProperties({ + GraphQLSubscriptionApolloProperties.class, + GraphQLSubscriptionWebsocketProperties.class +}) public class GraphQLWebsocketAutoConfiguration { private final GraphQLSubscriptionApolloProperties apolloProperties; @@ -55,15 +60,15 @@ public GraphQLWebsocketServlet graphQLWebsocketServlet( listeners.addAll(connectionListeners); } keepAliveListener().ifPresent(listeners::add); - return new GraphQLWebsocketServlet(graphQLInvoker, invocationInputFactory, graphQLObjectMapper, - listeners); + return new GraphQLWebsocketServlet( + graphQLInvoker, invocationInputFactory, graphQLObjectMapper, listeners); } private Optional keepAliveListener() { if (apolloProperties.isKeepAliveEnabled()) { - return Optional.of(new KeepAliveSubscriptionConnectionListener( - Duration.ofSeconds(apolloProperties.getKeepAliveIntervalSeconds())) - ); + return Optional.of( + new KeepAliveSubscriptionConnectionListener( + Duration.ofSeconds(apolloProperties.getKeepAliveIntervalSeconds()))); } return Optional.empty(); } @@ -80,5 +85,4 @@ public ServerEndpointRegistration serverEndpointRegistration(GraphQLWebsocketSer public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } - } diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWsServerEndpointRegistration.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWsServerEndpointRegistration.java index b712fe95..17e901a3 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWsServerEndpointRegistration.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/GraphQLWsServerEndpointRegistration.java @@ -7,11 +7,9 @@ import org.springframework.context.Lifecycle; import org.springframework.web.socket.server.standard.ServerEndpointRegistration; -/** - * @author Andrew Potter - */ -public class GraphQLWsServerEndpointRegistration extends ServerEndpointRegistration implements - Lifecycle { +/** @author Andrew Potter */ +public class GraphQLWsServerEndpointRegistration extends ServerEndpointRegistration + implements Lifecycle { private final GraphQLWebsocketServlet servlet; @@ -21,8 +19,8 @@ public GraphQLWsServerEndpointRegistration(String path, GraphQLWebsocketServlet } @Override - public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, - HandshakeResponse response) { + public void modifyHandshake( + ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { super.modifyHandshake(sec, request, response); servlet.modifyHandshake(sec, request, response); } diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/OnSchemaOrSchemaProviderBean.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/OnSchemaOrSchemaProviderBean.java index b0aa92f7..8eb44f74 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/OnSchemaOrSchemaProviderBean.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/OnSchemaOrSchemaProviderBean.java @@ -12,12 +12,8 @@ public OnSchemaOrSchemaProviderBean() { } @ConditionalOnBean(GraphQLSchema.class) - static class OnSchema { - - } + static class OnSchema {} @ConditionalOnBean(GraphQLSchemaProvider.class) - static class OnSchemaProvider { - - } + static class OnSchemaProvider {} } diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/metrics/MetricsInstrumentation.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/metrics/MetricsInstrumentation.java index e962090d..959abfa6 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/metrics/MetricsInstrumentation.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/metrics/MetricsInstrumentation.java @@ -10,9 +10,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -/** - * @author Bruno Rodrigues - */ +/** @author Bruno Rodrigues */ public class MetricsInstrumentation extends TracingInstrumentation { private static final String QUERY_TIME_METRIC_NAME = "graphql.timer.query"; @@ -28,7 +26,8 @@ public class MetricsInstrumentation extends TracingInstrumentation { private static final String VALIDATION = "validation"; private static final String PARSING = "parsing"; private static final String RESOLVERS = "resolvers"; - private static final String TIMER_DESCRIPTION = "Timer that records the time to fetch the data by Operation Name"; + private static final String TIMER_DESCRIPTION = + "Timer that records the time to fetch the data by Operation Name"; private final MeterRegistry meterRegistry; private final boolean tracingEnabled; @@ -41,41 +40,44 @@ public MetricsInstrumentation(MeterRegistry meterRegistry, boolean tracingEnable public CompletableFuture instrumentExecutionResult( ExecutionResult executionResult, InstrumentationExecutionParameters parameters) { - if (executionResult.getExtensions() != null && executionResult.getExtensions() - .containsKey(TRACING)) { + if (executionResult.getExtensions() != null + && executionResult.getExtensions().containsKey(TRACING)) { - Map tracingData = (Map) executionResult.getExtensions() - .get(TRACING); + Map tracingData = + (Map) executionResult.getExtensions().get(TRACING); Timer executionTimer = buildQueryTimer(parameters.getOperation(), EXECUTION); executionTimer.record((long) tracingData.get(DURATION), TimeUnit.NANOSECONDS); - //These next 2 ifs might not run if the document is cached on the document provider - if (tracingData.containsKey(VALIDATION) && ((Map) tracingData - .get(VALIDATION)).containsKey(DURATION)) { + // These next 2 ifs might not run if the document is cached on the document provider + if (tracingData.containsKey(VALIDATION) + && ((Map) tracingData.get(VALIDATION)).containsKey(DURATION)) { Timer validationTimer = buildQueryTimer(parameters.getOperation(), VALIDATION); - validationTimer - .record((long) ((Map) tracingData.get(VALIDATION)).get(DURATION), - TimeUnit.NANOSECONDS); + validationTimer.record( + (long) ((Map) tracingData.get(VALIDATION)).get(DURATION), + TimeUnit.NANOSECONDS); } - if (tracingData.containsKey(PARSING) && ((Map) tracingData.get(PARSING)) - .containsKey(DURATION)) { + if (tracingData.containsKey(PARSING) + && ((Map) tracingData.get(PARSING)).containsKey(DURATION)) { Timer parsingTimer = buildQueryTimer(parameters.getOperation(), PARSING); - parsingTimer - .record((long) ((Map) tracingData.get(PARSING)).get(DURATION), - TimeUnit.NANOSECONDS); + parsingTimer.record( + (long) ((Map) tracingData.get(PARSING)).get(DURATION), + TimeUnit.NANOSECONDS); } if (((Map) tracingData.get(EXECUTION)).containsKey(RESOLVERS)) { - ((List>) ((Map) tracingData.get(EXECUTION)) - .get(RESOLVERS)).forEach(field -> { - - Timer fieldTimer = buildFieldTimer(parameters.getOperation(), RESOLVERS, - (String) field.get("parentType"), (String) field.get("fieldName")); - fieldTimer.record((long) field.get(DURATION), TimeUnit.NANOSECONDS); - - }); - + ((List>) + ((Map) tracingData.get(EXECUTION)).get(RESOLVERS)) + .forEach( + field -> { + Timer fieldTimer = + buildFieldTimer( + parameters.getOperation(), + RESOLVERS, + (String) field.get("parentType"), + (String) field.get("fieldName")); + fieldTimer.record((long) field.get(DURATION), TimeUnit.NANOSECONDS); + }); } if (!tracingEnabled) { @@ -94,8 +96,8 @@ private Timer buildQueryTimer(String operationName, String operation) { .register(meterRegistry); } - private Timer buildFieldTimer(String operationName, String operation, String parent, - String field) { + private Timer buildFieldTimer( + String operationName, String operation, String parent, String field) { return Timer.builder(RESOLVER_TIME_METRIC_NAME) .description(TIMER_DESCRIPTION) .tag(OPERATION_NAME_TAG, operationName != null ? operationName : UNKNOWN_OPERATION_NAME) diff --git a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/metrics/WebsocketMetrics.java b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/metrics/WebsocketMetrics.java index e39033fd..21e62403 100644 --- a/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/metrics/WebsocketMetrics.java +++ b/graphql-spring-boot-autoconfigure/src/main/java/graphql/kickstart/spring/web/boot/metrics/WebsocketMetrics.java @@ -7,14 +7,17 @@ public class WebsocketMetrics { public WebsocketMetrics(MeterRegistry meterRegistry, GraphQLWebsocketServlet websocketServlet) { - Gauge.builder("graphql.websocket.sessions", websocketServlet, - GraphQLWebsocketServlet::getSessionCount) + Gauge.builder( + "graphql.websocket.sessions", + websocketServlet, + GraphQLWebsocketServlet::getSessionCount) .description("Active websocket sessions available for subscriptions") .register(meterRegistry); - Gauge.builder("graphql.websocket.subscriptions", websocketServlet, - GraphQLWebsocketServlet::getSubscriptionCount) + Gauge.builder( + "graphql.websocket.subscriptions", + websocketServlet, + GraphQLWebsocketServlet::getSubscriptionCount) .description("Active websocket subscriptions") .register(meterRegistry); } - } diff --git a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/CorsTest.java b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/CorsTest.java index 847d933b..e4636861 100644 --- a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/CorsTest.java +++ b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/CorsTest.java @@ -26,11 +26,15 @@ @ExtendWith(SpringExtension.class) @AutoConfigureMockMvc @ImportAutoConfiguration({JacksonAutoConfiguration.class, GraphQLWebAutoConfiguration.class}) -@SpringBootTest(properties = {"debug=true", "graphql.servlet.mapping=/graphql", "graphql.servlet.cors.allowed-origins=https://trusted.com"}) +@SpringBootTest( + properties = { + "debug=true", + "graphql.servlet.mapping=/graphql", + "graphql.servlet.cors.allowed-origins=https://trusted.com" + }) class CorsTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test void evilDomain_shouldNotBeAllowed() throws Exception { @@ -45,8 +49,7 @@ private ResultActions performCorsPreflight(String origin) throws Exception { options("/graphql") .contentType(MediaType.APPLICATION_JSON) .header("Access-Control-Request-Method", "POST") - .header("Origin", origin) - ); + .header("Origin", origin)); } @Test @@ -64,12 +67,16 @@ static class MyTestConfiguration { @Bean public GraphQLSchema graphQLSchema() { return GraphQLSchema.newSchema() - .query(GraphQLObjectType.newObject().name("Query").field( - GraphQLFieldDefinition.newFieldDefinition() - .name("echo") - .type(GraphQLString) - .build()).build()).build(); + .query( + GraphQLObjectType.newObject() + .name("Query") + .field( + GraphQLFieldDefinition.newFieldDefinition() + .name("echo") + .type(GraphQLString) + .build()) + .build()) + .build(); } } - } diff --git a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/GraphQLErrorHandlerTest.java b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/GraphQLErrorHandlerTest.java index 82ddf106..1ea2c668 100644 --- a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/GraphQLErrorHandlerTest.java +++ b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/GraphQLErrorHandlerTest.java @@ -43,15 +43,16 @@ void illegalArgumentExceptionShouldBeHandledConcretely() { TestUtils.assertGraphQLError( gql, "query { illegalArgumentException }", - new ThrowableGraphQLError(new IllegalArgumentException("Some argument"), - "Custom illegal argument"), - objectMapper - ); + new ThrowableGraphQLError( + new IllegalArgumentException("Some argument"), "Custom illegal argument"), + objectMapper); } @Test void illegalStateExceptionShouldBeHandledByCatchAll() { - TestUtils.assertGraphQLError(gql, "query { illegalStateException }", + TestUtils.assertGraphQLError( + gql, + "query { illegalStateException }", new ThrowableGraphQLError(new IllegalStateException("Illegal state"), "Catch all handler"), objectMapper); } @@ -86,13 +87,13 @@ Query queryResolver() { @Bean GraphQLSchema schema() { - SchemaParser schemaParser = SchemaParser.newParser() - .file("graphql/error-handler-test.graphql") - .resolvers(queryResolver()) - .build(); + SchemaParser schemaParser = + SchemaParser.newParser() + .file("graphql/error-handler-test.graphql") + .resolvers(queryResolver()) + .build(); return schemaParser.makeExecutableSchema(); } } - } } diff --git a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/GraphQLServletPropertiesTest.java b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/GraphQLServletPropertiesTest.java index 7c7f5f24..ed355d65 100644 --- a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/GraphQLServletPropertiesTest.java +++ b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/GraphQLServletPropertiesTest.java @@ -7,16 +7,17 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @EnableConfigurationProperties(GraphQLServletProperties.class) -@SpringBootTest(properties = {"graphql.servlet.mapping=/test", - "graphql.servlet.contextSetting=PER_REQUEST_WITH_INSTRUMENTATION"}) +@SpringBootTest( + properties = { + "graphql.servlet.mapping=/test", + "graphql.servlet.contextSetting=PER_REQUEST_WITH_INSTRUMENTATION" + }) class GraphQLServletPropertiesTest { @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") diff --git a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/TestAutoConfiguration.java b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/TestAutoConfiguration.java index df219a9c..28cf15ec 100644 --- a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/TestAutoConfiguration.java +++ b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/TestAutoConfiguration.java @@ -1,10 +1,6 @@ package graphql.kickstart.spring.web.boot; import org.springframework.boot.SpringBootConfiguration; -import org.springframework.context.annotation.Import; @SpringBootConfiguration -public class TestAutoConfiguration { - - -} +public class TestAutoConfiguration {} diff --git a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/AbstractAutoConfigurationTest.java b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/AbstractAutoConfigurationTest.java index bc08699c..a1a45d50 100644 --- a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/AbstractAutoConfigurationTest.java +++ b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/AbstractAutoConfigurationTest.java @@ -15,9 +15,7 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ public abstract class AbstractAutoConfigurationTest { private final Class contextClass; @@ -29,8 +27,8 @@ protected AbstractAutoConfigurationTest(Class autoConfiguration) { this(AnnotationConfigApplicationContext.class, autoConfiguration); } - protected AbstractAutoConfigurationTest(Class contextClass, - Class autoConfiguration) { + protected AbstractAutoConfigurationTest( + Class contextClass, Class autoConfiguration) { assert AnnotationConfigRegistry.class.isAssignableFrom(contextClass); this.contextClass = contextClass; this.autoConfiguration = autoConfiguration; @@ -61,8 +59,9 @@ protected void load(Class config, String... environment) { loadServletContext(); getContext().refresh(); - getContext().publishEvent( - new ApplicationReadyEvent(new SpringApplication(), new String[0], getContext())); + getContext() + .publishEvent( + new ApplicationReadyEvent(new SpringApplication(), new String[0], getContext())); } private void loadServletContext() { diff --git a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/GraphQLServletPropertiesTest.java b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/GraphQLServletPropertiesTest.java index e18a141a..a19532ae 100644 --- a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/GraphQLServletPropertiesTest.java +++ b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/GraphQLServletPropertiesTest.java @@ -5,9 +5,7 @@ import graphql.kickstart.spring.web.boot.GraphQLServletProperties; import org.junit.jupiter.api.Test; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ class GraphQLServletPropertiesTest { @Test @@ -31,8 +29,9 @@ private void verifyCorsMapping(String mapping) { servletProperties.setMapping(mapping); assertThat(servletProperties.getCorsMapping()) - .as(String.format("Expected mapping '%s' to return cors mapping '%s'", mapping, - "/graphql/**")) + .as( + String.format( + "Expected mapping '%s' to return cors mapping '%s'", mapping, "/graphql/**")) .isEqualTo("/graphql/**"); } @@ -41,8 +40,9 @@ private void verifyServletMapping(String mapping) { servletProperties.setMapping(mapping); assertThat(servletProperties.getServletMapping()) - .as(String - .format("Expected mapping '%s' to return servlet mapping '%s'", mapping, "/graphql/*")) + .as( + String.format( + "Expected mapping '%s' to return servlet mapping '%s'", mapping, "/graphql/*")) .isEqualTo("/graphql/*"); } } diff --git a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/extendedscalars/ExtendedScalarAutoConfigurationTest.java b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/extendedscalars/ExtendedScalarAutoConfigurationTest.java index bcbfecc5..6ad2cefb 100644 --- a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/extendedscalars/ExtendedScalarAutoConfigurationTest.java +++ b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/extendedscalars/ExtendedScalarAutoConfigurationTest.java @@ -1,7 +1,10 @@ package graphql.kickstart.spring.web.boot.test.extendedscalars; +import static org.assertj.core.api.Assertions.assertThat; + import graphql.scalars.ExtendedScalars; import graphql.schema.GraphQLScalarType; +import java.util.AbstractMap; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -10,29 +13,24 @@ import org.springframework.context.ApplicationContext; import org.springframework.test.context.TestPropertySource; -import java.util.AbstractMap; - -import static org.assertj.core.api.Assertions.assertThat; - @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, - classes = ExtendedScalarAutoConfigurationTest.ExtendedScalarsTestApplication.class -) + classes = ExtendedScalarAutoConfigurationTest.ExtendedScalarsTestApplication.class) @TestPropertySource(properties = "graphql.extended-scalars=BigDecimal") @DisplayName("Testing extended scalars auto configuration") public class ExtendedScalarAutoConfigurationTest { - @Autowired - private ApplicationContext applicationContext; + @Autowired private ApplicationContext applicationContext; - @Test - @DisplayName("The extended scalars initializer should be properly picked up by Spring auto configuration.") - void testAutoConfiguration() { - assertThat(applicationContext.getBeansOfType(GraphQLScalarType.class)) - .containsOnly(new AbstractMap.SimpleEntry<>("BigDecimal", ExtendedScalars.GraphQLBigDecimal)); - } + @Test + @DisplayName( + "The extended scalars initializer should be properly picked up by Spring auto configuration.") + void testAutoConfiguration() { + assertThat(applicationContext.getBeansOfType(GraphQLScalarType.class)) + .containsOnly( + new AbstractMap.SimpleEntry<>("BigDecimal", ExtendedScalars.GraphQLBigDecimal)); + } - @SpringBootApplication - public static class ExtendedScalarsTestApplication { - } + @SpringBootApplication + public static class ExtendedScalarsTestApplication {} } diff --git a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/extendedscalars/ExtendedScalarsTest.java b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/extendedscalars/ExtendedScalarsTest.java index 782210e0..7a1fde00 100644 --- a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/extendedscalars/ExtendedScalarsTest.java +++ b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/extendedscalars/ExtendedScalarsTest.java @@ -1,8 +1,13 @@ package graphql.kickstart.spring.web.boot.test.extendedscalars; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + import graphql.kickstart.spring.web.boot.GraphQLExtendedScalarsInitializer; import graphql.scalars.ExtendedScalars; import graphql.schema.GraphQLScalarType; +import java.util.AbstractMap; +import java.util.Collections; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.SpringApplication; @@ -12,64 +17,64 @@ import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.StandardEnvironment; -import java.util.AbstractMap; -import java.util.Collections; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - @DisplayName("Testing extended scalars configuration") public class ExtendedScalarsTest { - @Test - @DisplayName("Should throw exception at context initialization when invalid extended scalar name is provided.") - void shouldThrowErrorOnStartupIfExtendedScalarDoesNotExists() { - // GIVEN - final SpringApplication application = setupTestApplication("Long,Short,Datee,BadDecimal"); - // THEN - assertThatExceptionOfType(ApplicationContextException.class) - .isThrownBy(application::run) - .withMessage("Invalid extended scalar name(s) found: BadDecimal, Datee. Valid names are: BigDecimal, " + - "BigInteger, Byte, Char, Date, DateTime, JSON, Locale, Long, NegativeFloat, NegativeInt, " + - "NonNegativeFloat, NonNegativeInt, NonPositiveFloat, NonPositiveInt, Object, PositiveFloat, " + - "PositiveInt, Short, Time, Url."); - } + @Test + @DisplayName( + "Should throw exception at context initialization when invalid extended scalar name is provided.") + void shouldThrowErrorOnStartupIfExtendedScalarDoesNotExists() { + // GIVEN + final SpringApplication application = setupTestApplication("Long,Short,Datee,BadDecimal"); + // THEN + assertThatExceptionOfType(ApplicationContextException.class) + .isThrownBy(application::run) + .withMessage( + "Invalid extended scalar name(s) found: BadDecimal, Datee. Valid names are: BigDecimal, " + + "BigInteger, Byte, Char, Date, DateTime, JSON, Locale, Long, NegativeFloat, NegativeInt, " + + "NonNegativeFloat, NonNegativeInt, NonPositiveFloat, NonPositiveInt, Object, PositiveFloat, " + + "PositiveInt, Short, Time, Url."); + } - @Test - @DisplayName("Should not create any extended scalars by default.") - void shouldNotDeclareAnyExtendedScalarsByDefault() { - // GIVEN - final SpringApplication application = setupTestApplication(null); - // WHEN - final ConfigurableApplicationContext context = application.run(); - // THEN - assertThat(context.getBeansOfType(GraphQLScalarType.class)).isEmpty(); - } + @Test + @DisplayName("Should not create any extended scalars by default.") + void shouldNotDeclareAnyExtendedScalarsByDefault() { + // GIVEN + final SpringApplication application = setupTestApplication(null); + // WHEN + final ConfigurableApplicationContext context = application.run(); + // THEN + assertThat(context.getBeansOfType(GraphQLScalarType.class)).isEmpty(); + } - @Test - @DisplayName("Should declare the configured extended scalars.") - void shouldDeclareTheConfiguredScalars() { - // GIVEN - final SpringApplication application = setupTestApplication("Long,Short,BigDecimal,Date"); - // WHEN - final ConfigurableApplicationContext context = application.run(); - // THEN - assertThat(context.getBeansOfType(GraphQLScalarType.class)) - .containsOnly( - new AbstractMap.SimpleEntry<>("Long", ExtendedScalars.GraphQLLong), - new AbstractMap.SimpleEntry<>("Short", ExtendedScalars.GraphQLShort), - new AbstractMap.SimpleEntry<>("BigDecimal", ExtendedScalars.GraphQLBigDecimal), - new AbstractMap.SimpleEntry<>("Date", ExtendedScalars.Date) - ); - } + @Test + @DisplayName("Should declare the configured extended scalars.") + void shouldDeclareTheConfiguredScalars() { + // GIVEN + final SpringApplication application = setupTestApplication("Long,Short,BigDecimal,Date"); + // WHEN + final ConfigurableApplicationContext context = application.run(); + // THEN + assertThat(context.getBeansOfType(GraphQLScalarType.class)) + .containsOnly( + new AbstractMap.SimpleEntry<>("Long", ExtendedScalars.GraphQLLong), + new AbstractMap.SimpleEntry<>("Short", ExtendedScalars.GraphQLShort), + new AbstractMap.SimpleEntry<>("BigDecimal", ExtendedScalars.GraphQLBigDecimal), + new AbstractMap.SimpleEntry<>("Date", ExtendedScalars.Date)); + } - private SpringApplication setupTestApplication(final String extendedScalarValue) { - final StandardEnvironment standardEnvironment = new StandardEnvironment(); - standardEnvironment.getPropertySources().addFirst(new MapPropertySource("testProperties", - Collections.singletonMap("graphql.extended-scalars", extendedScalarValue))); - final SpringApplication application = new SpringApplication(GraphQLExtendedScalarsInitializer.class); - application.setWebApplicationType(WebApplicationType.NONE); - application.setEnvironment(standardEnvironment); - return application; - } + private SpringApplication setupTestApplication(final String extendedScalarValue) { + final StandardEnvironment standardEnvironment = new StandardEnvironment(); + standardEnvironment + .getPropertySources() + .addFirst( + new MapPropertySource( + "testProperties", + Collections.singletonMap("graphql.extended-scalars", extendedScalarValue))); + final SpringApplication application = + new SpringApplication(GraphQLExtendedScalarsInitializer.class); + application.setWebApplicationType(WebApplicationType.NONE); + application.setEnvironment(standardEnvironment); + return application; + } } diff --git a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/instrumentation/GraphQLInstrumentationAutoConfigurationTest.java b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/instrumentation/GraphQLInstrumentationAutoConfigurationTest.java index 49f31207..ce6295d8 100644 --- a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/instrumentation/GraphQLInstrumentationAutoConfigurationTest.java +++ b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/instrumentation/GraphQLInstrumentationAutoConfigurationTest.java @@ -14,7 +14,6 @@ import graphql.kickstart.spring.web.boot.test.AbstractAutoConfigurationTest; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLScalarType; import graphql.schema.GraphQLSchema; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -25,14 +24,12 @@ import org.springframework.context.support.AbstractApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -/** - * @author Marcel Overdijk - */ +/** @author Marcel Overdijk */ class GraphQLInstrumentationAutoConfigurationTest extends AbstractAutoConfigurationTest { public GraphQLInstrumentationAutoConfigurationTest() { - super(AnnotationConfigWebApplicationContext.class, - GraphQLInstrumentationAutoConfiguration.class); + super( + AnnotationConfigWebApplicationContext.class, GraphQLInstrumentationAutoConfiguration.class); } @Test @@ -67,7 +64,9 @@ void maxQueryDepthEnabled() { @Test void actuatorMetricsEnabledAndTracingEnabled() { - load(DefaultConfiguration.class, "graphql.servlet.tracing-enabled=true", + load( + DefaultConfiguration.class, + "graphql.servlet.tracing-enabled=true", "graphql.servlet.actuator-metrics=true"); AbstractApplicationContext context = getContext(); @@ -78,7 +77,9 @@ void actuatorMetricsEnabledAndTracingEnabled() { @Test void tracingInstrumentationDisabledAndMetricsEnabled() { - load(DefaultConfiguration.class, "graphql.servlet.tracing-enabled=false", + load( + DefaultConfiguration.class, + "graphql.servlet.tracing-enabled=false", "graphql.servlet.actuator-metrics=true"); assertThat(this.getContext().getBean(MetricsInstrumentation.class)).isNotNull(); @@ -87,7 +88,9 @@ void tracingInstrumentationDisabledAndMetricsEnabled() { @Test void tracingMetricsWithTracingDisabled() { - load(DefaultConfiguration.class, "graphql.servlet.tracing-enabled=metrics-only", + load( + DefaultConfiguration.class, + "graphql.servlet.tracing-enabled=metrics-only", "graphql.servlet.actuator-metrics=true"); assertThat(this.getContext().getBean("metricsInstrumentation")).isNotNull(); @@ -104,7 +107,9 @@ void actuatorMetricsEnabled() { @Test void tracingInstrumentationEnabledAndMetricsDisabled() { - load(DefaultConfiguration.class, "graphql.servlet.tracing-enabled=true", + load( + DefaultConfiguration.class, + "graphql.servlet.tracing-enabled=true", "graphql.servlet.actuator-metrics=false"); AbstractApplicationContext context = getContext(); @@ -115,7 +120,9 @@ void tracingInstrumentationEnabledAndMetricsDisabled() { @Test void tracingInstrumentationDisabledAndMetricsDisabled() { - load(DefaultConfiguration.class, "graphql.servlet.tracing-enabled=false", + load( + DefaultConfiguration.class, + "graphql.servlet.tracing-enabled=false", "graphql.servlet.actuator-metrics=false"); AbstractApplicationContext context = getContext(); @@ -149,8 +156,8 @@ GraphQLSchema schema() { GraphQLFieldDefinition.newFieldDefinition() .name("echo") .type(GraphQLString) - .build() - ).build()) + .build()) + .build()) .build(); } @@ -158,6 +165,5 @@ GraphQLSchema schema() { MeterRegistry meterRegistry() { return new SimpleMeterRegistry(); } - } } diff --git a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/web/GraphQLWebAutoConfigurationTest.java b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/web/GraphQLWebAutoConfigurationTest.java index 7f2970db..4c85c660 100644 --- a/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/web/GraphQLWebAutoConfigurationTest.java +++ b/graphql-spring-boot-autoconfigure/src/test/java/graphql/kickstart/spring/web/boot/test/web/GraphQLWebAutoConfigurationTest.java @@ -21,17 +21,21 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -/** - * @author oEmbedler Inc. - */ +/** @author oEmbedler Inc. */ class GraphQLWebAutoConfigurationTest extends AbstractAutoConfigurationTest { - private static final GraphQLSchema SCHEMA = GraphQLSchema.newSchema() - .query(GraphQLObjectType.newObject().name("Query").field( - GraphQLFieldDefinition.newFieldDefinition() - .name("echo") - .type(GraphQLString) - .build()).build()).build(); + private static final GraphQLSchema SCHEMA = + GraphQLSchema.newSchema() + .query( + GraphQLObjectType.newObject() + .name("Query") + .field( + GraphQLFieldDefinition.newFieldDefinition() + .name("echo") + .type(GraphQLString) + .build()) + .build()) + .build(); public GraphQLWebAutoConfigurationTest() { super(AnnotationConfigWebApplicationContext.class, GraphQLWebAutoConfiguration.class); @@ -100,7 +104,6 @@ static class SimpleConfiguration { GraphQLSchema schema() { return SCHEMA; } - } @Configuration @@ -176,5 +179,4 @@ GraphQLSchemaServletProvider schemaProvider() { return new DefaultGraphQLSchemaServletProvider(SCHEMA); } } - } diff --git a/graphql-spring-boot-test-autoconfigure/src/main/java/com/graphql/spring/boot/test/GraphQLTest.java b/graphql-spring-boot-test-autoconfigure/src/main/java/com/graphql/spring/boot/test/GraphQLTest.java index 6149f341..0636eae1 100644 --- a/graphql-spring-boot-test-autoconfigure/src/main/java/com/graphql/spring/boot/test/GraphQLTest.java +++ b/graphql-spring-boot-test-autoconfigure/src/main/java/com/graphql/spring/boot/test/GraphQLTest.java @@ -48,30 +48,32 @@ import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** - * Annotation that can be specified on a test class in combination with - * @RunWith(SpringRunner.class) for running tests that focus only on - * GraphQL components. - *

- * Provides the following features over the regular Spring TestContext Framework: + * Annotation that can be specified on a test class for running tests that focus + * only on GraphQL components. + * + *

Provides the following features over the regular Spring TestContext + * Framework: + * *

    - *
  • By default a fully running web server will be started listening on a - * {@link org.springframework.boot.test.context.SpringBootTest.WebEnvironment#RANDOM_PORT random} port.
  • - *
  • Disables full auto-configuration and instead apply only configuration relevant to - * GraphQL tests (i.e. beans required to create the GraphQL servlet but not {@code @Component}, - * {@code @Service} or {@code @Repository} beans). See {@link #includeFilters()} for a complete list of classes - * that are included.
  • - *
  • Sets the active profile to test.
  • - *
  • Registers a {@link com.graphql.spring.boot.test.GraphQLTestTemplate GraphQLTestTemplate} bean for use - * in GraphQL tests that are using a fully running web server.
  • - *
  • Typically {@code GraphQLTest} is used in combination with - * {@link org.springframework.boot.test.mock.mockito.MockBean @MockBean} or - * {@link org.springframework.context.annotation.Import @Import} to create any collaborators required by your - * {@code GraphQLResolver} beans.
  • + *
  • By default a fully running web server will be started listening on a {@link + * org.springframework.boot.test.context.SpringBootTest.WebEnvironment#RANDOM_PORT random} + * port. + *
  • Disables full auto-configuration and instead apply only configuration relevant to GraphQL + * tests (i.e. beans required to create the GraphQL servlet but not {@code @Component}, + * {@code @Service} or {@code @Repository} beans). See {@link #includeFilters()} for a + * complete list of classes that are included. + *
  • Sets the active profile to test. + *
  • Registers a {@link com.graphql.spring.boot.test.GraphQLTestTemplate GraphQLTestTemplate} + * bean for use in GraphQL tests that are using a fully running web server. + *
  • Typically {@code GraphQLTest} is used in combination with {@link + * org.springframework.boot.test.mock.mockito.MockBean @MockBean} or {@link + * org.springframework.context.annotation.Import @Import} to create any collaborators required + * by your {@code GraphQLResolver} beans. *
- *

- * If you are looking to load your full application configuration and use - * {@link com.graphql.spring.boot.test.GraphQLTestTemplate GraphQLTestTemplate} you should consider - * {@link SpringBootTest @SpringBootTest} rather than this annotation. + * + *

If you are looking to load your full application configuration and use {@link + * com.graphql.spring.boot.test.GraphQLTestTemplate GraphQLTestTemplate} you should consider {@link + * SpringBootTest @SpringBootTest} rather than this annotation. * * @author Michiel Oliemans * @since 5.0.2 @@ -87,42 +89,34 @@ String[] value() default {}; - @AliasFor( - annotation = ActiveProfiles.class - ) + @AliasFor(annotation = ActiveProfiles.class) String[] profiles() default {"test"}; - @AliasFor( - annotation = SpringBootTest.class - ) + @AliasFor(annotation = SpringBootTest.class) SpringBootTest.WebEnvironment webEnvironment() default SpringBootTest.WebEnvironment.RANDOM_PORT; - @AliasFor( - annotation = ImportAutoConfiguration.class - ) + @AliasFor(annotation = ImportAutoConfiguration.class) Class[] classes() default { - GraphQLInstrumentationAutoConfiguration.class, - ServletWebServerFactoryAutoConfiguration.class, - GraphQLJavaToolsAutoConfiguration.class, - GraphQLWebAutoConfiguration.class, - GraphQLTestAutoConfiguration.class, - PropertySourcesPlaceholderConfigurer.class, - WebSocketServletAutoConfiguration.class, - MetricsAutoConfiguration.class, - SimpleMetricsExportAutoConfiguration.class, - JacksonAutoConfiguration.class + GraphQLInstrumentationAutoConfiguration.class, + ServletWebServerFactoryAutoConfiguration.class, + GraphQLJavaToolsAutoConfiguration.class, + GraphQLWebAutoConfiguration.class, + GraphQLTestAutoConfiguration.class, + PropertySourcesPlaceholderConfigurer.class, + WebSocketServletAutoConfiguration.class, + MetricsAutoConfiguration.class, + SimpleMetricsExportAutoConfiguration.class, + JacksonAutoConfiguration.class }; - @AliasFor( - annotation = ComponentScan.class - ) + @AliasFor(annotation = ComponentScan.class) boolean useDefaultFilters() default false; - @AliasFor( - annotation = ComponentScan.class - ) + @AliasFor(annotation = ComponentScan.class) ComponentScan.Filter[] includeFilters() default { - @ComponentScan.Filter(type = ASSIGNABLE_TYPE, classes = { + @ComponentScan.Filter( + type = ASSIGNABLE_TYPE, + classes = { SchemaParser.class, GraphQLResolver.class, SchemaParserDictionary.class, @@ -148,7 +142,6 @@ ComponentScan.Filter[] includeFilters() default { GraphQLWebsocketServlet.class, ServerEndpointExporter.class, MultipartConfigElement.class - }) + }) }; - } diff --git a/graphql-spring-boot-test-autoconfigure/src/main/java/com/graphql/spring/boot/test/GraphQLTestAutoConfiguration.java b/graphql-spring-boot-test-autoconfigure/src/main/java/com/graphql/spring/boot/test/GraphQLTestAutoConfiguration.java index ae9fee67..6815582b 100644 --- a/graphql-spring-boot-test-autoconfigure/src/main/java/com/graphql/spring/boot/test/GraphQLTestAutoConfiguration.java +++ b/graphql-spring-boot-test-autoconfigure/src/main/java/com/graphql/spring/boot/test/GraphQLTestAutoConfiguration.java @@ -13,7 +13,10 @@ @Configuration @ConditionalOnWebApplication -@ConditionalOnProperty(value = "graphql.servlet.enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty( + value = "graphql.servlet.enabled", + havingValue = "true", + matchIfMissing = true) public class GraphQLTestAutoConfiguration { @Bean @@ -22,8 +25,7 @@ public GraphQLTestTemplate graphQLTestUtils( final ResourceLoader resourceLoader, final TestRestTemplate restTemplate, @Value("${graphql.servlet.mapping:/graphql}") final String graphqlMapping, - final ObjectMapper objectMapper - ) { + final ObjectMapper objectMapper) { return new GraphQLTestTemplate(resourceLoader, restTemplate, graphqlMapping, objectMapper); } @@ -32,9 +34,8 @@ public GraphQLTestTemplate graphQLTestUtils( public GraphQLTestSubscription graphQLTestSubscription( final Environment environment, final ObjectMapper objectMapper, - @Value("${graphql.servlet.subscriptions.websocket.path:subscriptions}") final String subscriptionPath - ) { + @Value("${graphql.servlet.subscriptions.websocket.path:subscriptions}") + final String subscriptionPath) { return new GraphQLTestSubscription(environment, objectMapper, subscriptionPath); } - } diff --git a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestAutoConfigurationTestBase.java b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestAutoConfigurationTestBase.java index 5f0ce2ab..b59213b2 100644 --- a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestAutoConfigurationTestBase.java +++ b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestAutoConfigurationTestBase.java @@ -10,26 +10,31 @@ public class GraphQLTestAutoConfigurationTestBase { static final String FOO = "foo"; - @Autowired - ApplicationContext applicationContext; + @Autowired ApplicationContext applicationContext; void assertThatTestSubscriptionWorksCorrectly() { // GIVEN - final GraphQLTestSubscription testSubscription = applicationContext - .getBean(GraphQLTestSubscription.class); + final GraphQLTestSubscription testSubscription = + applicationContext.getBean(GraphQLTestSubscription.class); // WHEN - THEN - testSubscription.start("test-subscription.graphql") + testSubscription + .start("test-subscription.graphql") .awaitAndGetNextResponse(1000) .assertThatNoErrorsArePresent() - .assertThatField("$.data.testSubscription").asString().isEqualTo(FOO); + .assertThatField("$.data.testSubscription") + .asString() + .isEqualTo(FOO); } void assertThatTestTemplateAutoConfigurationWorksCorrectly() throws IOException { // GIVEN final GraphQLTestTemplate testTemplate = applicationContext.getBean(GraphQLTestTemplate.class); // WHEN - THEN - testTemplate.postForResource("test-query.graphql") + testTemplate + .postForResource("test-query.graphql") .assertThatNoErrorsArePresent() - .assertThatField("$.data.testQuery").asString().isEqualTo(FOO); + .assertThatField("$.data.testQuery") + .asString() + .isEqualTo(FOO); } } diff --git a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAutoConfigurationCustomConfigTest.java b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAutoConfigurationCustomConfigTest.java index ba24fc14..63820a21 100644 --- a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAutoConfigurationCustomConfigTest.java +++ b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAutoConfigurationCustomConfigTest.java @@ -8,17 +8,18 @@ import org.springframework.test.util.ReflectionTestUtils; @ActiveProfiles({"test", "custom-subscription-path"}) -@DisplayName("Testing the auto-configuration of the GraphQLTestSubscription bean / custom subscription endpoint.") -class GraphQLTestSubscriptionAutoConfigurationCustomConfigTest extends - GraphQLTestAutoConfigurationTestBase { +@DisplayName( + "Testing the auto-configuration of the GraphQLTestSubscription bean / custom subscription endpoint.") +class GraphQLTestSubscriptionAutoConfigurationCustomConfigTest + extends GraphQLTestAutoConfigurationTestBase { @Test @DisplayName("Should provide a GraphQLTestTemplate bean.") void shouldProvideGraphQLTestSubscriptionBean() { assertThatTestSubscriptionWorksCorrectly(); assertThat( - ReflectionTestUtils.getField(applicationContext.getBean(GraphQLTestSubscription.class), - "subscriptionPath")) + ReflectionTestUtils.getField( + applicationContext.getBean(GraphQLTestSubscription.class), "subscriptionPath")) .as("Should use the configured subscription path.") .isEqualTo("/myCustomPath"); } diff --git a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAutoConfigurationDefaultConfigTest.java b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAutoConfigurationDefaultConfigTest.java index c78ba904..33212ecd 100644 --- a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAutoConfigurationDefaultConfigTest.java +++ b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAutoConfigurationDefaultConfigTest.java @@ -3,9 +3,10 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -@DisplayName("Testing the auto-configuration of the GraphQLTestSubscription bean / default settings.") -class GraphQLTestSubscriptionAutoConfigurationDefaultConfigTest extends - GraphQLTestAutoConfigurationTestBase { +@DisplayName( + "Testing the auto-configuration of the GraphQLTestSubscription bean / default settings.") +class GraphQLTestSubscriptionAutoConfigurationDefaultConfigTest + extends GraphQLTestAutoConfigurationTestBase { @Test @DisplayName("Should provide a GraphQLTestTemplate bean.") diff --git a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateAutoConfigurationCustomConfigTest.java b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateAutoConfigurationCustomConfigTest.java index 1fb92da8..78dc88c6 100644 --- a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateAutoConfigurationCustomConfigTest.java +++ b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateAutoConfigurationCustomConfigTest.java @@ -9,16 +9,18 @@ import org.springframework.test.util.ReflectionTestUtils; @ActiveProfiles({"test", "custom-servlet-mapping"}) -@DisplayName("Testing auto-configuration of the GraphQLTestTemplate bean / custom servlet endpoint.") -class GraphQLTestTemplateAutoConfigurationCustomConfigTest extends - GraphQLTestAutoConfigurationTestBase { +@DisplayName( + "Testing auto-configuration of the GraphQLTestTemplate bean / custom servlet endpoint.") +class GraphQLTestTemplateAutoConfigurationCustomConfigTest + extends GraphQLTestAutoConfigurationTestBase { @Test @DisplayName("GraphQLTestTemplate bean should work properly.") void shouldProvideGraphQLTestTemplateBean() throws IOException { assertThatTestTemplateAutoConfigurationWorksCorrectly(); - assertThat(ReflectionTestUtils.getField(applicationContext.getBean(GraphQLTestTemplate.class), - "graphqlMapping")) + assertThat( + ReflectionTestUtils.getField( + applicationContext.getBean(GraphQLTestTemplate.class), "graphqlMapping")) .as("Should use the configured servlet path.") .isEqualTo("/myCustomGraphQLEndpoint"); } diff --git a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateAutoConfigurationDefaultConfigTest.java b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateAutoConfigurationDefaultConfigTest.java index bacb50c4..6fe999a1 100644 --- a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateAutoConfigurationDefaultConfigTest.java +++ b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateAutoConfigurationDefaultConfigTest.java @@ -4,9 +4,10 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -@DisplayName("Testing auto-configuration of the GraphQLTestTemplate bean / default servlet endpoint.") -class GraphQLTestTemplateAutoConfigurationDefaultConfigTest extends - GraphQLTestAutoConfigurationTestBase { +@DisplayName( + "Testing auto-configuration of the GraphQLTestTemplate bean / default servlet endpoint.") +class GraphQLTestTemplateAutoConfigurationDefaultConfigTest + extends GraphQLTestAutoConfigurationTestBase { @Test @DisplayName("GraphQLTestTemplate bean should work properly.") diff --git a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/TestApplication.java b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/TestApplication.java index 8c3e177c..02a89a21 100644 --- a/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/TestApplication.java +++ b/graphql-spring-boot-test-autoconfigure/src/test/java/com/graphql/spring/boot/test/TestApplication.java @@ -10,4 +10,3 @@ public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } } - diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLResponse.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLResponse.java index 17fa8ae1..e6b0f164 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLResponse.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLResponse.java @@ -26,7 +26,8 @@ public GraphQLResponse(ResponseEntity responseEntity, ObjectMapper objec this.responseEntity = Objects.requireNonNull(responseEntity); this.mapper = Objects.requireNonNull(objectMapper); - Objects.requireNonNull(responseEntity.getBody(), + Objects.requireNonNull( + responseEntity.getBody(), () -> "Body is empty with status " + responseEntity.getStatusCodeValue()); context = JsonPath.parse(responseEntity.getBody()); } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestError.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestError.java index a143cbef..1fd5f52f 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestError.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestError.java @@ -18,9 +18,7 @@ import lombok.NoArgsConstructor; import org.springframework.util.NumberUtils; -/** - * An implementation of the {@link GraphQLError} interface for testing purposes. - */ +/** An implementation of the {@link GraphQLError} interface for testing purposes. */ @Data @Builder @NoArgsConstructor @@ -28,39 +26,45 @@ public class GraphQLTestError implements GraphQLError { private String message; + @JsonTypeInfo(defaultImpl = JacksonFriendlySourceLocation.class, use = Id.NAME) private List locations; + @JsonTypeInfo(defaultImpl = ErrorType.class, use = Id.NAME) private transient ErrorClassification errorType; + private transient List path; private transient Map extensions; @Override public String toString() { final StringBuilder sb = new StringBuilder(); - sb.append(Optional.ofNullable(errorType).map(ErrorClassification::toString) - .orElse("")); + sb.append( + Optional.ofNullable(errorType) + .map(ErrorClassification::toString) + .orElse("")); sb.append(": "); sb.append(Optional.ofNullable(message).orElse("")); if (nonNull(locations) && !locations.isEmpty()) { sb.append(" at line "); locations.forEach( - location -> sb - .append(location.getLine()) - .append(", column ") - .append(location.getColumn()).append(" in ") - .append(Optional.ofNullable(location.getSourceName()) - .orElse("unnamed/unspecified source")) - ); + location -> + sb.append(location.getLine()) + .append(", column ") + .append(location.getColumn()) + .append(" in ") + .append( + Optional.ofNullable(location.getSourceName()) + .orElse("unnamed/unspecified source"))); } if (nonNull(path) && !path.isEmpty()) { sb.append(". Selection path: "); - sb.append(path.stream() - .map(Object::toString) - .map(this::toNumericIndexIfPossible) - .collect(Collectors.joining("/")) - .replace("/[", "[") - ); + sb.append( + path.stream() + .map(Object::toString) + .map(this::toNumericIndexIfPossible) + .collect(Collectors.joining("/")) + .replace("/[", "[")); } return sb.toString(); } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestSubscription.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestSubscription.java index 253ec031..d05fb7a9 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestSubscription.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestSubscription.java @@ -42,15 +42,13 @@ import org.springframework.web.util.DefaultUriBuilderFactory; import org.springframework.web.util.UriBuilderFactory; -/** - * Helper object to test GraphQL subscriptions. - */ +/** Helper object to test GraphQL subscriptions. */ @RequiredArgsConstructor @Slf4j public class GraphQLTestSubscription { - private static final WebSocketContainer WEB_SOCKET_CONTAINER = ContainerProvider - .getWebSocketContainer(); + private static final WebSocketContainer WEB_SOCKET_CONTAINER = + ContainerProvider.getWebSocketContainer(); private static final int ACKNOWLEDGEMENT_AND_CONNECTION_TIMEOUT = 60000; private static final AtomicInteger ID_COUNTER = new AtomicInteger(1); private static final UriBuilderFactory URI_BUILDER_FACTORY = new DefaultUriBuilderFactory(); @@ -59,11 +57,9 @@ public class GraphQLTestSubscription { private final Environment environment; private final ObjectMapper objectMapper; private final String subscriptionPath; - @Getter - private Session session; - private SubscriptionState state = SubscriptionState.builder() - .id(ID_COUNTER.incrementAndGet()) - .build(); + @Getter private Session session; + private SubscriptionState state = + SubscriptionState.builder().id(ID_COUNTER.incrementAndGet()).build(); public boolean isInitialized() { return state.isInitialized(); @@ -124,7 +120,7 @@ public GraphQLTestSubscription init(@Nullable final Object payload) { * Sends the "start" message to the GraphQL server. * * @param graphQLResource the GraphQL resource, which contains the query for the subscription - * start payload. The start message will be sent without variables. + * start payload. The start message will be sent without variables. * @return self reference */ public GraphQLTestSubscription start(@NonNull final String graphQLResource) { @@ -136,12 +132,12 @@ public GraphQLTestSubscription start(@NonNull final String graphQLResource) { * Sends the "start" message to the GraphQL Subscription. * * @param graphQLResource the GraphQL resource, which contains the query for the subscription - * start payload. + * start payload. * @param variables the variables needed for the query to be evaluated. * @return self reference */ - public GraphQLTestSubscription start(@NonNull final String graphQLResource, - @Nullable final Object variables) { + public GraphQLTestSubscription start( + @NonNull final String graphQLResource, @Nullable final Object variables) { if (!isInitialized()) { init(); } @@ -207,7 +203,7 @@ public void reset() { * stopped after receiving the message (or timeout). * * @param timeout timeout in milliseconds. Test will fail if no message received from the - * subscription until the timeout expires. + * subscription until the timeout expires. * @return The received response. */ public GraphQLResponse awaitAndGetNextResponse(final int timeout) { @@ -218,9 +214,9 @@ public GraphQLResponse awaitAndGetNextResponse(final int timeout) { * Awaits and returns the next response received from the subscription. * * @param timeout timeout in milliseconds. Test will fail if no message received from the - * subscription until the timeout expires. + * subscription until the timeout expires. * @param stopAfter if true, the subscription will be stopped after the message was received (or - * timeout). + * timeout). * @return The received response. */ public GraphQLResponse awaitAndGetNextResponse(final int timeout, final boolean stopAfter) { @@ -247,8 +243,8 @@ public List awaitAndGetAllResponses(final int timeToWait) { * @param stopAfter if true, the subscription will be stopped after the time elapsed. * @return the list of responses received during that time. */ - public List awaitAndGetAllResponses(final int timeToWait, - final boolean stopAfter) { + public List awaitAndGetAllResponses( + final int timeToWait, final boolean stopAfter) { return awaitAndGetNextResponses(timeToWait, -1, stopAfter); } @@ -257,19 +253,17 @@ public List awaitAndGetAllResponses(final int timeToWait, * receiving the messages (or timeout). * * @param timeout timeout in milliseconds. Test will fail if the expected number of responses is - * not received. + * not received. * @param numExpectedResponses the number of expected responses. If negative, the method will wait - * the timeout and return all responses received during that time. In this case, no assertion is - * made regarding the number of responses, and the returned list may be empty. If zero, it is - * expected that no responses are sent during the timeout period. + * the timeout and return all responses received during that time. In this case, no assertion + * is made regarding the number of responses, and the returned list may be empty. If zero, it + * is expected that no responses are sent during the timeout period. * @return The list containing the expected number of responses. The list contains the responses - * in the order they were received. If more responses are received than minimally expected, {@link - * #getRemainingResponses()} can be used to retrieved them. + * in the order they were received. If more responses are received than minimally expected, + * {@link #getRemainingResponses()} can be used to retrieved them. */ public List awaitAndGetNextResponses( - final int timeout, - final int numExpectedResponses - ) { + final int timeout, final int numExpectedResponses) { return awaitAndGetNextResponses(timeout, numExpectedResponses, true); } @@ -277,22 +271,19 @@ public List awaitAndGetNextResponses( * Awaits and returns the specified number of responses. * * @param timeout timeout in milliseconds. Test will fail if the expected number of responses is - * not received. + * not received. * @param numExpectedResponses the number of expected responses. If negative, the method will wait - * the timeout and return all responses received during that time. In this case, no assertion is - * made regarding the number of responses, and the returned list may be empty. If zero, it is - * expected that no responses are sent during the timeout period. + * the timeout and return all responses received during that time. In this case, no assertion + * is made regarding the number of responses, and the returned list may be empty. If zero, it + * is expected that no responses are sent during the timeout period. * @param stopAfter if true, the subscription will be stopped after the messages were received (or - * timeout). + * timeout). * @return The list containing the expected number of responses. The list contains the responses - * in the order they were received. If more responses are received than minimally expected, {@link - * #getRemainingResponses()} can be used to retrieved them. + * in the order they were received. If more responses are received than minimally expected, + * {@link #getRemainingResponses()} can be used to retrieved them. */ public List awaitAndGetNextResponses( - final int timeout, - final int numExpectedResponses, - final boolean stopAfter - ) { + final int timeout, final int numExpectedResponses, final boolean stopAfter) { if (!isStarted()) { fail("Start message not sent. Please send start message first."); } @@ -322,16 +313,16 @@ public List awaitAndGetNextResponses( int responsesToPoll = responses.size(); if (numExpectedResponses == 0) { assertThat(responses) - .as(String.format("Expected no responses in %s MS, but received %s", timeout, - responses.size())) + .as( + String.format( + "Expected no responses in %s MS, but received %s", timeout, responses.size())) .isEmpty(); } if (numExpectedResponses > 0) { assertThat(responses) - .as("Expected at least %s message(s) in %d MS, but %d received.", - numExpectedResponses, - timeout, - responses.size()) + .as( + "Expected at least %s message(s) in %d MS, but %d received.", + numExpectedResponses, timeout, responses.size()) .hasSizeGreaterThanOrEqualTo(numExpectedResponses); responsesToPoll = numExpectedResponses; } @@ -350,8 +341,8 @@ public List awaitAndGetNextResponses( * @param timeToWait time to wait, in milliseconds. * @param stopAfter if true, the subscription will be stopped afterwards. */ - public GraphQLTestSubscription waitAndExpectNoResponse(final int timeToWait, - final boolean stopAfter) { + public GraphQLTestSubscription waitAndExpectNoResponse( + final int timeToWait, final boolean stopAfter) { awaitAndGetNextResponses(timeToWait, 0, stopAfter); return this; } @@ -384,24 +375,35 @@ public List getRemainingResponses() { private void initClient() throws IOException, DeploymentException { final String port = environment.getProperty("local.server.port"); - final URI uri = URI_BUILDER_FACTORY.builder().scheme("ws").host("localhost").port(port) - .path(subscriptionPath) - .build(); + final URI uri = + URI_BUILDER_FACTORY + .builder() + .scheme("ws") + .host("localhost") + .port(port) + .path(subscriptionPath) + .build(); log.debug("Connecting to client at {}", uri); - final ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create() - .configurator(new TestWebSocketClientConfigurator()) - .build(); - clientEndpointConfig.getUserProperties().put("org.apache.tomcat.websocket.IO_TIMEOUT_MS", - String.valueOf(ACKNOWLEDGEMENT_AND_CONNECTION_TIMEOUT)); - session = WEB_SOCKET_CONTAINER - .connectToServer(new TestWebSocketClient(state), clientEndpointConfig, uri); + final ClientEndpointConfig clientEndpointConfig = + ClientEndpointConfig.Builder.create() + .configurator(new TestWebSocketClientConfigurator()) + .build(); + clientEndpointConfig + .getUserProperties() + .put( + "org.apache.tomcat.websocket.IO_TIMEOUT_MS", + String.valueOf(ACKNOWLEDGEMENT_AND_CONNECTION_TIMEOUT)); + session = + WEB_SOCKET_CONTAINER.connectToServer( + new TestWebSocketClient(state), clientEndpointConfig, uri); session.addMessageHandler(new TestMessageHandler(objectMapper, state)); } private JsonNode getFinalPayload(final Object variables) { - return (JsonNode) Optional.ofNullable(variables) - .map(objectMapper::valueToTree) - .orElseGet(objectMapper::createObjectNode); + return (JsonNode) + Optional.ofNullable(variables) + .map(objectMapper::valueToTree) + .orElseGet(objectMapper::createObjectNode); } private String loadQuery(final String graphGLResource) { @@ -409,8 +411,10 @@ private String loadQuery(final String graphGLResource) { final File file = ResourceUtils.getFile("classpath:" + graphGLResource); return new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); } catch (IOException e) { - fail(String - .format("Test setup failure - could not load GraphQL resource: %s", graphGLResource), e); + fail( + String.format( + "Test setup failure - could not load GraphQL resource: %s", graphGLResource), + e); return ""; } } @@ -424,21 +428,21 @@ private void sendMessage(final Object message) { } private void awaitAcknowledgement() { - awaitAcknowledgementOrConnection(GraphQLTestSubscription::isAcknowledged, + awaitAcknowledgementOrConnection( + GraphQLTestSubscription::isAcknowledged, "Connection was acknowledged by the GraphQL server."); } private void awaitStop() { - awaitAcknowledgementOrConnection(GraphQLTestSubscription::isStopped, - "Connection was stopped in time."); + awaitAcknowledgementOrConnection( + GraphQLTestSubscription::isStopped, "Connection was stopped in time."); } - private void awaitAcknowledgementOrConnection(final Predicate condition, - final String timeoutDescription) { + private void awaitAcknowledgementOrConnection( + final Predicate condition, final String timeoutDescription) { await(timeoutDescription) .atMost(ACKNOWLEDGEMENT_AND_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS) .until(() -> condition.test(this)); - } @RequiredArgsConstructor @@ -470,9 +474,8 @@ public void onMessage(final String message) { final JsonNode payload = jsonNode.get(PAYLOAD); assertThat(payload).as("Data/error messages must have a payload.").isNotNull(); final String payloadString = objectMapper.writeValueAsString(payload); - final GraphQLResponse graphQLResponse = new GraphQLResponse( - ResponseEntity.ok(payloadString), - objectMapper); + final GraphQLResponse graphQLResponse = + new GraphQLResponse(ResponseEntity.ok(payloadString), objectMapper); if (state.isStopped() || state.isCompleted()) { log.debug( "Response discarded because subscription was stopped or completed in the meanwhile."); @@ -487,7 +490,8 @@ public void onMessage(final String message) { break; } } catch (JsonProcessingException e) { - fail("Exception while parsing server response. Response is not a valid GraphQL response.", + fail( + "Exception while parsing server response. Response is not a valid GraphQL response.", e); } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestTemplate.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestTemplate.java index 50f02844..bd27ac05 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestTemplate.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/GraphQLTestTemplate.java @@ -26,24 +26,20 @@ import org.springframework.util.MultiValueMap; import org.springframework.util.StreamUtils; -/** - * Helper class to test GraphQL queries and mutations. - */ +/** Helper class to test GraphQL queries and mutations. */ public class GraphQLTestTemplate { private final ResourceLoader resourceLoader; private final TestRestTemplate restTemplate; private final String graphqlMapping; private final ObjectMapper objectMapper; - @Getter - private final HttpHeaders headers = new HttpHeaders(); + @Getter private final HttpHeaders headers = new HttpHeaders(); public GraphQLTestTemplate( final ResourceLoader resourceLoader, final TestRestTemplate restTemplate, @Value("${graphql.servlet.mapping:/graphql}") final String graphqlMapping, - final ObjectMapper objectMapper - ) { + final ObjectMapper objectMapper) { this.resourceLoader = resourceLoader; this.restTemplate = restTemplate; this.graphqlMapping = graphqlMapping; @@ -119,8 +115,7 @@ public GraphQLTestTemplate withBearerAuth(@NonNull final String token) { public GraphQLTestTemplate withBasicAuth( @NonNull final String username, @NonNull final String password, - @Nullable final Charset charset - ) { + @Nullable final Charset charset) { headers.setBasicAuth(username, password, charset); return this; } @@ -132,8 +127,8 @@ public GraphQLTestTemplate withBasicAuth( * @param password the password * @return self */ - public GraphQLTestTemplate withBasicAuth(@NonNull final String username, - @NonNull final String password) { + public GraphQLTestTemplate withBasicAuth( + @NonNull final String username, @NonNull final String password) { headers.setBasicAuth(username, password, null); return this; } @@ -217,12 +212,13 @@ public GraphQLResponse perform(String graphqlResource, String operation, ObjectN * @param graphqlResource path to the classpath resource containing the GraphQL query * @param variables the input variables for the GraphQL query * @param fragmentResources an ordered list of classpath resources containing GraphQL fragment - * definitions. + * definitions. * @return {@link GraphQLResponse} containing the result of query execution * @throws IOException if the resource cannot be loaded from the classpath */ - public GraphQLResponse perform(String graphqlResource, ObjectNode variables, - List fragmentResources) throws IOException { + public GraphQLResponse perform( + String graphqlResource, ObjectNode variables, List fragmentResources) + throws IOException { return perform(graphqlResource, null, variables, fragmentResources); } @@ -233,12 +229,16 @@ public GraphQLResponse perform(String graphqlResource, ObjectNode variables, * @param graphqlResource path to the classpath resource containing the GraphQL query * @param variables the input variables for the GraphQL query * @param fragmentResources an ordered list of classpath resources containing GraphQL fragment - * definitions. + * definitions. * @return {@link GraphQLResponse} containing the result of query execution * @throws IOException if the resource cannot be loaded from the classpath */ - public GraphQLResponse perform(String graphqlResource, String operationName, ObjectNode variables, - List fragmentResources) throws IOException { + public GraphQLResponse perform( + String graphqlResource, + String operationName, + ObjectNode variables, + List fragmentResources) + throws IOException { StringBuilder sb = new StringBuilder(); for (String fragmentResource : fragmentResources) { sb.append(loadQuery(fragmentResource)); @@ -262,11 +262,11 @@ public GraphQLResponse postForResource(String graphqlResource) throws IOExceptio /** * Loads a GraphQL query or mutation from the given classpath resource, appending any graphql - * fragment resources provided and sends it to the GraphQL server. + * fragment resources provided and sends it to the GraphQL server. * * @param graphqlResource path to the classpath resource containing the GraphQL query * @param fragmentResources an ordered list of classpath resources containing GraphQL fragment - * definitions. + * definitions. * @return {@link GraphQLResponse} containing the result of query execution * @throws IOException if the resource cannot be loaded from the classpath */ @@ -290,9 +290,8 @@ public GraphQLResponse post(String payload) { } private GraphQLResponse postRequest(HttpEntity request) { - ResponseEntity response = restTemplate - .exchange(graphqlMapping, HttpMethod.POST, request, String.class); + ResponseEntity response = + restTemplate.exchange(graphqlMapping, HttpMethod.POST, request, String.class); return new GraphQLResponse(response, objectMapper); } - } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/JacksonFriendlySourceLocation.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/JacksonFriendlySourceLocation.java index 6ed73ce1..6626e47a 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/JacksonFriendlySourceLocation.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/JacksonFriendlySourceLocation.java @@ -5,17 +5,14 @@ import graphql.language.SourceLocation; import org.springframework.lang.Nullable; -/** - * Allow deserialization of {@link graphql.language.SourceLocation}. - */ +/** Allow deserialization of {@link graphql.language.SourceLocation}. */ public class JacksonFriendlySourceLocation extends SourceLocation { @JsonCreator public JacksonFriendlySourceLocation( final @JsonProperty("line") int line, final @JsonProperty("column") int column, - final @Nullable @JsonProperty("sourceName") String sourceName - ) { + final @Nullable @JsonProperty("sourceName") String sourceName) { super(line, column, sourceName); } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/RequestFactory.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/RequestFactory.java index a83272db..64e7f3bf 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/RequestFactory.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/RequestFactory.java @@ -23,5 +23,4 @@ static HttpEntity forMultipart(String query, String variables, HttpHeade values.add("variables", forJson(variables, new HttpHeaders())); return new HttpEntity<>(values, headers); } - } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/SubscriptionState.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/SubscriptionState.java index 2251fa2a..2051b708 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/SubscriptionState.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/SubscriptionState.java @@ -18,7 +18,6 @@ class SubscriptionState { private boolean started; private boolean stopped; private boolean completed; - @Builder.Default - private Queue responses = new ConcurrentLinkedQueue<>(); + @Builder.Default private Queue responses = new ConcurrentLinkedQueue<>(); private int id; } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/TestUtils.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/TestUtils.java index e18709ab..eb8a54a9 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/TestUtils.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/TestUtils.java @@ -24,9 +24,8 @@ public static Map assertNoGraphQLErrors(GraphQL gql, String quer return assertNoGraphQLErrors(gql, new HashMap<>(), new Object(), query); } - public static Map assertNoGraphQLErrors(GraphQL gql, Map args, - Object context, - String query) { + public static Map assertNoGraphQLErrors( + GraphQL gql, Map args, Object context, String query) { ExecutionResult result = execute(gql, args, context, query); if (!result.getErrors().isEmpty()) { @@ -41,19 +40,20 @@ private static String formatErrors(ExecutionResult result) { return result.getErrors().stream().map(TestUtils::toString).collect(Collectors.joining("\n")); } - private static ExecutionResult execute(GraphQL gql, Map args, Object context, - String query) { - return gql.execute(ExecutionInput.newExecutionInput() - .query(query) - .context(context) - .root(context) - .variables(args)); + private static ExecutionResult execute( + GraphQL gql, Map args, Object context, String query) { + return gql.execute( + ExecutionInput.newExecutionInput() + .query(query) + .context(context) + .root(context) + .variables(args)); } - public static void assertGraphQLError(GraphQL gql, String query, GraphQLError error, - GraphQLObjectMapper objectMapper) { - ExecutionResult result = objectMapper - .sanitizeErrors(execute(gql, new HashMap<>(), new Object(), query)); + public static void assertGraphQLError( + GraphQL gql, String query, GraphQLError error, GraphQLObjectMapper objectMapper) { + ExecutionResult result = + objectMapper.sanitizeErrors(execute(gql, new HashMap<>(), new Object(), query)); String expectedError = toString(error); if (result.getErrors().isEmpty()) { @@ -61,16 +61,17 @@ public static void assertGraphQLError(GraphQL gql, String query, GraphQLError er "GraphQL result did not contain any errors!Expected: \n" + expectedError); } - if (result.getErrors().stream().map(TestUtils::toString) + if (result.getErrors().stream() + .map(TestUtils::toString) .noneMatch(e -> e.equals(expectedError))) { throw new AssertionError( - "GraphQL result did not contain expected error!\nExpected:" + expectedError + "\nActual:" - + formatErrors( - result)); + "GraphQL result did not contain expected error!\nExpected:" + + expectedError + + "\nActual:" + + formatErrors(result)); } } - private static String toString(GraphQLError error) { try { return mapper.writeValueAsString(error.toSpecification()); @@ -79,5 +80,4 @@ private static String toString(GraphQLError error) { return null; } } - } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLErrorListAssertion.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLErrorListAssertion.java index 0c7822b7..cc43c0a3 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLErrorListAssertion.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLErrorListAssertion.java @@ -16,18 +16,20 @@ import org.assertj.core.api.ObjectAssertFactory; @EqualsAndHashCode(callSuper = true) -public class GraphQLErrorListAssertion extends FactoryBasedNavigableListAssert< - GraphQLErrorListAssertion, - List, - GraphQLError, - ObjectAssert - > +public class GraphQLErrorListAssertion + extends FactoryBasedNavigableListAssert< + GraphQLErrorListAssertion, + List, + GraphQLError, + ObjectAssert> implements GraphQLResponseAssertion { private final GraphQLResponse graphQLResponse; public GraphQLErrorListAssertion(final GraphQLResponse graphQLResponse) { - super(getGraphQLErrors(graphQLResponse), GraphQLErrorListAssertion.class, + super( + getGraphQLErrors(graphQLResponse), + GraphQLErrorListAssertion.class, new ObjectAssertFactory<>()); this.graphQLResponse = graphQLResponse; } @@ -46,11 +48,13 @@ private static List getGraphQLErrors( public GraphQLResponseAssertion hasNoErrors() { final List graphQLErrors = getGraphQLErrors(graphQLResponse); if (nonNull(graphQLErrors) && !graphQLErrors.isEmpty()) { - final String combinedMessage = graphQLErrors.stream() - .map(GraphQLError::toString) - .collect(Collectors.joining(System.lineSeparator())); - fail(String.format("Expected no GraphQL errors, but got %s: %s", graphQLErrors.size(), - combinedMessage)); + final String combinedMessage = + graphQLErrors.stream() + .map(GraphQLError::toString) + .collect(Collectors.joining(System.lineSeparator())); + fail( + String.format( + "Expected no GraphQL errors, but got %s: %s", graphQLErrors.size(), combinedMessage)); } return this; } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLFieldAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLFieldAssert.java index f8c38226..0c40a2f5 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLFieldAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLFieldAssert.java @@ -13,14 +13,13 @@ import java.util.Objects; import lombok.RequiredArgsConstructor; -/** - * Provides fluent assertions for a field (specified by a json path) of the GraphQL response. - */ +/** Provides fluent assertions for a field (specified by a json path) of the GraphQL response. */ @RequiredArgsConstructor public class GraphQLFieldAssert implements GraphQLResponseAssertion { public static final String EXPECTED_FIELD_S_TO_BE_PRESENT = "Expected field %s to be present."; - public static final String EXPECTED_THAT_CONTENT_OF_FIELD_S_CAN_BE_CONVERTED_TO_S = "Expected that content of field %s can be converted to %s."; + public static final String EXPECTED_THAT_CONTENT_OF_FIELD_S_CAN_BE_CONVERTED_TO_S = + "Expected that content of field %s can be converted to %s."; private final GraphQLResponse graphQLResponse; private final String jsonPath; @@ -97,7 +96,7 @@ public GraphQLFieldAssert isNotNull() { * * @return a {@link GraphQLBigDecimalAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to - * {@link BigDecimal} + * {@link BigDecimal} */ public GraphQLBigDecimalAssert asBigDecimal() { return new GraphQLBigDecimalAssert(graphQLResponse, getFieldAs(BigDecimal.class)); @@ -108,7 +107,7 @@ public GraphQLBigDecimalAssert asBigDecimal() { * * @return a {@link GraphQLBigIntegerAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to - * {@link BigInteger} + * {@link BigInteger} */ public GraphQLBigIntegerAssert asBigInteger() { return new GraphQLBigIntegerAssert(graphQLResponse, getFieldAs(BigInteger.class)); @@ -119,7 +118,7 @@ public GraphQLBigIntegerAssert asBigInteger() { * * @return a {@link GraphQLLongAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to - * {@link Long} + * {@link Long} */ public GraphQLLongAssert asLong() { return new GraphQLLongAssert(graphQLResponse, getFieldAs(Long.class)); @@ -130,7 +129,7 @@ public GraphQLLongAssert asLong() { * * @return a {@link GraphQLIntegerAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to - * {@link Integer} + * {@link Integer} */ public GraphQLIntegerAssert asInteger() { return new GraphQLIntegerAssert(graphQLResponse, getFieldAs(Integer.class)); @@ -141,7 +140,7 @@ public GraphQLIntegerAssert asInteger() { * * @return a {@link GraphQLShortAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to - * {@link Short} + * {@link Short} */ public GraphQLShortAssert asShort() { return new GraphQLShortAssert(graphQLResponse, getFieldAs(Short.class)); @@ -152,7 +151,7 @@ public GraphQLShortAssert asShort() { * * @return a {@link GraphQLByteAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to - * {@link Byte} + * {@link Byte} */ public GraphQLByteAssert asByte() { return new GraphQLByteAssert(graphQLResponse, getFieldAs(Byte.class)); @@ -163,7 +162,7 @@ public GraphQLByteAssert asByte() { * * @return a {@link GraphQLBooleanAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to - * {@link Boolean} + * {@link Boolean} */ public GraphQLBooleanAssert asBoolean() { return new GraphQLBooleanAssert(graphQLResponse, getFieldAs(Boolean.class)); @@ -174,7 +173,7 @@ public GraphQLBooleanAssert asBoolean() { * * @return a {@link GraphQLStringAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to - * {@link String} + * {@link String} */ public GraphQLStringAssert asString() { return new GraphQLStringAssert(graphQLResponse, getFieldAs(String.class)); @@ -186,7 +185,7 @@ public GraphQLStringAssert asString() { * @param clazz The class of the object. to assert * @return a {@link GraphQLGenericObjectAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to the - * specified class + * specified class */ public GraphQLGenericObjectAssert as(final Class clazz) { return new GraphQLGenericObjectAssert<>(graphQLResponse, getFieldAs(clazz)); @@ -198,7 +197,7 @@ public GraphQLGenericObjectAssert as(final Class clazz) { * @param javaType The java type definition. * @return a {@link GraphQLGenericObjectAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to the - * specified class + * specified class */ public GraphQLGenericObjectAssert as(final JavaType javaType) { return new GraphQLGenericObjectAssert<>(graphQLResponse, getFieldAs(javaType)); @@ -210,7 +209,7 @@ public GraphQLGenericObjectAssert as(final JavaType javaType) { * @param javaListType The java type definition. Expected to define a list type. * @return a {@link GraphQLListAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to the - * specified class or if the provided type is not a list type. + * specified class or if the provided type is not a list type. */ public GraphQLListAssert asList(final JavaType javaListType) { return new GraphQLListAssert<>(graphQLResponse, getFieldAs(javaListType)); @@ -222,15 +221,13 @@ public GraphQLListAssert asList(final JavaType javaListType) { * @param elementClass the type of objects in the list * @return a {@link GraphQLGenericObjectAssert} instance * @throws AssertionError if the path does not exist or the content could not be converted to the - * specified class + * specified class */ public GraphQLListAssert asListOf(final Class elementClass) { return new GraphQLListAssert<>(graphQLResponse, getFieldAsList(elementClass)); } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public GraphQLResponse and() { return graphQLResponse; @@ -243,8 +240,10 @@ private T getFieldAs(final Class targetClass) { fail(String.format(EXPECTED_FIELD_S_TO_BE_PRESENT, jsonPath), e); return null; } catch (IllegalArgumentException e) { - fail(String.format(EXPECTED_THAT_CONTENT_OF_FIELD_S_CAN_BE_CONVERTED_TO_S, jsonPath, - targetClass), e); + fail( + String.format( + EXPECTED_THAT_CONTENT_OF_FIELD_S_CAN_BE_CONVERTED_TO_S, jsonPath, targetClass), + e); return null; } } @@ -256,8 +255,8 @@ private T getFieldAs(final JavaType javaType) { fail(String.format(EXPECTED_FIELD_S_TO_BE_PRESENT, jsonPath), e); return null; } catch (IllegalArgumentException e) { - fail(String - .format(EXPECTED_THAT_CONTENT_OF_FIELD_S_CAN_BE_CONVERTED_TO_S, jsonPath, javaType), + fail( + String.format(EXPECTED_THAT_CONTENT_OF_FIELD_S_CAN_BE_CONVERTED_TO_S, jsonPath, javaType), e); return null; } @@ -270,8 +269,10 @@ private List getFieldAsList(final Class targetClass) { fail(String.format(EXPECTED_FIELD_S_TO_BE_PRESENT, jsonPath), e); return emptyList(); } catch (IllegalArgumentException e) { - fail(String.format(EXPECTED_THAT_CONTENT_OF_FIELD_S_CAN_BE_CONVERTED_TO_S, jsonPath, - targetClass), e); + fail( + String.format( + EXPECTED_THAT_CONTENT_OF_FIELD_S_CAN_BE_CONVERTED_TO_S, jsonPath, targetClass), + e); return emptyList(); } } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLListAssert.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLListAssert.java index 7ed2e215..23b0cf9b 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLListAssert.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLListAssert.java @@ -8,12 +8,9 @@ import org.assertj.core.api.ObjectAssertFactory; @EqualsAndHashCode(callSuper = true) -public class GraphQLListAssert extends FactoryBasedNavigableListAssert< - GraphQLListAssert, - List, - T, - ObjectAssert - > +public class GraphQLListAssert + extends FactoryBasedNavigableListAssert< + GraphQLListAssert, List, T, ObjectAssert> implements GraphQLResponseAssertion { private final GraphQLResponse graphQlResponse; diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLResponseAssertion.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLResponseAssertion.java index 2d4b0dc5..da5fc388 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLResponseAssertion.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/GraphQLResponseAssertion.java @@ -10,7 +10,7 @@ public interface GraphQLResponseAssertion { /** * @return the instance of {@link GraphQLResponse} for which this assertion was created. Allows - * chaining fluent assertions. + * chaining fluent assertions. */ GraphQLResponse and(); } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/NumberOfErrorsAssertion.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/NumberOfErrorsAssertion.java index 93fc1d86..017ec51e 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/NumberOfErrorsAssertion.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/assertions/NumberOfErrorsAssertion.java @@ -11,8 +11,7 @@ import org.assertj.core.api.AbstractIntegerAssert; @EqualsAndHashCode(callSuper = true) -public class NumberOfErrorsAssertion - extends AbstractIntegerAssert +public class NumberOfErrorsAssertion extends AbstractIntegerAssert implements GraphQLResponseAssertion { private final GraphQLResponse graphQLResponse; @@ -25,8 +24,8 @@ public NumberOfErrorsAssertion(final GraphQLResponse response) { private static Integer getNumberOfErrors(final GraphQLResponse response) { int numErrors = 0; try { - final List errorList = response - .getList(ERRORS_PATH, GraphQLTestError.class); + final List errorList = + response.getList(ERRORS_PATH, GraphQLTestError.class); if (nonNull(errorList)) { numErrors = errorList.size(); } diff --git a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/helper/GraphQLTestConstantsHelper.java b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/helper/GraphQLTestConstantsHelper.java index bdb55db6..7821f21d 100644 --- a/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/helper/GraphQLTestConstantsHelper.java +++ b/graphql-spring-boot-test/src/main/java/com/graphql/spring/boot/test/helper/GraphQLTestConstantsHelper.java @@ -6,7 +6,5 @@ public final class GraphQLTestConstantsHelper { public static final String DATA_PATH = "$.data"; public static final String EXTENSIONS_PATH = "$.extensions"; - private GraphQLTestConstantsHelper() { - - } + private GraphQLTestConstantsHelper() {} } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotNullTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotNullTest.java index 9c79ac39..33102f37 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotNullTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotNullTest.java @@ -7,7 +7,6 @@ import com.graphql.spring.boot.test.assertions.GraphQLFieldAssert; import com.jayway.jsonpath.PathNotFoundException; -import lombok.EqualsAndHashCode; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -19,8 +18,8 @@ class GraphQLAssertIsNotNullTest extends GraphQLFieldAssertTestBase { void shouldPassIfIsNotNull() { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(NON_NULL_VALUE); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatCode(graphQLFieldAssert::isNotNull).doesNotThrowAnyException(); assertThat(graphQLFieldAssert.isNotNull().and()).isSameAs(graphQLResponse); @@ -31,8 +30,8 @@ void shouldPassIfIsNotNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::isNotNull) @@ -45,8 +44,8 @@ void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundExce void shouldFailIfIsNotNull() { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::isNotNull) diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotPresentOrNullTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotPresentOrNullTest.java index 4a753451..b4f85ae5 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotPresentOrNullTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLAssertIsNotPresentOrNullTest.java @@ -18,8 +18,8 @@ class GraphQLAssertIsNotPresentOrNullTest extends GraphQLFieldAssertTestBase { void shouldPassIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatCode(graphQLFieldAssert::isNotPresentOrNull).doesNotThrowAnyException(); assertThat(graphQLFieldAssert.isNotPresentOrNull().and()).isSameAs(graphQLResponse); @@ -30,8 +30,8 @@ void shouldPassIfPathNotFound(final @Mock PathNotFoundException pathNotFoundExce void shouldPassIfIsNull() { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatCode(graphQLFieldAssert::isNotPresentOrNull).doesNotThrowAnyException(); assertThat(graphQLFieldAssert.isNotPresentOrNull().and()).isSameAs(graphQLResponse); @@ -42,8 +42,8 @@ void shouldPassIfIsNull() { void shouldFailIfIsNotNull() { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(NON_NULL_VALUE); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::isNotPresentOrNull) diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigDecimalTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigDecimalTest.java index 24d7b699..918c5292 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigDecimalTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigDecimalTest.java @@ -20,8 +20,8 @@ void shouldReturnBigDecimalAssertIfFieldIsNonNull() { // GIVEN final BigDecimal value = new BigDecimal("1.23"); given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLBigDecimalAssert actual = graphQLFieldAssert.asBigDecimal(); // THEN @@ -36,8 +36,8 @@ void shouldReturnBigDecimalAssertIfFieldIsNonNull() { void shouldReturnBigDecimalAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLBigDecimalAssert actual = graphQLFieldAssert.asBigDecimal(); // THEN @@ -51,8 +51,8 @@ void shouldReturnBigDecimalAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asBigDecimal) @@ -66,13 +66,14 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, BigDecimal.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asBigDecimal) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - BigDecimal.class) + .withMessage( + "Expected that content of field %s can be converted to %s.", + MOCK_PATH, BigDecimal.class) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigIntegerTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigIntegerTest.java index b192bbf0..e83bd49a 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigIntegerTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBigIntegerTest.java @@ -20,8 +20,8 @@ void shouldReturnBigIntegerAssertIfFieldIsNonNull() { // GIVEN final BigInteger value = new BigInteger("123"); given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLBigIntegerAssert actual = graphQLFieldAssert.asBigInteger(); // THEN @@ -36,8 +36,8 @@ void shouldReturnBigIntegerAssertIfFieldIsNonNull() { void shouldReturnBigIntegerAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLBigIntegerAssert actual = graphQLFieldAssert.asBigInteger(); // THEN @@ -51,8 +51,8 @@ void shouldReturnBigIntegerAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asBigInteger) @@ -66,13 +66,14 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, BigInteger.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asBigInteger) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - BigInteger.class) + .withMessage( + "Expected that content of field %s can be converted to %s.", + MOCK_PATH, BigInteger.class) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBooleanTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBooleanTest.java index e7422633..0eed1faf 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBooleanTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsBooleanTest.java @@ -18,8 +18,8 @@ class GraphQLFieldAssertAsBooleanTest extends GraphQLFieldAssertTestBase { void shouldReturnBooleanAssertIfFieldIsNonNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willReturn(true); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLBooleanAssert actual = graphQLFieldAssert.asBoolean(); // THEN @@ -34,8 +34,8 @@ void shouldReturnBooleanAssertIfFieldIsNonNull() { void shouldReturnBooleanAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLBooleanAssert actual = graphQLFieldAssert.asBoolean(); // THEN @@ -49,8 +49,8 @@ void shouldReturnBooleanAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asBoolean) @@ -64,13 +64,13 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Boolean.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asBoolean) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Boolean.class) + .withMessage( + "Expected that content of field %s can be converted to %s.", MOCK_PATH, Boolean.class) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsByteTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsByteTest.java index 46836b6d..6da50051 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsByteTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsByteTest.java @@ -19,8 +19,8 @@ void shouldReturnByteAssertIfFieldIsNonNull() { // GIVEN final Byte value = 123; given(graphQLResponse.get(MOCK_PATH, Byte.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLByteAssert actual = graphQLFieldAssert.asByte(); // THEN @@ -35,8 +35,8 @@ void shouldReturnByteAssertIfFieldIsNonNull() { void shouldReturnByteAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, Byte.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLByteAssert actual = graphQLFieldAssert.asByte(); // THEN @@ -50,8 +50,8 @@ void shouldReturnByteAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Byte.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asByte) @@ -65,13 +65,13 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Byte.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asByte) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Byte.class) + .withMessage( + "Expected that content of field %s can be converted to %s.", MOCK_PATH, Byte.class) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsIntegerTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsIntegerTest.java index 1417d99c..614c38ea 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsIntegerTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsIntegerTest.java @@ -19,8 +19,8 @@ void shouldReturnIntegerAssertIfFieldIsNonNull() { // GIVEN final Integer value = 123; given(graphQLResponse.get(MOCK_PATH, Integer.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLIntegerAssert actual = graphQLFieldAssert.asInteger(); // THEN @@ -35,8 +35,8 @@ void shouldReturnIntegerAssertIfFieldIsNonNull() { void shouldReturnIntegerAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, Integer.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLIntegerAssert actual = graphQLFieldAssert.asInteger(); // THEN @@ -50,8 +50,8 @@ void shouldReturnIntegerAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Integer.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asInteger) @@ -65,13 +65,13 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Integer.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asInteger) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Integer.class) + .withMessage( + "Expected that content of field %s can be converted to %s.", MOCK_PATH, Integer.class) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaListTypeTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaListTypeTest.java index 881072e3..55444302 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaListTypeTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaListTypeTest.java @@ -17,8 +17,8 @@ class GraphQLFieldAssertAsJavaListTypeTest extends GraphQLFieldAssertTestBase { - private static final JavaType STRING_LIST_TYPE = TypeFactory.defaultInstance() - .constructCollectionLikeType(List.class, String.class); + private static final JavaType STRING_LIST_TYPE = + TypeFactory.defaultInstance().constructCollectionLikeType(List.class, String.class); @Test @DisplayName("Should return a String list assertion (value at specific path is valid list).") @@ -26,8 +26,8 @@ void shouldReturnStringListAssertIfFieldIsNonNull() { // GIVEN final List values = Arrays.asList("value1", "value2"); given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willReturn(values); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLListAssert actual = graphQLFieldAssert.asList(STRING_LIST_TYPE); // THEN @@ -42,8 +42,8 @@ void shouldReturnStringListAssertIfFieldIsNonNull() { void shouldReturnStringListAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLListAssert actual = graphQLFieldAssert.asList(STRING_LIST_TYPE); // THEN @@ -57,8 +57,8 @@ void shouldReturnStringListAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> graphQLFieldAssert.asList(STRING_LIST_TYPE)) @@ -72,13 +72,14 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, STRING_LIST_TYPE)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> graphQLFieldAssert.asList(STRING_LIST_TYPE)) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - STRING_LIST_TYPE) + .withMessage( + "Expected that content of field %s can be converted to %s.", + MOCK_PATH, STRING_LIST_TYPE) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaTypeTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaTypeTest.java index b252ff5a..53f04e26 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaTypeTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsJavaTypeTest.java @@ -23,11 +23,11 @@ void shouldReturnGenericObjectAssertIfFieldIsNonNull() { // GIVEN final Foo foo = new Foo("fooBar"); given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willReturn(foo); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - final GraphQLGenericObjectAssert - actual = graphQLFieldAssert.as(FOO_TYPE); + final GraphQLGenericObjectAssert actual = + graphQLFieldAssert.as(FOO_TYPE); // THEN assertThat(actual).isNotNull(); assertThat(actual.and()).isSameAs(graphQLResponse); @@ -40,8 +40,8 @@ void shouldReturnGenericObjectAssertIfFieldIsNonNull() { void shouldReturnGenericObjectAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLGenericObjectAssert actual = graphQLFieldAssert.as(FOO_TYPE); // THEN @@ -55,8 +55,8 @@ void shouldReturnGenericObjectAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> graphQLFieldAssert.as(FOO_TYPE)) @@ -70,13 +70,13 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, FOO_TYPE)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> graphQLFieldAssert.as(FOO_TYPE)) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - FOO_TYPE) + .withMessage( + "Expected that content of field %s can be converted to %s.", MOCK_PATH, FOO_TYPE) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsListTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsListTest.java index 69fdf9c8..d06d202a 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsListTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsListTest.java @@ -21,8 +21,8 @@ void shouldReturnStringListAssertIfFieldIsNonNull() { // GIVEN final List values = Arrays.asList("value1", "value2"); given(graphQLResponse.getList(MOCK_PATH, String.class)).willReturn(values); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLListAssert actual = graphQLFieldAssert.asListOf(String.class); // THEN @@ -37,8 +37,8 @@ void shouldReturnStringListAssertIfFieldIsNonNull() { void shouldReturnStringListAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.getList(MOCK_PATH, String.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLListAssert actual = graphQLFieldAssert.asListOf(String.class); // THEN @@ -52,8 +52,8 @@ void shouldReturnStringListAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.getList(MOCK_PATH, String.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> graphQLFieldAssert.asListOf(String.class)) @@ -67,13 +67,13 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.getList(MOCK_PATH, String.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> graphQLFieldAssert.asListOf(String.class)) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - String.class) + .withMessage( + "Expected that content of field %s can be converted to %s.", MOCK_PATH, String.class) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsLongTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsLongTest.java index 602aa2d4..105a50cf 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsLongTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsLongTest.java @@ -19,8 +19,8 @@ void shouldReturnLongAssertIfFieldIsNonNull() { // GIVEN final Long value = 123L; given(graphQLResponse.get(MOCK_PATH, Long.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLLongAssert actual = graphQLFieldAssert.asLong(); // THEN @@ -35,8 +35,8 @@ void shouldReturnLongAssertIfFieldIsNonNull() { void shouldReturnLongAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, Long.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLLongAssert actual = graphQLFieldAssert.asLong(); // THEN @@ -50,8 +50,8 @@ void shouldReturnLongAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Long.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asLong) @@ -65,13 +65,13 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Long.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asLong) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Long.class) + .withMessage( + "Expected that content of field %s can be converted to %s.", MOCK_PATH, Long.class) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsShortTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsShortTest.java index 0281db7a..af80095d 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsShortTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsShortTest.java @@ -19,8 +19,8 @@ void shouldReturnShortAssertIfFieldIsNonNull() { // GIVEN final Short value = 123; given(graphQLResponse.get(MOCK_PATH, Short.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLShortAssert actual = graphQLFieldAssert.asShort(); // THEN @@ -35,8 +35,8 @@ void shouldReturnShortAssertIfFieldIsNonNull() { void shouldReturnShortAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, Short.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLShortAssert actual = graphQLFieldAssert.asShort(); // THEN @@ -50,8 +50,8 @@ void shouldReturnShortAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Short.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asShort) @@ -65,13 +65,13 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Short.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asShort) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Short.class) + .withMessage( + "Expected that content of field %s can be converted to %s.", MOCK_PATH, Short.class) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsStringTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsStringTest.java index 79f97aa5..a663b45d 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsStringTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsStringTest.java @@ -19,8 +19,8 @@ void shouldReturnStringAssertIfFieldIsNonNull() { // GIVEN final String value = "some value"; given(graphQLResponse.get(MOCK_PATH, String.class)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLStringAssert actual = graphQLFieldAssert.asString(); // THEN @@ -35,8 +35,8 @@ void shouldReturnStringAssertIfFieldIsNonNull() { void shouldReturnStringAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, String.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLStringAssert actual = graphQLFieldAssert.asString(); // THEN @@ -50,8 +50,8 @@ void shouldReturnStringAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, String.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asString) @@ -65,13 +65,13 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, String.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::asString) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - String.class) + .withMessage( + "Expected that content of field %s can be converted to %s.", MOCK_PATH, String.class) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsTest.java index 038f4d17..e6422522 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertAsTest.java @@ -19,8 +19,8 @@ void shouldReturnGenericObjectAssertIfFieldIsNonNull() { // GIVEN final Foo foo = new Foo("fooBar"); given(graphQLResponse.get(MOCK_PATH, Foo.class)).willReturn(foo); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLGenericObjectAssert actual = graphQLFieldAssert.as(Foo.class); // THEN @@ -35,8 +35,8 @@ void shouldReturnGenericObjectAssertIfFieldIsNonNull() { void shouldReturnGenericObjectAssertIfFieldIsNull() { // GIVEN given(graphQLResponse.get(MOCK_PATH, Foo.class)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN final GraphQLGenericObjectAssert actual = graphQLFieldAssert.as(Foo.class); // THEN @@ -50,8 +50,8 @@ void shouldReturnGenericObjectAssertIfFieldIsNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Foo.class)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> graphQLFieldAssert.as(Foo.class)) @@ -65,13 +65,13 @@ void shouldFailIfCannotBeConverted( final @Mock IllegalArgumentException illegalArgumentException) { // GIVEN given(graphQLResponse.get(MOCK_PATH, Foo.class)).willThrow(illegalArgumentException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> graphQLFieldAssert.as(Foo.class)) - .withMessage("Expected that content of field %s can be converted to %s.", MOCK_PATH, - Foo.class) + .withMessage( + "Expected that content of field %s can be converted to %s.", MOCK_PATH, Foo.class) .withCause(illegalArgumentException); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNotPresentTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNotPresentTest.java index c57b96ac..f4cd9c15 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNotPresentTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNotPresentTest.java @@ -25,8 +25,8 @@ private static Stream valuesThatShouldCauseFailure() { void shouldFailIfValueIsPresent(final String value) { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(value); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::isNotPresent) @@ -38,8 +38,8 @@ void shouldFailIfValueIsPresent(final String value) { void shouldPassIfNotPresent() { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(PathNotFoundException.class); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatCode(graphQLFieldAssert::isNotPresent).doesNotThrowAnyException(); assertThat(graphQLFieldAssert.isNotPresent().and()).isSameAs(graphQLResponse); diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNullTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNullTest.java index f0aa0146..fc5f49a7 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNullTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertIsNullTest.java @@ -18,8 +18,8 @@ class GraphQLFieldAssertIsNullTest extends GraphQLFieldAssertTestBase { void shouldPassIfNull() { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(null); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatCode(graphQLFieldAssert::isNull).doesNotThrowAnyException(); assertThat(graphQLFieldAssert.isNull().and()).isSameAs(graphQLResponse); @@ -30,8 +30,8 @@ void shouldPassIfNull() { void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundException) { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willThrow(pathNotFoundException); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::isNull) @@ -44,8 +44,8 @@ void shouldFailIfPathNotFound(final @Mock PathNotFoundException pathNotFoundExce void shouldFailIfIsNotNull() { // GIVEN given(graphQLResponse.getRaw(MOCK_PATH)).willReturn(NON_NULL_VALUE); - final GraphQLFieldAssert graphQLFieldAssert = new GraphQLFieldAssert(graphQLResponse, - MOCK_PATH); + final GraphQLFieldAssert graphQLFieldAssert = + new GraphQLFieldAssert(graphQLResponse, MOCK_PATH); // WHEN - THEN assertThatExceptionOfType(AssertionError.class) .isThrownBy(graphQLFieldAssert::isNull) diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertTestBase.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertTestBase.java index 9b47aa9f..3f7c0f21 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertTestBase.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLFieldAssertTestBase.java @@ -12,8 +12,7 @@ public class GraphQLFieldAssertTestBase { protected static final String MOCK_PATH = "test.path"; protected static final String NON_NULL_VALUE = "non-null"; - @Mock - protected GraphQLResponse graphQLResponse; + @Mock protected GraphQLResponse graphQLResponse; @Data @AllArgsConstructor diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLResponseTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLResponseTest.java index a3404a04..f647ffd7 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLResponseTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLResponseTest.java @@ -43,15 +43,13 @@ class GraphQLResponseTest { private static final String NESTED_LIST_RESPONSE_FILE = "response-with-nested-list.json"; private static final String EMPTY_OBJECT_RESPONSE = "{}"; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; private static Stream testGetStringArguments() { return Stream.of( Arguments.of("{\"data\": {\"test\": 2}}", "2"), Arguments.of("{\"data\": {\"test\": \"2\"}}", "2"), - Arguments.of("{\"data\": {\"test\": \"2020-02-23\"}}", "2020-02-23") - ); + Arguments.of("{\"data\": {\"test\": \"2020-02-23\"}}", "2020-02-23")); } private static Stream testGetArguments() { @@ -59,32 +57,35 @@ private static Stream testGetArguments() { Arguments.of("{\"data\": {\"test\": \"2\"}}", Integer.class, 2), Arguments.of("{\"data\": {\"test\": \"2\"}}", String.class, "2"), Arguments.of("{\"data\": {\"test\": \"2\"}}", BigDecimal.class, new BigDecimal("2")), - Arguments.of("{\"data\": {\"test\": \"2020-02-23\"}}", LocalDate.class, + Arguments.of( + "{\"data\": {\"test\": \"2020-02-23\"}}", + LocalDate.class, LocalDate.parse("2020-02-23")), - Arguments - .of("{\"data\": {\"test\": {\"foo\": \"fizzBuzz\", \"bar\": 13.8 }}}", FooBar.class, - new FooBar("fizzBuzz", new BigDecimal("13.8"))) - ); + Arguments.of( + "{\"data\": {\"test\": {\"foo\": \"fizzBuzz\", \"bar\": 13.8 }}}", + FooBar.class, + new FooBar("fizzBuzz", new BigDecimal("13.8")))); } private static Stream testGetListArguments() { return Stream.of( Arguments.of("{\"data\": {\"test\": [\"2\", \"1\"]}}", Integer.class, Arrays.asList(2, 1)), - Arguments - .of("{\"data\": {\"test\": [\"2\", \"1\"]}}", String.class, Arrays.asList("2", "1")), - Arguments.of("{\"data\": {\"test\": [\"2\", \"1\"]}}", BigDecimal.class, + Arguments.of( + "{\"data\": {\"test\": [\"2\", \"1\"]}}", String.class, Arrays.asList("2", "1")), + Arguments.of( + "{\"data\": {\"test\": [\"2\", \"1\"]}}", + BigDecimal.class, Arrays.asList(new BigDecimal("2"), new BigDecimal("1"))), - Arguments.of("{\"data\": {\"test\": [\"2020-02-23\", \"2020-02-24\"]}}", LocalDate.class, + Arguments.of( + "{\"data\": {\"test\": [\"2020-02-23\", \"2020-02-24\"]}}", + LocalDate.class, Arrays.asList(LocalDate.parse("2020-02-23"), LocalDate.parse("2020-02-24"))), - Arguments - .of("{\"data\":{\"test\":[{\"foo\":\"fizz\",\"bar\":1.23},{\"foo\":\"buzz\",\"bar\":32.12}]}}", - FooBar.class, - Arrays.asList( - new FooBar("fizz", new BigDecimal("1.23")), - new FooBar("buzz", new BigDecimal("32.12")) - ) - ) - ); + Arguments.of( + "{\"data\":{\"test\":[{\"foo\":\"fizz\",\"bar\":1.23},{\"foo\":\"buzz\",\"bar\":32.12}]}}", + FooBar.class, + Arrays.asList( + new FooBar("fizz", new BigDecimal("1.23")), + new FooBar("buzz", new BigDecimal("32.12"))))); } private static String loadClassPathResource(final String path) { @@ -100,11 +101,11 @@ private static String loadClassPathResource(final String path) { @ParameterizedTest @MethodSource("testGetStringArguments") void testGetString(final String bodyString, final String expected) { - //GIVEN + // GIVEN final GraphQLResponse graphQLResponse = createResponse(bodyString); - //WHEN + // WHEN final String actual = graphQLResponse.get(DATA_PATH_TEST); - //THEN + // THEN assertThat(actual).isEqualTo(expected); } @@ -112,24 +113,23 @@ void testGetString(final String bodyString, final String expected) { @ParameterizedTest @MethodSource("testGetArguments") void testGet(final String bodyString, final Class clazz, final T expected) { - //GIVEN + // GIVEN final GraphQLResponse graphQLResponse = createResponse(bodyString); - //WHEN + // WHEN final T actual = graphQLResponse.get(DATA_PATH_TEST, clazz); - //THEN + // THEN assertThat(actual).isInstanceOf(clazz).isEqualTo(expected); } @DisplayName("Should get the JSON node's value as a List.") @ParameterizedTest @MethodSource("testGetListArguments") - void testGetList(final String bodyString, final Class clazz, - final List expected) { - //GIVEN + void testGetList(final String bodyString, final Class clazz, final List expected) { + // GIVEN final GraphQLResponse graphQLResponse = createResponse(bodyString); - //WHEN + // WHEN final List actual = graphQLResponse.getList(DATA_PATH_TEST, clazz); - //THEN + // THEN assertThat(actual).containsExactlyElementsOf(expected); } @@ -137,20 +137,18 @@ void testGetList(final String bodyString, final Class clazz, @Test void testGetAsJavaType() { // GIVEN - final List> expected = Arrays.asList(Arrays.asList("foo1", "foo2"), - Collections.singletonList("foo3")); - final JavaType stringList = objectMapper.getTypeFactory() - .constructCollectionType(List.class, String.class); - final JavaType listOfStringLists = objectMapper.getTypeFactory() - .constructCollectionType(List.class, - stringList); + final List> expected = + Arrays.asList(Arrays.asList("foo1", "foo2"), Collections.singletonList("foo3")); + final JavaType stringList = + objectMapper.getTypeFactory().constructCollectionType(List.class, String.class); + final JavaType listOfStringLists = + objectMapper.getTypeFactory().constructCollectionType(List.class, stringList); // WHEN - final List> actual = createResponse( - loadClassPathResource(NESTED_LIST_RESPONSE_FILE)) - .get(INNER_FOO_LIST_DATA_PATH, listOfStringLists); + final List> actual = + createResponse(loadClassPathResource(NESTED_LIST_RESPONSE_FILE)) + .get(INNER_FOO_LIST_DATA_PATH, listOfStringLists); // THEN assertThat(actual).containsExactlyElementsOf(expected); - } @DisplayName("Should throw illegal argument exception if type is incompatible") @@ -163,15 +161,15 @@ void testGetAsJavaTypeConversionError() { // THEN assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> actual.get(INNER_FOO_LIST_DATA_PATH, stringType)); - } @ParameterizedTest - @ValueSource(strings = { - "{\"data\": { \"foo\":\"bar\" } }", - "{\"errors\": null, \"data\": { \"foo\":\"bar\"} }", - "{\"errors\": [], \"data\": { \"foo\":\"bar\"} }" - }) + @ValueSource( + strings = { + "{\"data\": { \"foo\":\"bar\" } }", + "{\"errors\": null, \"data\": { \"foo\":\"bar\"} }", + "{\"errors\": [], \"data\": { \"foo\":\"bar\"} }" + }) @DisplayName("Should pass the assertion if no errors are present.") void testExpectNoErrorsPass(final String response) { // WHEN @@ -186,7 +184,8 @@ void testExpectNoErrorsPass(final String response) { @DisplayName("Should throw assertion error if an error is present in the response.") void testExpectNoErrorsFail() { // GIVEN - final String response = "{\"errors\": [{\"message\": \"Test error.\"}], \"data\": { \"foo\":\"bar\"} }"; + final String response = + "{\"errors\": [{\"message\": \"Test error.\"}], \"data\": { \"foo\":\"bar\"} }"; // WHEN final GraphQLResponse graphQLResponse = createResponse(response); // THEN @@ -222,9 +221,14 @@ void testErrorListAssertion() { final GraphQLErrorListAssertion actual = graphQLResponse.assertThatListOfErrors(); // THEN assertThat(actual).isNotNull(); - assertThat(actual).extracting("actual") - .isEqualTo(Collections.singletonList(GraphQLTestError.builder() - .message("Test error.").errorType(ErrorType.DataFetchingException).build())); + assertThat(actual) + .extracting("actual") + .isEqualTo( + Collections.singletonList( + GraphQLTestError.builder() + .message("Test error.") + .errorType(ErrorType.DataFetchingException) + .build())); assertThat(actual.and()).isSameAs(graphQLResponse); } @@ -293,10 +297,10 @@ private GraphQLResponse createResponse(final String s) { private void assertThatAssertionIsCorrect( final GraphQLFieldAssert actual, final GraphQLResponse expectedResponse, - final Object expectedPath - ) { + final Object expectedPath) { assertThat(actual).isNotNull(); - assertThat(actual).extracting("graphQLResponse", "jsonPath") + assertThat(actual) + .extracting("graphQLResponse", "jsonPath") .containsExactly(expectedResponse, expectedPath); } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLSubscriptionTestAwaitNoAnswerTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLSubscriptionTestAwaitNoAnswerTest.java index 5d183c08..ae19e713 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLSubscriptionTestAwaitNoAnswerTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLSubscriptionTestAwaitNoAnswerTest.java @@ -2,13 +2,12 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import java.time.Instant; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import java.time.Instant; - @DisplayName("Testing awaitNoResponse methods") class GraphQLSubscriptionTestAwaitNoAnswerTest extends GraphQLTestSubscriptionTestBase { @@ -29,9 +28,7 @@ void shouldAwaitNoResponseSucceedIfNoResponsesArrivedDefaultStopAfter() { @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Should succeed if no responses arrive.") - void shouldAwaitNoResponseSucceedIfNoResponsesArrived( - final boolean stopAfter - ) { + void shouldAwaitNoResponseSucceedIfNoResponsesArrived(final boolean stopAfter) { // GIVEN final Instant timeBeforeTestStart = Instant.now(); // WHEN @@ -57,9 +54,7 @@ void shouldRaiseAssertionErrorIfResponseArrivedDefaultStopAfter() { @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Should raise assertion error if any response arrived.") - void shouldRaiseAssertionErrorIfResponseArrived( - final boolean stopAfter - ) { + void shouldRaiseAssertionErrorIfResponseArrived(final boolean stopAfter) { // WHEN graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE); // THEN diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestErrorToStringTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestErrorToStringTest.java index a0d21fee..99eb3c2a 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestErrorToStringTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestErrorToStringTest.java @@ -21,54 +21,65 @@ private static Stream toStringTestArguments() { return Stream.of( Arguments.of( new GraphQLTestError(null, null, null, null, null), - ": " - ), + ": "), Arguments.of( new GraphQLTestError(TEST_MESSAGE, null, null, null, null), - ": Test message" - ), + ": Test message"), Arguments.of( new GraphQLTestError(TEST_MESSAGE, null, ErrorType.DataFetchingException, null, null), - "DataFetchingException: Test message" - ), + "DataFetchingException: Test message"), Arguments.of( - new GraphQLTestError(TEST_MESSAGE, Collections.emptyList(), - ErrorType.DataFetchingException, null, null), - "DataFetchingException: Test message" - ), + new GraphQLTestError( + TEST_MESSAGE, Collections.emptyList(), ErrorType.DataFetchingException, null, null), + "DataFetchingException: Test message"), Arguments.of( - new GraphQLTestError(TEST_MESSAGE, Collections.singletonList(new SourceLocation(1, 2)), - ErrorType.DataFetchingException, null, null), - "DataFetchingException: Test message at line 1, column 2 in unnamed/unspecified source" - ), + new GraphQLTestError( + TEST_MESSAGE, + Collections.singletonList(new SourceLocation(1, 2)), + ErrorType.DataFetchingException, + null, + null), + "DataFetchingException: Test message at line 1, column 2 in unnamed/unspecified source"), Arguments.of( - new GraphQLTestError(TEST_MESSAGE, Collections.singletonList(new SourceLocation(1, 2)), - ErrorType.DataFetchingException, Collections.emptyList(), null), - "DataFetchingException: Test message at line 1, column 2 in unnamed/unspecified source" - ), + new GraphQLTestError( + TEST_MESSAGE, + Collections.singletonList(new SourceLocation(1, 2)), + ErrorType.DataFetchingException, + Collections.emptyList(), + null), + "DataFetchingException: Test message at line 1, column 2 in unnamed/unspecified source"), Arguments.of( - new GraphQLTestError(TEST_MESSAGE, Collections.singletonList(new SourceLocation(1, 2)), - ErrorType.DataFetchingException, Arrays.asList("path", "to", "error"), null), - "DataFetchingException: Test message at line 1, column 2 in unnamed/unspecified source. Selection path: path/to/error" - ), + new GraphQLTestError( + TEST_MESSAGE, + Collections.singletonList(new SourceLocation(1, 2)), + ErrorType.DataFetchingException, + Arrays.asList("path", "to", "error"), + null), + "DataFetchingException: Test message at line 1, column 2 in unnamed/unspecified source. Selection path: path/to/error"), Arguments.of( - new GraphQLTestError(TEST_MESSAGE, + new GraphQLTestError( + TEST_MESSAGE, Collections.singletonList(new SourceLocation(1, 2, "test.graphql")), - ErrorType.DataFetchingException, Arrays.asList("path", "to", "error"), null), - "DataFetchingException: Test message at line 1, column 2 in test.graphql. Selection path: path/to/error" - ), + ErrorType.DataFetchingException, + Arrays.asList("path", "to", "error"), + null), + "DataFetchingException: Test message at line 1, column 2 in test.graphql. Selection path: path/to/error"), Arguments.of( - new GraphQLTestError(TEST_MESSAGE, Collections.singletonList(new SourceLocation(1, 2)), - ErrorType.DataFetchingException, Arrays.asList("path", 123, "error"), null), - "DataFetchingException: Test message at line 1, column 2 in unnamed/unspecified source. Selection path: path[123]/error" - ), + new GraphQLTestError( + TEST_MESSAGE, + Collections.singletonList(new SourceLocation(1, 2)), + ErrorType.DataFetchingException, + Arrays.asList("path", 123, "error"), + null), + "DataFetchingException: Test message at line 1, column 2 in unnamed/unspecified source. Selection path: path[123]/error"), Arguments.of( - new GraphQLTestError(TEST_MESSAGE, Collections.singletonList(new SourceLocation(1, 2)), - ErrorType.DataFetchingException, Arrays.asList("path", 123, "error"), + new GraphQLTestError( + TEST_MESSAGE, + Collections.singletonList(new SourceLocation(1, 2)), + ErrorType.DataFetchingException, + Arrays.asList("path", 123, "error"), Collections.singletonMap("please ignore", "this")), - "DataFetchingException: Test message at line 1, column 2 in unnamed/unspecified source. Selection path: path[123]/error" - ) - ); + "DataFetchingException: Test message at line 1, column 2 in unnamed/unspecified source. Selection path: path[123]/error")); } @DisplayName("toString should work properly") diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAwaitAndGetResponseTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAwaitAndGetResponseTest.java index 4eb04da6..b2bcfd70 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAwaitAndGetResponseTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionAwaitAndGetResponseTest.java @@ -12,8 +12,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -class GraphQLTestSubscriptionAwaitAndGetResponseTest extends - GraphQLTestSubscriptionTestBase { +class GraphQLTestSubscriptionAwaitAndGetResponseTest extends GraphQLTestSubscriptionTestBase { @Test @DisplayName("Should await and get single response.") @@ -22,7 +21,9 @@ void shouldAwaitAndGetResponse() { graphQLTestSubscription .start(TIMER_SUBSCRIPTION_RESOURCE) .awaitAndGetNextResponse(TIMEOUT) - .assertThatField(DATA_TIMER_FIELD).asLong().isZero(); + .assertThatField(DATA_TIMER_FIELD) + .asLong() + .isZero(); // THEN assertThatSubscriptionWasStopped(); } @@ -31,9 +32,10 @@ void shouldAwaitAndGetResponse() { @DisplayName("Should await and get multiple responses.") void shouldAwaitAndGetMultipleResponses() { // WHEN - final List graphQLResponses = graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .awaitAndGetNextResponses(TIMEOUT, 5); + final List graphQLResponses = + graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) + .awaitAndGetNextResponses(TIMEOUT, 5); // THEN assertThat(graphQLResponses) .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) @@ -47,9 +49,8 @@ void shouldAwaitAndGetAllResponsesDefaultStopAfter() { // GIVEN final Instant timeBeforeTest = Instant.now(); // WHEN - final List graphQLResponses = graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .awaitAndGetAllResponses(TIMEOUT); + final List graphQLResponses = + graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE).awaitAndGetAllResponses(TIMEOUT); // THEN assertThat(graphQLResponses) .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) @@ -61,15 +62,14 @@ void shouldAwaitAndGetAllResponsesDefaultStopAfter() { @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Should await and get all responses.") - void shouldAwaitAndGetAllResponses( - final boolean stopAfter - ) { + void shouldAwaitAndGetAllResponses(final boolean stopAfter) { // GIVEN final Instant timeBeforeTest = Instant.now(); // WHEN - final List graphQLResponses = graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .awaitAndGetAllResponses(TIMEOUT, stopAfter); + final List graphQLResponses = + graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) + .awaitAndGetAllResponses(TIMEOUT, stopAfter); // THEN assertThat(graphQLResponses) .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) @@ -79,21 +79,24 @@ void shouldAwaitAndGetAllResponses( } @Test - @DisplayName("Should handle multiple subsequent await and get calls, assuming stopAfter was false.") + @DisplayName( + "Should handle multiple subsequent await and get calls, assuming stopAfter was false.") void shouldWorkWithMultipleAwaitAndGetCalls() { // GIVEN graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE); // WHEN - graphQLTestSubscription.awaitAndGetNextResponse(TIMEOUT, false) + graphQLTestSubscription + .awaitAndGetNextResponse(TIMEOUT, false) .assertThatField(DATA_TIMER_FIELD) - .asLong().isZero(); + .asLong() + .isZero(); // THEN assertThatSubscriptionWasNotStopped(); // WHEN - final List graphQLResponses = graphQLTestSubscription - .awaitAndGetNextResponses(TIMEOUT, 3, false); + final List graphQLResponses = + graphQLTestSubscription.awaitAndGetNextResponses(TIMEOUT, 3, false); // THEN assertThat(graphQLResponses) .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) @@ -101,8 +104,8 @@ void shouldWorkWithMultipleAwaitAndGetCalls() { assertThatSubscriptionWasNotStopped(); // WHEN - final List graphQLResponses2 = graphQLTestSubscription - .awaitAndGetAllResponses(TIMEOUT); + final List graphQLResponses2 = + graphQLTestSubscription.awaitAndGetAllResponses(TIMEOUT); // THEN assertThat(graphQLResponses2) .extracting(response -> response.get(DATA_TIMER_FIELD, Long.class)) @@ -120,7 +123,9 @@ void shouldHandleSubscriptionWithParameters() { graphQLTestSubscription .start(SUBSCRIPTION_WITH_PARAMETER_RESOURCE, startPayload) .awaitAndGetNextResponse(TIMEOUT) - .assertThatField(DATA_SUBSCRIPTION_WITH_PARAMETER_FIELD).asString().isEqualTo(param); + .assertThatField(DATA_SUBSCRIPTION_WITH_PARAMETER_FIELD) + .asString() + .isEqualTo(param); } @Test @@ -128,14 +133,15 @@ void shouldHandleSubscriptionWithParameters() { void shouldSubscriptionWithInitPayload() { // GIVEN final String initParamValue = String.valueOf(UUID.randomUUID()); - final Map initPayload = Collections - .singletonMap("initParamValue", initParamValue); + final Map initPayload = + Collections.singletonMap("initParamValue", initParamValue); // WHEN - THEN graphQLTestSubscription .init(initPayload) .start(SUBSCRIPTION_WITH_INIT_PAYLOAD_RESOURCE) .awaitAndGetNextResponse(TIMEOUT) - .assertThatField(DATA_SUBSCRIPTION_WITH_INIT_PAYLOAD_FIELD).asString() + .assertThatField(DATA_SUBSCRIPTION_WITH_INIT_PAYLOAD_FIELD) + .asString() .isEqualTo(initParamValue); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionErrorTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionErrorTest.java index c758eae5..ad8b4425 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionErrorTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionErrorTest.java @@ -10,10 +10,13 @@ class GraphQLTestSubscriptionErrorTest extends GraphQLTestSubscriptionTestBase { @DisplayName("Should handle error messages.") void shouldHandleErrorMessages() { // WHEN - THEN - graphQLTestSubscription.start(SUBSCRIPTION_THAT_THROWS_EXCEPTION) + graphQLTestSubscription + .start(SUBSCRIPTION_THAT_THROWS_EXCEPTION) .awaitAndGetNextResponse(TIMEOUT) - .assertThatDataField().isNotPresent() + .assertThatDataField() + .isNotPresent() .and() - .assertThatListOfErrors().isNotEmpty(); + .assertThatListOfErrors() + .isNotEmpty(); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionGetRemainingResponsesTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionGetRemainingResponsesTest.java index 47c50fad..61472185 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionGetRemainingResponsesTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionGetRemainingResponsesTest.java @@ -9,14 +9,14 @@ import org.junit.jupiter.api.Test; @DisplayName("Testing getRemainingResponses") -class GraphQLTestSubscriptionGetRemainingResponsesTest extends - GraphQLTestSubscriptionTestBase { +class GraphQLTestSubscriptionGetRemainingResponsesTest extends GraphQLTestSubscriptionTestBase { @Test @DisplayName("Should properly return remaining responses after the Subscription was stopped.") void shouldGetRemainingResponses() { // WHEN - graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE) + graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) .awaitAndGetNextResponse(TIMEOUT, false); await().atMost(TIMEOUT, MILLISECONDS); graphQLTestSubscription.stop(); diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionResetTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionResetTest.java index 6dc1e342..a47d2c39 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionResetTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionResetTest.java @@ -58,9 +58,11 @@ void shouldAllowStartingNewSubscriptionAfterReset() { } private void startAndAssertThatNewSubscriptionWorks() { - final Integer actual = graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE) - .awaitAndGetNextResponse(TIMEOUT) - .get("$.data.timer", Integer.class); + final Integer actual = + graphQLTestSubscription + .start(TIMER_SUBSCRIPTION_RESOURCE) + .awaitAndGetNextResponse(TIMEOUT) + .get("$.data.timer", Integer.class); assertThat(actual).isZero(); } @@ -70,9 +72,12 @@ private void assertThatSubscriptionWasReset() { assertThat(graphQLTestSubscription.isStarted()).isFalse(); assertThat(graphQLTestSubscription.isStopped()).isFalse(); assertThat(graphQLTestSubscription.isCompleted()).isFalse(); - assertThat(((SubscriptionState) ReflectionTestUtils - .getField(graphQLTestSubscription, GraphQLTestSubscription.class, - "state")).getResponses()).isEmpty(); + assertThat( + ((SubscriptionState) + ReflectionTestUtils.getField( + graphQLTestSubscription, GraphQLTestSubscription.class, "state")) + .getResponses()) + .isEmpty(); assertThat(graphQLTestSubscription.getSession()).isNull(); } @@ -81,7 +86,9 @@ private void assertThatNewIdWasGenerated(int previousId) { } private int getSubscriptionId() { - return ((SubscriptionState) ReflectionTestUtils - .getField(graphQLTestSubscription, GraphQLTestSubscription.class, "state")).getId(); + return ((SubscriptionState) + ReflectionTestUtils.getField( + graphQLTestSubscription, GraphQLTestSubscription.class, "state")) + .getId(); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionTestBase.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionTestBase.java index 004fde14..4aff72d1 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionTestBase.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionTestBase.java @@ -3,6 +3,8 @@ import static org.assertj.core.api.Assertions.assertThat; import com.fasterxml.jackson.databind.ObjectMapper; +import java.time.Duration; +import java.time.Instant; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Timeout; @@ -10,38 +12,36 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.Environment; -import java.time.Duration; -import java.time.Instant; - @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @Timeout(60) public class GraphQLTestSubscriptionTestBase { protected static final String TIMER_SUBSCRIPTION_RESOURCE = "timer-subscription-resource.graphql"; - protected static final String SUBSCRIPTION_WITH_PARAMETER_RESOURCE = "subscription-with-param-resource.graphql"; - protected static final String SUBSCRIPTION_WITH_INIT_PAYLOAD_RESOURCE - = "subscription-with-init-payload-resource.graphql"; - protected static final String SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE - = "subscription-that-times-out-resource.graphql"; - protected static final String SUBSCRIPTION_THAT_THROWS_EXCEPTION - = "subscription-that-throws-exception-resource.graphql"; + protected static final String SUBSCRIPTION_WITH_PARAMETER_RESOURCE = + "subscription-with-param-resource.graphql"; + protected static final String SUBSCRIPTION_WITH_INIT_PAYLOAD_RESOURCE = + "subscription-with-init-payload-resource.graphql"; + protected static final String SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE = + "subscription-that-times-out-resource.graphql"; + protected static final String SUBSCRIPTION_THAT_THROWS_EXCEPTION = + "subscription-that-throws-exception-resource.graphql"; protected static final String DATA_TIMER_FIELD = "$.data.timer"; - protected static final String DATA_SUBSCRIPTION_WITH_PARAMETER_FIELD = "$.data.subscriptionWithParameter"; - protected static final String DATA_SUBSCRIPTION_WITH_INIT_PAYLOAD_FIELD = "$.data.subscriptionWithInitPayload"; + protected static final String DATA_SUBSCRIPTION_WITH_PARAMETER_FIELD = + "$.data.subscriptionWithParameter"; + protected static final String DATA_SUBSCRIPTION_WITH_INIT_PAYLOAD_FIELD = + "$.data.subscriptionWithInitPayload"; protected static final int TIMEOUT = 2000; - @Autowired - protected Environment environment; + @Autowired protected Environment environment; - @Autowired - protected ObjectMapper objectMapper; + @Autowired protected ObjectMapper objectMapper; protected GraphQLTestSubscription graphQLTestSubscription; @BeforeEach protected void setUp() { - graphQLTestSubscription = new GraphQLTestSubscription(environment, objectMapper, - "subscriptions"); + graphQLTestSubscription = + new GraphQLTestSubscription(environment, objectMapper, "subscriptions"); } @AfterEach @@ -58,9 +58,7 @@ protected void assertThatSubscriptionStoppedStatusIs(boolean isStopped) { } protected void assertThatSubscriptionWasStopped() { - assertThat(graphQLTestSubscription.isStopped()) - .as("Subscription should be stopped.") - .isTrue(); + assertThat(graphQLTestSubscription.isStopped()).as("Subscription should be stopped.").isTrue(); } protected void assertThatSubscriptionWasNotStopped() { diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionUsageErrorHandlingTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionUsageErrorHandlingTest.java index 210ff109..4599f605 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionUsageErrorHandlingTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestSubscriptionUsageErrorHandlingTest.java @@ -20,11 +20,9 @@ void shouldRaiseAssertionErrorIfInitAfterInit() { @Test @DisplayName("Should raise an assertion error if awaitAndGet times out.") void shouldRaiseAssertionErrorIfAwaitAndGetTimesOut() { - graphQLTestSubscription - .start(SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE); + graphQLTestSubscription.start(SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE); assertThatExceptionOfType(ConditionTimeoutException.class) - .isThrownBy(() -> graphQLTestSubscription - .awaitAndGetNextResponse(110)); + .isThrownBy(() -> graphQLTestSubscription.awaitAndGetNextResponse(110)); } @Test @@ -53,15 +51,14 @@ void shouldRaiseAssertionErrorIfStopAfterStop() { @Test @DisplayName("Should raise an assertion error if awaitAndGet methods are called after stop.") void shouldRaiseAssertionErrorIfGettingResponseAfterStop() { - graphQLTestSubscription - .start(TIMER_SUBSCRIPTION_RESOURCE) - .stop(); + graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE).stop(); assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> graphQLTestSubscription.awaitAndGetNextResponse(TIMEOUT)); } @Test - @DisplayName("Should raise an assertion error if the provided GraphQL resource could not be found.") + @DisplayName( + "Should raise an assertion error if the provided GraphQL resource could not be found.") void shouldRaiseAssertionErrorIfGraphQLResourceCouldNotBeFound() { assertThatExceptionOfType(AssertionError.class) .isThrownBy(() -> graphQLTestSubscription.start("non-existing-file.graphql")); diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateIntegrationTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateIntegrationTest.java index d827da2e..723e85a5 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateIntegrationTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateIntegrationTest.java @@ -20,7 +20,8 @@ class GraphQLTestTemplateIntegrationTest { private static final String SIMPLE_TEST_QUERY = "simple-test-query.graphql"; - private static final String SIMPLE_TEST_QUERY_WITH_FRAGMENTS = "simple-test-query-with-fragments.graphql"; + private static final String SIMPLE_TEST_QUERY_WITH_FRAGMENTS = + "simple-test-query-with-fragments.graphql"; private static final String TEST_FRAGMENT_FILE = "foo-bar-fragment.graphql"; private static final String QUERY_WITH_VARIABLES = "query-with-variables.graphql"; private static final String COMPLEX_TEST_QUERY = "complex-query.graphql"; @@ -44,38 +45,40 @@ class GraphQLTestTemplateIntegrationTest { private static final String OPERATION_NAME_COMPLEX_QUERY = "complexQuery"; private static final String GRAPHQL_ENDPOINT = "/graphql"; - @Autowired - private ResourceLoader resourceLoader; + @Autowired private ResourceLoader resourceLoader; - @Autowired - private TestRestTemplate testRestTemplate; + @Autowired private TestRestTemplate testRestTemplate; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; private GraphQLTestTemplate graphQLTestTemplate; @BeforeEach void setUp() { - graphQLTestTemplate = new GraphQLTestTemplate(resourceLoader, testRestTemplate, - GRAPHQL_ENDPOINT, objectMapper); + graphQLTestTemplate = + new GraphQLTestTemplate(resourceLoader, testRestTemplate, GRAPHQL_ENDPOINT, objectMapper); } @Test @DisplayName("Test postForResource with only the GraphQL resource provided.") void testPostForResource() throws IOException { - graphQLTestTemplate.postForResource(SIMPLE_TEST_QUERY) + graphQLTestTemplate + .postForResource(SIMPLE_TEST_QUERY) .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_OTHER_QUERY).asString().isEqualTo(TEST); + .assertThatField(DATA_FIELD_OTHER_QUERY) + .asString() + .isEqualTo(TEST); } @Test @DisplayName("Test postForResource with fragments.") void testPostForResourceWithFragments() throws IOException { - graphQLTestTemplate.postForResource(SIMPLE_TEST_QUERY_WITH_FRAGMENTS, - Collections.singletonList(TEST_FRAGMENT_FILE)) + graphQLTestTemplate + .postForResource( + SIMPLE_TEST_QUERY_WITH_FRAGMENTS, Collections.singletonList(TEST_FRAGMENT_FILE)) .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_FOO_BAR).as(FooBar.class) + .assertThatField(DATA_FIELD_FOO_BAR) + .as(FooBar.class) .usingRecursiveComparison() .ignoringAllOverriddenEquals() .isEqualTo(FooBar.builder().foo(FOO).bar(BAR).build()); @@ -88,9 +91,12 @@ void testPerformWithVariables() throws IOException { final ObjectNode variables = objectMapper.createObjectNode(); variables.put(INPUT_STRING_NAME, INPUT_STRING_VALUE); // WHEN - THEN - graphQLTestTemplate.perform(QUERY_WITH_VARIABLES, variables) + graphQLTestTemplate + .perform(QUERY_WITH_VARIABLES, variables) .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString().isEqualTo(INPUT_STRING_VALUE); + .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES) + .asString() + .isEqualTo(INPUT_STRING_VALUE); } @Test @@ -100,25 +106,32 @@ void testPerformWithOperationAndVariables() throws IOException { final ObjectNode variables = objectMapper.createObjectNode(); variables.put(INPUT_STRING_NAME, INPUT_STRING_VALUE); // WHEN - THEN - graphQLTestTemplate.perform(MULTIPLE_QUERIES, OPERATION_NAME_WITH_VARIABLES, variables) + graphQLTestTemplate + .perform(MULTIPLE_QUERIES, OPERATION_NAME_WITH_VARIABLES, variables) .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString().isEqualTo(INPUT_STRING_VALUE); + .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES) + .asString() + .isEqualTo(INPUT_STRING_VALUE); } @Test @DisplayName("Test perform with variables and fragments") void testPerformWithVariablesAndFragments() throws IOException { // GIVEN - final FooBar expected = new FooBar(String.valueOf(UUID.randomUUID()), - String.valueOf(UUID.randomUUID())); + final FooBar expected = + new FooBar(String.valueOf(UUID.randomUUID()), String.valueOf(UUID.randomUUID())); final ObjectNode variables = objectMapper.valueToTree(expected); // WHEN - THEN graphQLTestTemplate - .perform(SIMPLE_TEST_QUERY_WITH_FRAGMENTS, variables, + .perform( + SIMPLE_TEST_QUERY_WITH_FRAGMENTS, + variables, Collections.singletonList(TEST_FRAGMENT_FILE)) .assertThatNoErrorsArePresent() .assertThatField(DATA_FIELD_FOO_BAR) - .as(FooBar.class).usingRecursiveComparison().ignoringAllOverriddenEquals() + .as(FooBar.class) + .usingRecursiveComparison() + .ignoringAllOverriddenEquals() .isEqualTo(expected); } @@ -126,12 +139,18 @@ void testPerformWithVariablesAndFragments() throws IOException { @DisplayName("Test perform with operation name.") void testPerformWithOperationName() throws IOException { // WHEN - THEN - graphQLTestTemplate.perform(MULTIPLE_QUERIES, OPERATION_NAME_TEST_QUERY_1) + graphQLTestTemplate + .perform(MULTIPLE_QUERIES, OPERATION_NAME_TEST_QUERY_1) .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_DUMMY).asBoolean().isTrue(); - graphQLTestTemplate.perform(MULTIPLE_QUERIES, OPERATION_NAME_TEST_QUERY_2) + .assertThatField(DATA_FIELD_DUMMY) + .asBoolean() + .isTrue(); + graphQLTestTemplate + .perform(MULTIPLE_QUERIES, OPERATION_NAME_TEST_QUERY_2) .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_OTHER_QUERY).asString().isEqualTo(TEST); + .assertThatField(DATA_FIELD_OTHER_QUERY) + .asString() + .isEqualTo(TEST); } @Test @@ -139,9 +158,14 @@ void testPerformWithOperationName() throws IOException { void testPerformWithGraphQLError() throws IOException { graphQLTestTemplate .postForResource(SIMPLE_TEST_QUERY, Collections.singletonList(TEST_FRAGMENT_FILE)) - .assertThatDataField().isNotPresentOrNull() - .and().assertThatNumberOfErrors().isOne() - .and().assertThatListOfErrors().extracting(GraphQLError::getMessage) + .assertThatDataField() + .isNotPresentOrNull() + .and() + .assertThatNumberOfErrors() + .isOne() + .and() + .assertThatListOfErrors() + .extracting(GraphQLError::getMessage) .allMatch(message -> message.contains("UnusedFragment")); } @@ -157,13 +181,23 @@ void testPerformWithAllInputs() throws IOException { // WHEN - THEN graphQLTestTemplate .withHeaders(httpHeaders) - .perform(COMPLEX_TEST_QUERY, OPERATION_NAME_COMPLEX_QUERY, variables, + .perform( + COMPLEX_TEST_QUERY, + OPERATION_NAME_COMPLEX_QUERY, + variables, Collections.singletonList(TEST_FRAGMENT_FILE)) .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_QUERY_WITH_HEADER).asString().isEqualTo(TEST_HEADER_VALUE) - .and().assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString() + .assertThatField(DATA_FIELD_QUERY_WITH_HEADER) + .asString() + .isEqualTo(TEST_HEADER_VALUE) + .and() + .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES) + .asString() .isEqualTo(INPUT_STRING_VALUE) - .and().assertThatField(DATA_FIELD_FOO_BAR).as(FooBar.class).isEqualTo(new FooBar(FOO, BAR)); + .and() + .assertThatField(DATA_FIELD_FOO_BAR) + .as(FooBar.class) + .isEqualTo(new FooBar(FOO, BAR)); } @Test @@ -172,17 +206,22 @@ void testPost() { // GIVEN final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(TEST_HEADER_NAME, TEST_HEADER_VALUE); - final String payload = "{\"query\":" - + "\"query ($input: String!, $headerName: String!) " - + "{ queryWithVariables(input: $input) queryWithHeader(headerName: $headerName) }\", " - + "\"variables\": {\"input\": \"input-value\", \"headerName\": \"x-test\"}}"; + final String payload = + "{\"query\":" + + "\"query ($input: String!, $headerName: String!) " + + "{ queryWithVariables(input: $input) queryWithHeader(headerName: $headerName) }\", " + + "\"variables\": {\"input\": \"input-value\", \"headerName\": \"x-test\"}}"; // WHEN - THEN graphQLTestTemplate .withHeaders(httpHeaders) .post(payload) .assertThatNoErrorsArePresent() - .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES).asString().isEqualTo(INPUT_STRING_VALUE) - .and().assertThatField(DATA_FIELD_QUERY_WITH_HEADER).asString() + .assertThatField(DATA_FIELD_QUERY_WITH_VARIABLES) + .asString() + .isEqualTo(INPUT_STRING_VALUE) + .and() + .assertThatField(DATA_FIELD_QUERY_WITH_HEADER) + .asString() .isEqualTo(TEST_HEADER_VALUE); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateTest.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateTest.java index 540f0baa..33d61eca 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateTest.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/GraphQLTestTemplateTest.java @@ -29,27 +29,26 @@ class GraphQLTestTemplateTest { private static final String BASIC_AUTH_PREFIX = "Basic "; private static final String BEARER_AUTH_PREFIX = "Bearer "; - @Mock - private ResourceLoader resourceLoader; + @Mock private ResourceLoader resourceLoader; - @Mock - private TestRestTemplate testRestTemplate; + @Mock private TestRestTemplate testRestTemplate; private GraphQLTestTemplate graphQLTestTemplate; @BeforeEach void setUp() { - graphQLTestTemplate = new GraphQLTestTemplate(resourceLoader, testRestTemplate, - GRAPHQL_ENDPOINT, - new ObjectMapper()); + graphQLTestTemplate = + new GraphQLTestTemplate( + resourceLoader, testRestTemplate, GRAPHQL_ENDPOINT, new ObjectMapper()); } @Test void testWithAdditionalHeader() { // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate - .withAdditionalHeader(HEADER_NAME_1, HEADER_VALUE_1) - .withAdditionalHeader(HEADER_NAME_2, HEADER_VALUE_2); + final GraphQLTestTemplate actual = + graphQLTestTemplate + .withAdditionalHeader(HEADER_NAME_1, HEADER_VALUE_1) + .withAdditionalHeader(HEADER_NAME_2, HEADER_VALUE_2); // THEN assertThat(actual).isSameAs(graphQLTestTemplate); assertThatContainsAllHeaders(); @@ -62,8 +61,8 @@ void testWithAdditionalHeaders() { final HttpHeaders additionalHeaders = new HttpHeaders(); additionalHeaders.add(HEADER_NAME_2, HEADER_VALUE_2); // WHEN - final GraphQLTestTemplate actualGraphqlTestTemplate = graphQLTestTemplate - .withAdditionalHeaders(additionalHeaders); + final GraphQLTestTemplate actualGraphqlTestTemplate = + graphQLTestTemplate.withAdditionalHeaders(additionalHeaders); // THEN assertThat(actualGraphqlTestTemplate).isSameAs(graphQLTestTemplate); assertThatContainsAllHeaders(); @@ -76,8 +75,7 @@ void testWithHeaders() { final HttpHeaders newHeaders = new HttpHeaders(); newHeaders.add(HEADER_NAME_2, HEADER_VALUE_2); // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate - .withHeaders(newHeaders); + final GraphQLTestTemplate actual = graphQLTestTemplate.withHeaders(newHeaders); // THEN assertThat(actual).isSameAs(graphQLTestTemplate); assertThat(actual.getHeaders()).hasSize(1); @@ -116,8 +114,8 @@ void testWithEncodedBasicAuth() { @Test void testWithBasicAuth() { // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate - .withBasicAuth(TEST_USERNAME, TEST_PASSWORD); + final GraphQLTestTemplate actual = + graphQLTestTemplate.withBasicAuth(TEST_USERNAME, TEST_PASSWORD); // THEN assertThat(actual).isSameAs(graphQLTestTemplate); assertAuthHeader(BASIC_AUTH_PREFIX, ENCODED_BASIC_AUTH); @@ -126,9 +124,8 @@ void testWithBasicAuth() { @Test void testWithBasicAuthCharset() { // WHEN - final GraphQLTestTemplate actual = graphQLTestTemplate - .withBasicAuth(TEST_USERNAME, TEST_PASSWORD, - StandardCharsets.UTF_8); + final GraphQLTestTemplate actual = + graphQLTestTemplate.withBasicAuth(TEST_USERNAME, TEST_PASSWORD, StandardCharsets.UTF_8); // THEN assertThat(actual).isSameAs(graphQLTestTemplate); assertAuthHeader(BASIC_AUTH_PREFIX, ENCODED_BASIC_AUTH); diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/DummyQuery.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/DummyQuery.java index 26aecc58..fe7ce908 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/DummyQuery.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/DummyQuery.java @@ -29,10 +29,9 @@ public String queryWithVariables(final String input) { } public String queryWithHeader( - final String headerName, - final DataFetchingEnvironment dataFetchingEnvironment - ) { - return ((GraphQLServletContext) dataFetchingEnvironment.getContext()).getHttpServletRequest() + final String headerName, final DataFetchingEnvironment dataFetchingEnvironment) { + return ((GraphQLServletContext) dataFetchingEnvironment.getContext()) + .getHttpServletRequest() .getHeader(headerName); } } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/SubscriptionListener.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/SubscriptionListener.java index 5a54a9e2..9b3dc44b 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/SubscriptionListener.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/SubscriptionListener.java @@ -15,13 +15,12 @@ public class SubscriptionListener implements ApolloSubscriptionConnectionListene private final ObjectMapper objectMapper; - @Getter - private String expectedConnectionInitParamValue; + @Getter private String expectedConnectionInitParamValue; @Override public void onConnect(final SubscriptionSession session, final OperationMessage message) { - final InitPayload initPayload = objectMapper - .convertValue(message.getPayload(), InitPayload.class); + final InitPayload initPayload = + objectMapper.convertValue(message.getPayload(), InitPayload.class); expectedConnectionInitParamValue = initPayload.getInitParamValue(); } diff --git a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/TestSubscriptions.java b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/TestSubscriptions.java index d28312b8..6a223cee 100644 --- a/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/TestSubscriptions.java +++ b/graphql-spring-boot-test/src/test/java/com/graphql/spring/boot/test/beans/TestSubscriptions.java @@ -13,8 +13,7 @@ public class TestSubscriptions implements GraphQLSubscriptionResolver { private final SubscriptionListener subscriptionListener; public Flowable timer() { - return Flowable - .intervalRange(0, 10, 0, 1, TimeUnit.MILLISECONDS); + return Flowable.intervalRange(0, 10, 0, 1, TimeUnit.MILLISECONDS); } public Flowable subscriptionWithParameter(final String param) { diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundAutoConfiguration.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundAutoConfiguration.java index d560c159..0f8ff508 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundAutoConfiguration.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundAutoConfiguration.java @@ -12,10 +12,14 @@ @EnableConfigurationProperties(PlaygroundPropertiesConfiguration.class) public class PlaygroundAutoConfiguration { - @Bean - @ConditionalOnProperty(value = "graphql.playground.enabled", havingValue = "true", matchIfMissing = true) - public PlaygroundController playgroundController(final PlaygroundPropertiesConfiguration playgroundPropertiesConfiguration, - final ObjectMapper objectMapper) { - return new PlaygroundController(playgroundPropertiesConfiguration, objectMapper); - } + @Bean + @ConditionalOnProperty( + value = "graphql.playground.enabled", + havingValue = "true", + matchIfMissing = true) + public PlaygroundController playgroundController( + final PlaygroundPropertiesConfiguration playgroundPropertiesConfiguration, + final ObjectMapper objectMapper) { + return new PlaygroundController(playgroundPropertiesConfiguration, objectMapper); + } } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundController.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundController.java index c6e3c111..b452809e 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundController.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundController.java @@ -1,72 +1,75 @@ package graphql.kickstart.playground.boot; +import static java.util.Objects.nonNull; + import com.fasterxml.jackson.databind.ObjectMapper; +import java.nio.file.Paths; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestAttribute; -import java.nio.file.Paths; - -import static java.util.Objects.nonNull; - @Controller @RequiredArgsConstructor public class PlaygroundController { - private static final String CDN_ROOT = "https://cdn.jsdelivr.net/npm/graphql-playground-react"; - private static final String CSS_PATH = "static/css/index.css"; - private static final String FAVICON_PATH = "favicon.png"; - private static final String SCRIPT_PATH = "static/js/middleware.js"; - private static final String LOGO_PATH = "logo.png"; + private static final String CDN_ROOT = "https://cdn.jsdelivr.net/npm/graphql-playground-react"; + private static final String CSS_PATH = "static/css/index.css"; + private static final String FAVICON_PATH = "favicon.png"; + private static final String SCRIPT_PATH = "static/js/middleware.js"; + private static final String LOGO_PATH = "logo.png"; - private static final String CSS_URL_ATTRIBUTE_NAME = "cssUrl"; - private static final String FAVICON_URL_ATTRIBUTE_NAME = "faviconUrl"; - private static final String SCRIPT_URL_ATTRIBUTE_NAME = "scriptUrl"; - private static final String LOGO_URL_ATTRIBUTE_NAME = "logoUrl"; - private static final String _CSRF = "_csrf"; + private static final String CSS_URL_ATTRIBUTE_NAME = "cssUrl"; + private static final String FAVICON_URL_ATTRIBUTE_NAME = "faviconUrl"; + private static final String SCRIPT_URL_ATTRIBUTE_NAME = "scriptUrl"; + private static final String LOGO_URL_ATTRIBUTE_NAME = "logoUrl"; + private static final String _CSRF = "_csrf"; - private final PlaygroundPropertiesConfiguration propertiesConfiguration; + private final PlaygroundPropertiesConfiguration propertiesConfiguration; - private final ObjectMapper objectMapper; + private final ObjectMapper objectMapper; - @GetMapping("${graphql.playground.mapping:/playground}") - public String playground(final Model model, final @RequestAttribute(value = _CSRF, required = false) Object csrf) { - if (propertiesConfiguration.getPlayground().getCdn().isEnabled()) { - setCdnUrls(model); - } else { - setLocalAssetUrls(model); - } - model.addAttribute("pageTitle", propertiesConfiguration.getPlayground().getPageTitle()); - model.addAttribute("properties", objectMapper.valueToTree(propertiesConfiguration.getPlayground())); - if (nonNull(csrf)) { - model.addAttribute(_CSRF, csrf); - } - return "playground"; + @GetMapping("${graphql.playground.mapping:/playground}") + public String playground( + final Model model, final @RequestAttribute(value = _CSRF, required = false) Object csrf) { + if (propertiesConfiguration.getPlayground().getCdn().isEnabled()) { + setCdnUrls(model); + } else { + setLocalAssetUrls(model); } - - private String getCdnUrl(final String assetPath) { - return String.format("%s@%s/build/%s", CDN_ROOT, propertiesConfiguration.getPlayground().getCdn().getVersion(), - assetPath); + model.addAttribute("pageTitle", propertiesConfiguration.getPlayground().getPageTitle()); + model.addAttribute( + "properties", objectMapper.valueToTree(propertiesConfiguration.getPlayground())); + if (nonNull(csrf)) { + model.addAttribute(_CSRF, csrf); } + return "playground"; + } - private String getLocalUrl(final String assetPath) { - return Paths.get(propertiesConfiguration.getPlayground().getStaticPath().getBase(), assetPath).toString() - .replace('\\', '/'); - } + private String getCdnUrl(final String assetPath) { + return String.format( + "%s@%s/build/%s", + CDN_ROOT, propertiesConfiguration.getPlayground().getCdn().getVersion(), assetPath); + } - private void setCdnUrls(final Model model) { - model.addAttribute(CSS_URL_ATTRIBUTE_NAME, getCdnUrl(CSS_PATH)); - model.addAttribute(FAVICON_URL_ATTRIBUTE_NAME, getCdnUrl(FAVICON_PATH)); - model.addAttribute(SCRIPT_URL_ATTRIBUTE_NAME, getCdnUrl(SCRIPT_PATH)); - model.addAttribute(LOGO_URL_ATTRIBUTE_NAME, getCdnUrl(LOGO_PATH)); - } + private String getLocalUrl(final String assetPath) { + return Paths.get(propertiesConfiguration.getPlayground().getStaticPath().getBase(), assetPath) + .toString() + .replace('\\', '/'); + } - private void setLocalAssetUrls(final Model model) { - model.addAttribute(CSS_URL_ATTRIBUTE_NAME, getLocalUrl(CSS_PATH)); - model.addAttribute(FAVICON_URL_ATTRIBUTE_NAME, getLocalUrl(FAVICON_PATH)); - model.addAttribute(SCRIPT_URL_ATTRIBUTE_NAME, getLocalUrl(SCRIPT_PATH)); - model.addAttribute(LOGO_URL_ATTRIBUTE_NAME, getLocalUrl(LOGO_PATH)); - } + private void setCdnUrls(final Model model) { + model.addAttribute(CSS_URL_ATTRIBUTE_NAME, getCdnUrl(CSS_PATH)); + model.addAttribute(FAVICON_URL_ATTRIBUTE_NAME, getCdnUrl(FAVICON_PATH)); + model.addAttribute(SCRIPT_URL_ATTRIBUTE_NAME, getCdnUrl(SCRIPT_PATH)); + model.addAttribute(LOGO_URL_ATTRIBUTE_NAME, getCdnUrl(LOGO_PATH)); + } + + private void setLocalAssetUrls(final Model model) { + model.addAttribute(CSS_URL_ATTRIBUTE_NAME, getLocalUrl(CSS_PATH)); + model.addAttribute(FAVICON_URL_ATTRIBUTE_NAME, getLocalUrl(FAVICON_PATH)); + model.addAttribute(SCRIPT_URL_ATTRIBUTE_NAME, getLocalUrl(SCRIPT_PATH)); + model.addAttribute(LOGO_URL_ATTRIBUTE_NAME, getLocalUrl(LOGO_PATH)); + } } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundPropertiesConfiguration.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundPropertiesConfiguration.java index a9de91e3..c0d31d1e 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundPropertiesConfiguration.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundPropertiesConfiguration.java @@ -11,6 +11,5 @@ @Validated public class PlaygroundPropertiesConfiguration { - @NestedConfigurationProperty - private PlaygroundProperties playground = new PlaygroundProperties(); + @NestedConfigurationProperty private PlaygroundProperties playground = new PlaygroundProperties(); } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundWebFluxAutoConfiguration.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundWebFluxAutoConfiguration.java index 7a55a166..a095e944 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundWebFluxAutoConfiguration.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundWebFluxAutoConfiguration.java @@ -1,11 +1,9 @@ package graphql.kickstart.playground.boot; +import java.nio.charset.StandardCharsets; import lombok.RequiredArgsConstructor; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -21,38 +19,42 @@ import org.thymeleaf.templatemode.TemplateMode; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; -import java.nio.charset.StandardCharsets; - @Configuration @Import(PlaygroundWebFluxControllerAdvice.class) @ConditionalOnClass(WebFluxConfigurer.class) -@ConditionalOnProperty(value = "graphql.playground.enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty( + value = "graphql.playground.enabled", + havingValue = "true", + matchIfMissing = true) @RequiredArgsConstructor public class PlaygroundWebFluxAutoConfiguration implements WebFluxConfigurer { - private final ApplicationContext applicationContext; + private final ApplicationContext applicationContext; - @Bean - public RouterFunction playgroundStaticFilesRouter() { - return RouterFunctions.resources("/vendor/playground/**", new ClassPathResource("static/vendor/playground/")); - } + @Bean + public RouterFunction playgroundStaticFilesRouter() { + return RouterFunctions.resources( + "/vendor/playground/**", new ClassPathResource("static/vendor/playground/")); + } - @Override - public void configureViewResolvers(final ViewResolverRegistry registry) { - final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); - templateResolver.setPrefix("templates/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode(TemplateMode.HTML); - templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.displayName()); - templateResolver.setOrder(1); - templateResolver.setCheckExistence(true); - final SpringWebFluxTemplateEngine springWebFluxTemplateEngine = new SpringWebFluxTemplateEngine(); - springWebFluxTemplateEngine.setTemplateResolver(templateResolver); - final ThymeleafReactiveViewResolver thymeleafReactiveViewResolver = new ThymeleafReactiveViewResolver(); - thymeleafReactiveViewResolver.setDefaultCharset(StandardCharsets.UTF_8); - thymeleafReactiveViewResolver.setApplicationContext(applicationContext); - thymeleafReactiveViewResolver.setTemplateEngine(springWebFluxTemplateEngine); - thymeleafReactiveViewResolver.setViewNames(new String[] {"playground"}); - registry.viewResolver(thymeleafReactiveViewResolver); - } + @Override + public void configureViewResolvers(final ViewResolverRegistry registry) { + final ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); + templateResolver.setPrefix("templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode(TemplateMode.HTML); + templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.displayName()); + templateResolver.setOrder(1); + templateResolver.setCheckExistence(true); + final SpringWebFluxTemplateEngine springWebFluxTemplateEngine = + new SpringWebFluxTemplateEngine(); + springWebFluxTemplateEngine.setTemplateResolver(templateResolver); + final ThymeleafReactiveViewResolver thymeleafReactiveViewResolver = + new ThymeleafReactiveViewResolver(); + thymeleafReactiveViewResolver.setDefaultCharset(StandardCharsets.UTF_8); + thymeleafReactiveViewResolver.setApplicationContext(applicationContext); + thymeleafReactiveViewResolver.setTemplateEngine(springWebFluxTemplateEngine); + thymeleafReactiveViewResolver.setViewNames(new String[] {"playground"}); + registry.viewResolver(thymeleafReactiveViewResolver); + } } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundWebFluxControllerAdvice.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundWebFluxControllerAdvice.java index 6b69844c..271181a6 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundWebFluxControllerAdvice.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundWebFluxControllerAdvice.java @@ -12,12 +12,12 @@ @NoArgsConstructor @ControllerAdvice -@ConditionalOnClass({ CsrfToken.class, CsrfRequestDataValueProcessor.class }) +@ConditionalOnClass({CsrfToken.class, CsrfRequestDataValueProcessor.class}) @ConditionalOnBean(CsrfRequestDataValueProcessor.class) public class PlaygroundWebFluxControllerAdvice { - @ModelAttribute(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME) - public Mono getCsrfToken(final ServerWebExchange exchange) { - return exchange.getAttributeOrDefault(CsrfToken.class.getName(), Mono.empty()); - } + @ModelAttribute(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME) + public Mono getCsrfToken(final ServerWebExchange exchange) { + return exchange.getAttributeOrDefault(CsrfToken.class.getName(), Mono.empty()); + } } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/ResourceSerializer.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/ResourceSerializer.java index a76302b2..f48e77db 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/ResourceSerializer.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/ResourceSerializer.java @@ -3,19 +3,19 @@ import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import org.apache.tomcat.util.http.fileupload.util.Streams; import org.springframework.boot.jackson.JsonComponent; import org.springframework.core.io.Resource; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - @JsonComponent public class ResourceSerializer extends JsonSerializer { - @Override - public void serialize(final Resource value, final JsonGenerator gen, final SerializerProvider serializers) - throws IOException { - final String content = Streams.asString(value.getInputStream(), StandardCharsets.UTF_8.name()); - gen.writeString(content); - } + @Override + public void serialize( + final Resource value, final JsonGenerator gen, final SerializerProvider serializers) + throws IOException { + final String content = Streams.asString(value.getInputStream(), StandardCharsets.UTF_8.name()); + gen.writeString(content); + } } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundCdn.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundCdn.java index c95a104e..3734c334 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundCdn.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundCdn.java @@ -1,13 +1,11 @@ package graphql.kickstart.playground.boot.properties; -import lombok.Data; - import javax.validation.constraints.NotBlank; +import lombok.Data; @Data public class PlaygroundCdn { - private boolean enabled; - @NotBlank - private String version = "latest"; + private boolean enabled; + @NotBlank private String version = "latest"; } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundProperties.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundProperties.java index bc810f81..2820bdcd 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundProperties.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundProperties.java @@ -2,40 +2,31 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; -import lombok.Data; -import org.springframework.boot.context.properties.NestedConfigurationProperty; - -import javax.validation.constraints.NotBlank; import java.util.Collections; import java.util.List; import java.util.Map; +import javax.validation.constraints.NotBlank; +import lombok.Data; +import org.springframework.boot.context.properties.NestedConfigurationProperty; @Data @JsonInclude(JsonInclude.Include.NON_EMPTY) public class PlaygroundProperties { - @NotBlank - private String endpoint = "/graphql"; + @NotBlank private String endpoint = "/graphql"; - @NotBlank - private String subscriptionEndpoint = "/subscriptions"; + @NotBlank private String subscriptionEndpoint = "/subscriptions"; - @NestedConfigurationProperty - @JsonIgnore - private PlaygroundCdn cdn = new PlaygroundCdn(); + @NestedConfigurationProperty @JsonIgnore private PlaygroundCdn cdn = new PlaygroundCdn(); - @NestedConfigurationProperty - @JsonIgnore - private PlaygroundStaticPathSettings staticPath = new PlaygroundStaticPathSettings(); + @NestedConfigurationProperty @JsonIgnore + private PlaygroundStaticPathSettings staticPath = new PlaygroundStaticPathSettings(); - @JsonIgnore - private String pageTitle = "Playground"; + @JsonIgnore private String pageTitle = "Playground"; - @NestedConfigurationProperty - private PlaygroundSettings settings; + @NestedConfigurationProperty private PlaygroundSettings settings; - private Map headers = Collections.emptyMap(); + private Map headers = Collections.emptyMap(); - @NestedConfigurationProperty - private List tabs = Collections.emptyList(); + @NestedConfigurationProperty private List tabs = Collections.emptyList(); } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundSettings.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundSettings.java index f514a5ca..4bae2eb7 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundSettings.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundSettings.java @@ -14,23 +14,23 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class PlaygroundSettings { - @NestedConfigurationProperty - @JsonUnwrapped(prefix = "editor.") - private PlaygroundEditorSettings editor; + @NestedConfigurationProperty + @JsonUnwrapped(prefix = "editor.") + private PlaygroundEditorSettings editor; - @NestedConfigurationProperty - @JsonUnwrapped(prefix = "prettier.") - private PlaygroundPrettierSettings prettier; + @NestedConfigurationProperty + @JsonUnwrapped(prefix = "prettier.") + private PlaygroundPrettierSettings prettier; - @NestedConfigurationProperty - @JsonUnwrapped(prefix = "request.") - private PlaygroundRequestSettings request; + @NestedConfigurationProperty + @JsonUnwrapped(prefix = "request.") + private PlaygroundRequestSettings request; - @NestedConfigurationProperty - @JsonUnwrapped(prefix = "schema.") - private PlaygroundSchemaSettings schema; + @NestedConfigurationProperty + @JsonUnwrapped(prefix = "schema.") + private PlaygroundSchemaSettings schema; - @NestedConfigurationProperty - @JsonUnwrapped(prefix = "tracing.") - private PlaygroundTracingSettings tracing; + @NestedConfigurationProperty + @JsonUnwrapped(prefix = "tracing.") + private PlaygroundTracingSettings tracing; } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundStaticPathSettings.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundStaticPathSettings.java index cb88779c..8289f365 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundStaticPathSettings.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundStaticPathSettings.java @@ -1,12 +1,10 @@ package graphql.kickstart.playground.boot.properties; -import lombok.Data; - import javax.validation.constraints.NotBlank; +import lombok.Data; @Data public class PlaygroundStaticPathSettings { - @NotBlank - private String base = "/vendor/playground"; + @NotBlank private String base = "/vendor/playground"; } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundTab.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundTab.java index 22082f85..cdec45c3 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundTab.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/PlaygroundTab.java @@ -2,45 +2,37 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; import graphql.kickstart.playground.boot.ResourceSerializer; -import lombok.Data; -import org.springframework.core.io.Resource; - import java.util.List; import java.util.Map; +import lombok.Data; +import org.springframework.core.io.Resource; @Data public class PlaygroundTab { - /** - * The GraphQL endpoint for this tab. If not set, the default GraphQL endpoint will be used. - */ - private String endpoint; - - /** - * The GraphQL query (operation) to be initially displayed on the tab. It should be a graphql resource. - */ - @JsonSerialize(using = ResourceSerializer.class) - private Resource query; - - /** - * The name of the tab. - */ - private String name; - - /** - * The query variables. It should be a JSON resource. - */ - @JsonSerialize(using = ResourceSerializer.class) - private Resource variables; - - /** - * The list of responses to be displayed under "responses". It should be a list of JSON resources. - */ - @JsonSerialize(contentUsing = ResourceSerializer.class) - private List responses; - - /** - * HTTP headers. Key-value pairs expected. - */ - private Map headers; + /** The GraphQL endpoint for this tab. If not set, the default GraphQL endpoint will be used. */ + private String endpoint; + + /** + * The GraphQL query (operation) to be initially displayed on the tab. It should be a graphql + * resource. + */ + @JsonSerialize(using = ResourceSerializer.class) + private Resource query; + + /** The name of the tab. */ + private String name; + + /** The query variables. It should be a JSON resource. */ + @JsonSerialize(using = ResourceSerializer.class) + private Resource variables; + + /** + * The list of responses to be displayed under "responses". It should be a list of JSON resources. + */ + @JsonSerialize(contentUsing = ResourceSerializer.class) + private List responses; + + /** HTTP headers. Key-value pairs expected. */ + private Map headers; } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundEditorCursorShape.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundEditorCursorShape.java index 854efd5b..4a4a3ac3 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundEditorCursorShape.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundEditorCursorShape.java @@ -3,10 +3,10 @@ import com.fasterxml.jackson.annotation.JsonProperty; public enum PlaygroundEditorCursorShape { - @JsonProperty("line") - LINE, - @JsonProperty("block") - BLOCK, - @JsonProperty("underline") - UNDERLINE + @JsonProperty("line") + LINE, + @JsonProperty("block") + BLOCK, + @JsonProperty("underline") + UNDERLINE } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundEditorSettings.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundEditorSettings.java index 54f1f5d3..3ce92f3f 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundEditorSettings.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundEditorSettings.java @@ -7,9 +7,9 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class PlaygroundEditorSettings { - private PlaygroundEditorCursorShape cursorShape; - private String fontFamily; - private Integer fontSize; - private PlaygroundEditorTheme theme; - private Boolean reuseHeaders; + private PlaygroundEditorCursorShape cursorShape; + private String fontFamily; + private Integer fontSize; + private PlaygroundEditorTheme theme; + private Boolean reuseHeaders; } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundPrettierSettings.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundPrettierSettings.java index dd9596f7..78eea677 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundPrettierSettings.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundPrettierSettings.java @@ -1,17 +1,18 @@ package graphql.kickstart.playground.boot.properties.settings; import com.fasterxml.jackson.annotation.JsonInclude; -import lombok.Data; - import javax.validation.constraints.Min; +import lombok.Data; @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class PlaygroundPrettierSettings { - @Min(1) - private Integer printWidth; - @Min(1) - private Integer tabWidth; - private Boolean useTabs; + @Min(1) + private Integer printWidth; + + @Min(1) + private Integer tabWidth; + + private Boolean useTabs; } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundRequestIncludeCredentials.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundRequestIncludeCredentials.java index a776723c..2f71fc03 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundRequestIncludeCredentials.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundRequestIncludeCredentials.java @@ -3,10 +3,10 @@ import com.fasterxml.jackson.annotation.JsonProperty; public enum PlaygroundRequestIncludeCredentials { - @JsonProperty("omit") - OMIT, - @JsonProperty("include") - INCLUDE, - @JsonProperty("same-origin") - SAME_ORIGIN + @JsonProperty("omit") + OMIT, + @JsonProperty("include") + INCLUDE, + @JsonProperty("same-origin") + SAME_ORIGIN } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundRequestSettings.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundRequestSettings.java index 0334fdd6..f7a38645 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundRequestSettings.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundRequestSettings.java @@ -7,5 +7,5 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class PlaygroundRequestSettings { - private PlaygroundRequestIncludeCredentials credentials; + private PlaygroundRequestIncludeCredentials credentials; } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundSchemaPollingSettings.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundSchemaPollingSettings.java index d05ba458..47a86e47 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundSchemaPollingSettings.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundSchemaPollingSettings.java @@ -1,16 +1,16 @@ package graphql.kickstart.playground.boot.properties.settings; import com.fasterxml.jackson.annotation.JsonInclude; -import lombok.Data; - import javax.validation.constraints.Min; +import lombok.Data; @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class PlaygroundSchemaPollingSettings { - private Boolean enable; - private String endpointFilter; - @Min(1) - private Integer interval; + private Boolean enable; + private String endpointFilter; + + @Min(1) + private Integer interval; } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundSchemaSettings.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundSchemaSettings.java index 3947b8f6..dc8ff403 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundSchemaSettings.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundSchemaSettings.java @@ -9,9 +9,9 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class PlaygroundSchemaSettings { - private Boolean disableComments; + private Boolean disableComments; - @NestedConfigurationProperty - @JsonUnwrapped(prefix = "polling.") - private PlaygroundSchemaPollingSettings polling; + @NestedConfigurationProperty + @JsonUnwrapped(prefix = "polling.") + private PlaygroundSchemaPollingSettings polling; } diff --git a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundTracingSettings.java b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundTracingSettings.java index 6f69761c..133b60ba 100644 --- a/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundTracingSettings.java +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/properties/settings/PlaygroundTracingSettings.java @@ -7,5 +7,5 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class PlaygroundTracingSettings { - private Boolean hideTracingResponse; + private Boolean hideTracingResponse; } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCSRFTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCSRFTest.java index c8a1f8fe..d9084069 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCSRFTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCSRFTest.java @@ -1,5 +1,10 @@ package graphql.kickstart.playground.boot; +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -11,33 +16,29 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - @ExtendWith(SpringExtension.class) @SpringBootTest(classes = PlaygroundTestConfig.class) @AutoConfigureMockMvc class PlaygroundCSRFTest { - private static final String CSRF_ATTRIBUTE_NAME = "_csrf"; + private static final String CSRF_ATTRIBUTE_NAME = "_csrf"; - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; - @Test - void shouldLoadCSRFData() throws Exception { - final MvcResult mvcResult = mockMvc.perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) - .andExpect(status().isOk()) - .andExpect(model().attributeExists(CSRF_ATTRIBUTE_NAME)) - .andReturn(); + @Test + void shouldLoadCSRFData() throws Exception { + final MvcResult mvcResult = + mockMvc + .perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) + .andExpect(status().isOk()) + .andExpect(model().attributeExists(CSRF_ATTRIBUTE_NAME)) + .andReturn(); - assertThat(mvcResult.getModelAndView()).isNotNull(); - assertThat(mvcResult.getModelAndView().getModel()).isNotNull(); - assertThat(mvcResult.getModelAndView().getModel().get(CSRF_ATTRIBUTE_NAME)).isInstanceOf(CsrfToken.class); - } + assertThat(mvcResult.getModelAndView()).isNotNull(); + assertThat(mvcResult.getModelAndView().getModel()).isNotNull(); + assertThat(mvcResult.getModelAndView().getModel().get(CSRF_ATTRIBUTE_NAME)) + .isInstanceOf(CsrfToken.class); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCdnCustomVersionTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCdnCustomVersionTest.java index 55b06b92..7abda695 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCdnCustomVersionTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCdnCustomVersionTest.java @@ -13,13 +13,12 @@ @TestPropertySource("classpath:application-playground-cdn-custom-version-test.properties") public class PlaygroundCdnCustomVersionTest extends PlaygroundResourcesTestBase { - @Test - public void shouldLoadSpecifiedVersionFromCdn() throws Exception { - testPlaygroundResources( - PlaygroundTestHelper.CUSTOM_VERSION_CSS_CDN_PATH, - PlaygroundTestHelper.CUSTOM_VERSION_SCRIPT_CDN_PATH, - PlaygroundTestHelper.CUSTOM_VERSION_FAVICON_CDN_PATH, - PlaygroundTestHelper.CUSTOM_VERSION_LOGO_CDN_PATH - ); - } + @Test + public void shouldLoadSpecifiedVersionFromCdn() throws Exception { + testPlaygroundResources( + PlaygroundTestHelper.CUSTOM_VERSION_CSS_CDN_PATH, + PlaygroundTestHelper.CUSTOM_VERSION_SCRIPT_CDN_PATH, + PlaygroundTestHelper.CUSTOM_VERSION_FAVICON_CDN_PATH, + PlaygroundTestHelper.CUSTOM_VERSION_LOGO_CDN_PATH); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCdnTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCdnTest.java index afc78e4e..ff4a66e4 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCdnTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCdnTest.java @@ -13,13 +13,12 @@ @TestPropertySource("classpath:application-playground-cdn-test.properties") public class PlaygroundCdnTest extends PlaygroundResourcesTestBase { - @Test - public void shouldLoadLatestVersionFromCdn() throws Exception { - testPlaygroundResources( - PlaygroundTestHelper.DEFAULT_CSS_CDN_PATH, - PlaygroundTestHelper.DEFAULT_SCRIPT_CDN_PATH, - PlaygroundTestHelper.DEFAULT_FAVICON_CDN_PATH, - PlaygroundTestHelper.DEFAULT_LOGO_CDN_PATH - ); - } + @Test + public void shouldLoadLatestVersionFromCdn() throws Exception { + testPlaygroundResources( + PlaygroundTestHelper.DEFAULT_CSS_CDN_PATH, + PlaygroundTestHelper.DEFAULT_SCRIPT_CDN_PATH, + PlaygroundTestHelper.DEFAULT_FAVICON_CDN_PATH, + PlaygroundTestHelper.DEFAULT_LOGO_CDN_PATH); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomMappingTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomMappingTest.java index a6da477c..e55715d8 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomMappingTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomMappingTest.java @@ -23,15 +23,15 @@ @TestPropertySource("classpath:application-playground-mapping-test.properties") public class PlaygroundCustomMappingTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; - @Test - public void shouldUseTheConfiguredRequestMapping() throws Exception { - mockMvc.perform(get(PlaygroundTestHelper.CUSTOM_MAPPING)) - .andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)) - .andExpect(content().encoding(StandardCharsets.UTF_8.name())) - .andExpect(content().string(not(isEmptyString()))); - } + @Test + public void shouldUseTheConfiguredRequestMapping() throws Exception { + mockMvc + .perform(get(PlaygroundTestHelper.CUSTOM_MAPPING)) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)) + .andExpect(content().encoding(StandardCharsets.UTF_8.name())) + .andExpect(content().string(not(isEmptyString()))); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomStaticPathTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomStaticPathTest.java index 354b3997..f18c29c4 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomStaticPathTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomStaticPathTest.java @@ -13,13 +13,12 @@ @TestPropertySource("classpath:application-playground-custom-static-path.properties") public class PlaygroundCustomStaticPathTest extends PlaygroundResourcesTestBase { - @Test - public void shouldLoadStaticResourcesFromCustomPath() throws Exception { - testPlaygroundResources( - PlaygroundTestHelper.CUSTOM_LOCAL_CSS_URL, - PlaygroundTestHelper.CUSTOM_LOCAL_SCRIPT_URL, - PlaygroundTestHelper.CUSTOM_LOCAL_FAVICON_URL, - PlaygroundTestHelper.CUSTOM_LOCAL_LOGO_URL - ); - } + @Test + public void shouldLoadStaticResourcesFromCustomPath() throws Exception { + testPlaygroundResources( + PlaygroundTestHelper.CUSTOM_LOCAL_CSS_URL, + PlaygroundTestHelper.CUSTOM_LOCAL_SCRIPT_URL, + PlaygroundTestHelper.CUSTOM_LOCAL_FAVICON_URL, + PlaygroundTestHelper.CUSTOM_LOCAL_LOGO_URL); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomTitleTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomTitleTest.java index bd57f0c6..2410467a 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomTitleTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundCustomTitleTest.java @@ -22,17 +22,22 @@ @TestPropertySource("classpath:application-playground-custom-title.properties") public class PlaygroundCustomTitleTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; - @Test - public void shouldUseTheCustomPageTitle() throws Exception { - final MvcResult mvcResult = mockMvc.perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) - .andExpect(status().isOk()) - .andExpect(model().attribute(PlaygroundTestHelper.PAGE_TITLE_FIELD_NAME, PlaygroundTestHelper.CUSTOM_TITLE)) - .andReturn(); + @Test + public void shouldUseTheCustomPageTitle() throws Exception { + final MvcResult mvcResult = + mockMvc + .perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) + .andExpect(status().isOk()) + .andExpect( + model() + .attribute( + PlaygroundTestHelper.PAGE_TITLE_FIELD_NAME, + PlaygroundTestHelper.CUSTOM_TITLE)) + .andReturn(); - final Document document = Jsoup.parse(mvcResult.getResponse().getContentAsString()); - PlaygroundTestHelper.assertTitle(document, PlaygroundTestHelper.CUSTOM_TITLE); - } + final Document document = Jsoup.parse(mvcResult.getResponse().getContentAsString()); + PlaygroundTestHelper.assertTitle(document, PlaygroundTestHelper.CUSTOM_TITLE); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundDisabledTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundDisabledTest.java index a60bc831..1e77deb4 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundDisabledTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundDisabledTest.java @@ -15,15 +15,15 @@ import org.springframework.test.web.servlet.MockMvc; @ExtendWith(SpringExtension.class) -@SpringBootTest(classes = PlaygroundTestConfig.class, properties = "graphql.playground.enabled=false") +@SpringBootTest( + classes = PlaygroundTestConfig.class, + properties = "graphql.playground.enabled=false") @AutoConfigureMockMvc class PlaygroundDisabledTest { - @Autowired - private ApplicationContext applicationContext; + @Autowired private ApplicationContext applicationContext; - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test void playgroundShouldNotLoadIfDisabled() { @@ -33,7 +33,8 @@ void playgroundShouldNotLoadIfDisabled() { @Test void playgroundEndpointShouldNotExist() throws Exception { - mockMvc.perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) + mockMvc + .perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) .andExpect(status().isNotFound()); } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundEnabledTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundEnabledTest.java index d4c24989..01548c4c 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundEnabledTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundEnabledTest.java @@ -34,14 +34,11 @@ class PlaygroundEnabledTest { private static final String DEFAULT_LOGO_PATH = "/vendor/playground/logo.png"; private static final String DEFAULT_TITLE = "Playground"; - @Autowired - private ApplicationContext applicationContext; + @Autowired private ApplicationContext applicationContext; - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; @Test void playgroundLoads() { @@ -50,29 +47,33 @@ void playgroundLoads() { @Test void playgroundShouldBeAvailableAtDefaultEndpoint() throws Exception { - final MvcResult mvcResult = mockMvc - .perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) - .andExpect(status().isOk()) - .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)) - .andExpect(content().string(not(is(emptyString())))) - .andExpect(model().attribute(PlaygroundTestHelper.PAGE_TITLE_FIELD_NAME, DEFAULT_TITLE)) - .andExpect(model().attribute(PlaygroundTestHelper.CSS_URL_FIELD_NAME, DEFAULT_CSS_PATH)) - .andExpect( - model().attribute(PlaygroundTestHelper.SCRIPT_URL_FIELD_NAME, DEFAULT_SCRIPT_PATH)) - .andExpect( - model().attribute(PlaygroundTestHelper.FAVICON_URL_FIELD_NAME, DEFAULT_FAVICON_PATH)) - .andExpect(model().attribute(PlaygroundTestHelper.LOGO_URL_FIELD_NAME, DEFAULT_LOGO_PATH)) - .andReturn(); + final MvcResult mvcResult = + mockMvc + .perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) + .andExpect(status().isOk()) + .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)) + .andExpect(content().string(not(is(emptyString())))) + .andExpect(model().attribute(PlaygroundTestHelper.PAGE_TITLE_FIELD_NAME, DEFAULT_TITLE)) + .andExpect(model().attribute(PlaygroundTestHelper.CSS_URL_FIELD_NAME, DEFAULT_CSS_PATH)) + .andExpect( + model().attribute(PlaygroundTestHelper.SCRIPT_URL_FIELD_NAME, DEFAULT_SCRIPT_PATH)) + .andExpect( + model() + .attribute(PlaygroundTestHelper.FAVICON_URL_FIELD_NAME, DEFAULT_FAVICON_PATH)) + .andExpect( + model().attribute(PlaygroundTestHelper.LOGO_URL_FIELD_NAME, DEFAULT_LOGO_PATH)) + .andReturn(); final Document document = Jsoup.parse(mvcResult.getResponse().getContentAsString()); PlaygroundTestHelper.assertTitle(document, DEFAULT_TITLE); - PlaygroundTestHelper.assertStaticResources(document, DEFAULT_CSS_PATH, DEFAULT_SCRIPT_PATH, - DEFAULT_FAVICON_PATH, DEFAULT_LOGO_PATH); + PlaygroundTestHelper.assertStaticResources( + document, DEFAULT_CSS_PATH, DEFAULT_SCRIPT_PATH, DEFAULT_FAVICON_PATH, DEFAULT_LOGO_PATH); } @Test void defaultCssShouldBeAvailable() throws Exception { - mockMvc.perform(get(DEFAULT_CSS_PATH)) + mockMvc + .perform(get(DEFAULT_CSS_PATH)) .andExpect(status().isOk()) .andExpect(content().string(not(is(emptyString())))) .andExpect(content().contentTypeCompatibleWith("text/css")); @@ -80,7 +81,8 @@ void defaultCssShouldBeAvailable() throws Exception { @Test void defaultScriptShouldBeAvailable() throws Exception { - mockMvc.perform(get(DEFAULT_SCRIPT_PATH)) + mockMvc + .perform(get(DEFAULT_SCRIPT_PATH)) .andExpect(status().isOk()) .andExpect(content().string(not(is(emptyString())))) .andExpect(content().contentTypeCompatibleWith("application/javascript")); @@ -88,7 +90,8 @@ void defaultScriptShouldBeAvailable() throws Exception { @Test void defaultFaviconShouldBeAvailable() throws Exception { - mockMvc.perform(get(DEFAULT_FAVICON_PATH)) + mockMvc + .perform(get(DEFAULT_FAVICON_PATH)) .andExpect(status().isOk()) .andExpect(content().string(not(is(emptyString())))) .andExpect(content().contentTypeCompatibleWith("image/png")); @@ -96,7 +99,8 @@ void defaultFaviconShouldBeAvailable() throws Exception { @Test void defaultLogoShouldBeAvailable() throws Exception { - mockMvc.perform(get(DEFAULT_LOGO_PATH)) + mockMvc + .perform(get(DEFAULT_LOGO_PATH)) .andExpect(status().isOk()) .andExpect(content().string(not(is(emptyString())))) .andExpect(content().contentTypeCompatibleWith("image/png")); diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundResourcesTestBase.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundResourcesTestBase.java index 9412fafc..c0d8867e 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundResourcesTestBase.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundResourcesTestBase.java @@ -1,31 +1,33 @@ package graphql.kickstart.playground.boot; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - class PlaygroundResourcesTestBase { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; - void testPlaygroundResources(final String cssUrl, final String scriptUrl, final String faviconUrl, - final String logoUrl) throws Exception { - final MvcResult mvcResult = mockMvc.perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) - .andExpect(status().isOk()) - .andExpect(model().attribute(PlaygroundTestHelper.CSS_URL_FIELD_NAME, cssUrl)) - .andExpect(model().attribute(PlaygroundTestHelper.SCRIPT_URL_FIELD_NAME, scriptUrl)) - .andExpect(model().attribute(PlaygroundTestHelper.FAVICON_URL_FIELD_NAME, faviconUrl)) - .andExpect(model().attribute(PlaygroundTestHelper.LOGO_URL_FIELD_NAME, logoUrl)) - .andReturn(); + void testPlaygroundResources( + final String cssUrl, final String scriptUrl, final String faviconUrl, final String logoUrl) + throws Exception { + final MvcResult mvcResult = + mockMvc + .perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) + .andExpect(status().isOk()) + .andExpect(model().attribute(PlaygroundTestHelper.CSS_URL_FIELD_NAME, cssUrl)) + .andExpect(model().attribute(PlaygroundTestHelper.SCRIPT_URL_FIELD_NAME, scriptUrl)) + .andExpect(model().attribute(PlaygroundTestHelper.FAVICON_URL_FIELD_NAME, faviconUrl)) + .andExpect(model().attribute(PlaygroundTestHelper.LOGO_URL_FIELD_NAME, logoUrl)) + .andReturn(); - final Document document = Jsoup.parse(mvcResult.getResponse().getContentAsString()); - PlaygroundTestHelper.assertStaticResources(document, cssUrl, scriptUrl, faviconUrl, logoUrl); - } + final Document document = Jsoup.parse(mvcResult.getResponse().getContentAsString()); + PlaygroundTestHelper.assertStaticResources(document, cssUrl, scriptUrl, faviconUrl, logoUrl); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundSettingsTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundSettingsTest.java index cb419d32..14de0378 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundSettingsTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundSettingsTest.java @@ -22,11 +22,9 @@ @TestPropertySource("classpath:application-playground-settings-test.properties") class PlaygroundSettingsTest { - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; @Test void shouldProperlyLoadSettings() throws Exception { @@ -68,7 +66,8 @@ void shouldProperlyLoadSettings() throws Exception { expectedNode.set("headers", headers); expectedNode.set("tabs", tabs); - mockMvc.perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) + mockMvc + .perform(get(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT)) .andExpect(status().isOk()) .andExpect(model().attribute("properties", expectedNode)); } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundTestConfig.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundTestConfig.java index 5d1c150b..97337261 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundTestConfig.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundTestConfig.java @@ -11,12 +11,16 @@ @EnableAutoConfiguration(exclude = WebFluxAutoConfiguration.class) @EnableWebSecurity -@ContextConfiguration(classes = {PlaygroundAutoConfiguration.class, ObjectMapper.class, - ThymeleafAutoConfiguration.class}) +@ContextConfiguration( + classes = { + PlaygroundAutoConfiguration.class, + ObjectMapper.class, + ThymeleafAutoConfiguration.class + }) class PlaygroundTestConfig extends WebSecurityConfigurerAdapter { - @Override - protected void configure(final HttpSecurity http) throws Exception { - http.authorizeRequests().anyRequest().permitAll(); - } + @Override + protected void configure(final HttpSecurity http) throws Exception { + http.authorizeRequests().anyRequest().permitAll(); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundTestHelper.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundTestHelper.java index 0599afbf..bf144d18 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundTestHelper.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/PlaygroundTestHelper.java @@ -1,65 +1,79 @@ package graphql.kickstart.playground.boot; +import static org.assertj.core.api.Assertions.assertThat; + import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; -import static org.assertj.core.api.Assertions.assertThat; - public final class PlaygroundTestHelper { - public static final String CUSTOM_LOCAL_CSS_URL = "/custom-static-path/static/css/index.css"; - public static final String CUSTOM_LOCAL_SCRIPT_URL = "/custom-static-path/static/js/middleware.js"; - public static final String CUSTOM_LOCAL_FAVICON_URL = "/custom-static-path/favicon.png"; - public static final String CUSTOM_LOCAL_LOGO_URL = "/custom-static-path/logo.png"; + public static final String CUSTOM_LOCAL_CSS_URL = "/custom-static-path/static/css/index.css"; + public static final String CUSTOM_LOCAL_SCRIPT_URL = + "/custom-static-path/static/js/middleware.js"; + public static final String CUSTOM_LOCAL_FAVICON_URL = "/custom-static-path/favicon.png"; + public static final String CUSTOM_LOCAL_LOGO_URL = "/custom-static-path/logo.png"; + + public static final String DEFAULT_CSS_CDN_PATH = + "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/static/css/index.css"; + public static final String DEFAULT_SCRIPT_CDN_PATH = + "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/static/js/middleware.js"; + public static final String DEFAULT_FAVICON_CDN_PATH = + "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/favicon.png"; + public static final String DEFAULT_LOGO_CDN_PATH = + "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/logo.png"; + + public static final String CUSTOM_VERSION_CSS_CDN_PATH = + "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/static/css/index.css"; + public static final String CUSTOM_VERSION_SCRIPT_CDN_PATH = + "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/static/js/middleware.js"; + public static final String CUSTOM_VERSION_FAVICON_CDN_PATH = + "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/favicon.png"; + public static final String CUSTOM_VERSION_LOGO_CDN_PATH = + "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/logo.png"; + + public static final String CUSTOM_MAPPING = "/test-mapping"; + public static final String CUSTOM_TITLE = "My CustomTest Title"; + public static final String DEFAULT_PLAYGROUND_ENDPOINT = "/playground"; + public static final String CSS_URL_FIELD_NAME = "cssUrl"; + public static final String SCRIPT_URL_FIELD_NAME = "scriptUrl"; + public static final String FAVICON_URL_FIELD_NAME = "faviconUrl"; + public static final String LOGO_URL_FIELD_NAME = "logoUrl"; + public static final String PAGE_TITLE_FIELD_NAME = "pageTitle"; + + public static void assertTitle(final Document document, final String title) { + assertThat(document.select("head title")).extracting(Element::text).containsExactly(title); + } - public static final String DEFAULT_CSS_CDN_PATH - = "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/static/css/index.css"; - public static final String DEFAULT_SCRIPT_CDN_PATH - = "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/static/js/middleware.js"; - public static final String DEFAULT_FAVICON_CDN_PATH - = "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/favicon.png"; - public static final String DEFAULT_LOGO_CDN_PATH - = "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/logo.png"; + private static void assertStylesheet(final Document document, final String cssUrl) { + assertThat(document.select(String.format("head link[rel=stylesheet][href=%s]", cssUrl)).size()) + .isOne(); + } - public static final String CUSTOM_VERSION_CSS_CDN_PATH - = "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/static/css/index.css"; - public static final String CUSTOM_VERSION_SCRIPT_CDN_PATH - = "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/static/js/middleware.js"; - public static final String CUSTOM_VERSION_FAVICON_CDN_PATH - = "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/favicon.png"; - public static final String CUSTOM_VERSION_LOGO_CDN_PATH - = "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/logo.png"; + private static void assertScript(final Document document, final String scriptUrl) { + assertThat(document.select(String.format("script[src=%s]", scriptUrl)).size()).isOne(); + } - public static final String CUSTOM_MAPPING = "/test-mapping"; - public static final String CUSTOM_TITLE = "My CustomTest Title"; - public static final String DEFAULT_PLAYGROUND_ENDPOINT = "/playground"; - public static final String CSS_URL_FIELD_NAME = "cssUrl"; - public static final String SCRIPT_URL_FIELD_NAME = "scriptUrl"; - public static final String FAVICON_URL_FIELD_NAME = "faviconUrl"; - public static final String LOGO_URL_FIELD_NAME = "logoUrl"; - public static final String PAGE_TITLE_FIELD_NAME = "pageTitle"; + private static void assertFavicon(final Document document, final String faviconUrl) { + assertThat( + document + .select(String.format("head link[rel=shortcut icon][href=%s]", faviconUrl)) + .size()) + .isOne(); + } - public static void assertTitle(final Document document, final String title) { - assertThat(document.select("head title")).extracting(Element::text).containsExactly(title); - } + private static void assertLoadingLogo(final Document document, final String logoUrl) { + assertThat(document.select(String.format("#root img[src=%s]", logoUrl)).size()).isOne(); + } - private static void assertStylesheet(final Document document, final String cssUrl) { - assertThat(document.select(String.format("head link[rel=stylesheet][href=%s]", cssUrl)).size()).isOne(); - } - private static void assertScript(final Document document, final String scriptUrl) { - assertThat(document.select(String.format("script[src=%s]", scriptUrl)).size()).isOne(); - } - private static void assertFavicon(final Document document, final String faviconUrl) { - assertThat(document.select(String.format("head link[rel=shortcut icon][href=%s]", faviconUrl)).size()).isOne(); - } - private static void assertLoadingLogo(final Document document, final String logoUrl) { - assertThat(document.select(String.format("#root img[src=%s]", logoUrl)).size()).isOne(); - } - public static void assertStaticResources(final Document document, final String cssUrl, final String scriptUrl, - final String faviconUrl, final String logoUrl) { - assertStylesheet(document, cssUrl); - assertScript(document, scriptUrl); - assertFavicon(document, faviconUrl); - assertLoadingLogo(document, logoUrl); - } + public static void assertStaticResources( + final Document document, + final String cssUrl, + final String scriptUrl, + final String faviconUrl, + final String logoUrl) { + assertStylesheet(document, cssUrl); + assertScript(document, scriptUrl); + assertFavicon(document, faviconUrl); + assertLoadingLogo(document, logoUrl); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCSRFTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCSRFTest.java index a99e121e..0576f866 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCSRFTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCSRFTest.java @@ -1,34 +1,38 @@ package graphql.kickstart.playground.boot.webflux; +import static org.assertj.core.api.Assertions.assertThat; + import graphql.kickstart.playground.boot.PlaygroundTestHelper; +import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.reactive.server.WebTestClient; -import java.nio.charset.StandardCharsets; - -import static org.assertj.core.api.Assertions.assertThat; - @SpringBootTest(classes = PlaygroundWebFluxTestConfig.class) @AutoConfigureWebTestClient public class PlaygroundWebFluxCSRFTest { - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; - @Test - void shouldLoadCSRFData() { - // WHEN - final byte[] actual = webTestClient.get().uri(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT) + @Test + void shouldLoadCSRFData() { + // WHEN + final byte[] actual = + webTestClient + .get() + .uri(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT) .exchange() - .expectStatus().isOk() - .expectBody().returnResult().getResponseBody(); - // THEN - assertThat(actual).isNotNull(); - assertThat(new String(actual, StandardCharsets.UTF_8)) - .contains("let csrf = {\"token\":") - .contains("\"parameterName\":\"_csrf\",\"headerName\":\"X-CSRF-TOKEN\"}"); - } + .expectStatus() + .isOk() + .expectBody() + .returnResult() + .getResponseBody(); + // THEN + assertThat(actual).isNotNull(); + assertThat(new String(actual, StandardCharsets.UTF_8)) + .contains("let csrf = {\"token\":") + .contains("\"parameterName\":\"_csrf\",\"headerName\":\"X-CSRF-TOKEN\"}"); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCdnTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCdnTest.java index d9412b62..cfbd229b 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCdnTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCdnTest.java @@ -11,13 +11,12 @@ @TestPropertySource("classpath:application-playground-cdn-test.properties") public class PlaygroundWebFluxCdnTest extends PlaygroundWebFluxResourcesTestBase { - @Test - public void shouldLoadLatestVersionFromCdn() { - testPlaygroundResources( - PlaygroundTestHelper.DEFAULT_CSS_CDN_PATH, - PlaygroundTestHelper.DEFAULT_SCRIPT_CDN_PATH, - PlaygroundTestHelper.DEFAULT_FAVICON_CDN_PATH, - PlaygroundTestHelper.DEFAULT_LOGO_CDN_PATH - ); - } + @Test + public void shouldLoadLatestVersionFromCdn() { + testPlaygroundResources( + PlaygroundTestHelper.DEFAULT_CSS_CDN_PATH, + PlaygroundTestHelper.DEFAULT_SCRIPT_CDN_PATH, + PlaygroundTestHelper.DEFAULT_FAVICON_CDN_PATH, + PlaygroundTestHelper.DEFAULT_LOGO_CDN_PATH); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomCdnVersionTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomCdnVersionTest.java index 0ed385ce..51cecc4b 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomCdnVersionTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomCdnVersionTest.java @@ -11,13 +11,12 @@ @TestPropertySource("classpath:application-playground-cdn-custom-version-test.properties") public class PlaygroundWebFluxCustomCdnVersionTest extends PlaygroundWebFluxResourcesTestBase { - @Test - public void shouldLoadSpecifiedVersionFromCdn() { - testPlaygroundResources( - PlaygroundTestHelper.CUSTOM_VERSION_CSS_CDN_PATH, - PlaygroundTestHelper.CUSTOM_VERSION_SCRIPT_CDN_PATH, - PlaygroundTestHelper.CUSTOM_VERSION_FAVICON_CDN_PATH, - PlaygroundTestHelper.CUSTOM_VERSION_LOGO_CDN_PATH - ); - } + @Test + public void shouldLoadSpecifiedVersionFromCdn() { + testPlaygroundResources( + PlaygroundTestHelper.CUSTOM_VERSION_CSS_CDN_PATH, + PlaygroundTestHelper.CUSTOM_VERSION_SCRIPT_CDN_PATH, + PlaygroundTestHelper.CUSTOM_VERSION_FAVICON_CDN_PATH, + PlaygroundTestHelper.CUSTOM_VERSION_LOGO_CDN_PATH); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomMappingTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomMappingTest.java index ad16bced..fc61e7c3 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomMappingTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomMappingTest.java @@ -14,14 +14,17 @@ @TestPropertySource("classpath:application-playground-mapping-test.properties") public class PlaygroundWebFluxCustomMappingTest { - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; - @Test - public void shouldUseTheConfiguredRequestMapping() { - webTestClient.get().uri(PlaygroundTestHelper.CUSTOM_MAPPING) - .exchange() - .expectStatus().isOk() - .expectHeader().contentTypeCompatibleWith(MediaType.TEXT_HTML); - } + @Test + public void shouldUseTheConfiguredRequestMapping() { + webTestClient + .get() + .uri(PlaygroundTestHelper.CUSTOM_MAPPING) + .exchange() + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_HTML); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomStaticPathTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomStaticPathTest.java index 048625b6..d90b9aa1 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomStaticPathTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomStaticPathTest.java @@ -11,13 +11,12 @@ @TestPropertySource("classpath:application-playground-custom-static-path.properties") public class PlaygroundWebFluxCustomStaticPathTest extends PlaygroundWebFluxResourcesTestBase { - @Test - public void shouldLoadStaticResourcesFromCustomPath() { - testPlaygroundResources( - PlaygroundTestHelper.CUSTOM_LOCAL_CSS_URL, - PlaygroundTestHelper.CUSTOM_LOCAL_SCRIPT_URL, - PlaygroundTestHelper.CUSTOM_LOCAL_FAVICON_URL, - PlaygroundTestHelper.CUSTOM_LOCAL_LOGO_URL - ); - } + @Test + public void shouldLoadStaticResourcesFromCustomPath() { + testPlaygroundResources( + PlaygroundTestHelper.CUSTOM_LOCAL_CSS_URL, + PlaygroundTestHelper.CUSTOM_LOCAL_SCRIPT_URL, + PlaygroundTestHelper.CUSTOM_LOCAL_FAVICON_URL, + PlaygroundTestHelper.CUSTOM_LOCAL_LOGO_URL); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomTitleTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomTitleTest.java index b02b37d5..a2afcfb1 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomTitleTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomTitleTest.java @@ -1,6 +1,10 @@ package graphql.kickstart.playground.boot.webflux; +import static graphql.kickstart.playground.boot.PlaygroundTestHelper.CUSTOM_TITLE; +import static org.assertj.core.api.Assertions.assertThat; + import graphql.kickstart.playground.boot.PlaygroundTestHelper; +import java.nio.charset.StandardCharsets; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.junit.jupiter.api.Test; @@ -8,33 +12,31 @@ import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.web.reactive.server.EntityExchangeResult; import org.springframework.test.web.reactive.server.WebTestClient; -import org.springframework.test.web.servlet.MvcResult; - -import java.nio.charset.StandardCharsets; - -import static graphql.kickstart.playground.boot.PlaygroundTestHelper.CUSTOM_TITLE; -import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = PlaygroundWebFluxTestConfig.class) @AutoConfigureWebTestClient @TestPropertySource("classpath:application-playground-custom-title.properties") public class PlaygroundWebFluxCustomTitleTest { - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; - @Test - public void shouldUseTheCustomPageTitle() { - // WHEN - final byte[] actual = webTestClient.get().uri(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT) + @Test + public void shouldUseTheCustomPageTitle() { + // WHEN + final byte[] actual = + webTestClient + .get() + .uri(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT) .exchange() - .expectStatus().isOk() - .expectBody().returnResult().getResponseBody(); - // THEN - assertThat(actual).isNotNull(); - final Document document = Jsoup.parse(new String(actual, StandardCharsets.UTF_8)); - PlaygroundTestHelper.assertTitle(document, CUSTOM_TITLE); - } + .expectStatus() + .isOk() + .expectBody() + .returnResult() + .getResponseBody(); + // THEN + assertThat(actual).isNotNull(); + final Document document = Jsoup.parse(new String(actual, StandardCharsets.UTF_8)); + PlaygroundTestHelper.assertTitle(document, CUSTOM_TITLE); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxDisabledTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxDisabledTest.java index 3bf12060..8b9754ad 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxDisabledTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxDisabledTest.java @@ -1,5 +1,7 @@ package graphql.kickstart.playground.boot.webflux; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; + import graphql.kickstart.playground.boot.PlaygroundController; import graphql.kickstart.playground.boot.PlaygroundTestHelper; import org.junit.jupiter.api.Test; @@ -10,28 +12,29 @@ import org.springframework.context.ApplicationContext; import org.springframework.test.web.reactive.server.WebTestClient; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; - -@SpringBootTest(classes = PlaygroundWebFluxTestConfig.class, properties = "graphql.playground.enabled=false") +@SpringBootTest( + classes = PlaygroundWebFluxTestConfig.class, + properties = "graphql.playground.enabled=false") @AutoConfigureWebTestClient public class PlaygroundWebFluxDisabledTest { - @Autowired - private ApplicationContext applicationContext; + @Autowired private ApplicationContext applicationContext; - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; - @Test - public void playgroundShouldNotLoadIfDisabled() { - assertThatExceptionOfType(NoSuchBeanDefinitionException.class) - .isThrownBy(() -> applicationContext.getBean(PlaygroundController.class)); - } + @Test + public void playgroundShouldNotLoadIfDisabled() { + assertThatExceptionOfType(NoSuchBeanDefinitionException.class) + .isThrownBy(() -> applicationContext.getBean(PlaygroundController.class)); + } - @Test - public void playgroundEndpointShouldNotExist() { - webTestClient.get().uri(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT) - .exchange() - .expectStatus().isNotFound(); - } + @Test + public void playgroundEndpointShouldNotExist() { + webTestClient + .get() + .uri(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT) + .exchange() + .expectStatus() + .isNotFound(); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxEnabledTest.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxEnabledTest.java index 5e9a682f..cac1eca9 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxEnabledTest.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxEnabledTest.java @@ -1,8 +1,12 @@ package graphql.kickstart.playground.boot.webflux; +import static org.assertj.core.api.Assertions.assertThat; + import com.fasterxml.jackson.databind.ObjectMapper; import graphql.kickstart.playground.boot.PlaygroundController; import graphql.kickstart.playground.boot.PlaygroundTestHelper; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.junit.jupiter.api.Test; @@ -16,102 +20,107 @@ import org.springframework.util.StreamUtils; import org.springframework.web.reactive.function.client.ExchangeStrategies; -import java.io.IOException; -import java.nio.charset.StandardCharsets; - -import static org.assertj.core.api.Assertions.assertThat; - @SpringBootTest(classes = PlaygroundWebFluxTestConfig.class) @AutoConfigureWebTestClient public class PlaygroundWebFluxEnabledTest { - private static final int MAX_IN_MEMORY_SIZE = 3 * 1024 * 1024; - private static final String DEFAULT_CSS_PATH = "/vendor/playground/static/css/index.css"; - private static final String DEFAULT_CSS_RESOURCE = "/static/vendor/playground/static/css/index.css"; - private static final String DEFAULT_SCRIPT_PATH = "/vendor/playground/static/js/middleware.js"; - private static final String DEFAULT_SCRIPT_RESOURCE = "/static/vendor/playground/static/js/middleware.js"; - private static final String DEFAULT_FAVICON_PATH = "/vendor/playground/favicon.png"; - private static final String DEFAULT_FAVICON_RESOURCE = "/static/vendor/playground/favicon.png"; - private static final String DEFAULT_LOGO_PATH = "/vendor/playground/logo.png"; - private static final String DEFAULT_LOGO_RESOURCE = "/static/vendor/playground/logo.png"; - private static final String DEFAULT_TITLE = "Playground"; + private static final int MAX_IN_MEMORY_SIZE = 3 * 1024 * 1024; + private static final String DEFAULT_CSS_PATH = "/vendor/playground/static/css/index.css"; + private static final String DEFAULT_CSS_RESOURCE = + "/static/vendor/playground/static/css/index.css"; + private static final String DEFAULT_SCRIPT_PATH = "/vendor/playground/static/js/middleware.js"; + private static final String DEFAULT_SCRIPT_RESOURCE = + "/static/vendor/playground/static/js/middleware.js"; + private static final String DEFAULT_FAVICON_PATH = "/vendor/playground/favicon.png"; + private static final String DEFAULT_FAVICON_RESOURCE = "/static/vendor/playground/favicon.png"; + private static final String DEFAULT_LOGO_PATH = "/vendor/playground/logo.png"; + private static final String DEFAULT_LOGO_RESOURCE = "/static/vendor/playground/logo.png"; + private static final String DEFAULT_TITLE = "Playground"; - @Autowired - private ApplicationContext applicationContext; + @Autowired private ApplicationContext applicationContext; - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; - @Autowired - private ObjectMapper objectMapper; + @Autowired private ObjectMapper objectMapper; - @Test - public void playgroundLoads() { - assertThat(applicationContext.getBean(PlaygroundController.class)).isNotNull(); - } + @Test + public void playgroundLoads() { + assertThat(applicationContext.getBean(PlaygroundController.class)).isNotNull(); + } - @Test - public void playgroundShouldBeAvailableAtDefaultEndpoint() { - // WHEN - final byte[] content = webTestClient.get().uri(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT) + @Test + public void playgroundShouldBeAvailableAtDefaultEndpoint() { + // WHEN + final byte[] content = + webTestClient + .get() + .uri(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT) .accept(MediaType.TEXT_HTML) .acceptCharset(StandardCharsets.UTF_8) .exchange() - .expectStatus().isOk() - .expectHeader().contentTypeCompatibleWith(MediaType.TEXT_HTML) + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(MediaType.TEXT_HTML) .expectBody() .returnResult() .getResponseBodyContent(); - // THEN - assertThat(content).isNotNull(); - final Document document = Jsoup.parse(new String(content, StandardCharsets.UTF_8)); - PlaygroundTestHelper.assertTitle(document, DEFAULT_TITLE); - PlaygroundTestHelper.assertStaticResources(document, DEFAULT_CSS_PATH, DEFAULT_SCRIPT_PATH, DEFAULT_FAVICON_PATH, DEFAULT_LOGO_PATH); - } + // THEN + assertThat(content).isNotNull(); + final Document document = Jsoup.parse(new String(content, StandardCharsets.UTF_8)); + PlaygroundTestHelper.assertTitle(document, DEFAULT_TITLE); + PlaygroundTestHelper.assertStaticResources( + document, DEFAULT_CSS_PATH, DEFAULT_SCRIPT_PATH, DEFAULT_FAVICON_PATH, DEFAULT_LOGO_PATH); + } - @Test - public void defaultCssShouldBeAvailable() throws IOException { - testStaticResource(DEFAULT_CSS_RESOURCE, DEFAULT_CSS_PATH, "text/css"); - } + @Test + public void defaultCssShouldBeAvailable() throws IOException { + testStaticResource(DEFAULT_CSS_RESOURCE, DEFAULT_CSS_PATH, "text/css"); + } - @Test - public void defaultScriptShouldBeAvailable() throws Exception { - testStaticResource(DEFAULT_SCRIPT_RESOURCE, DEFAULT_SCRIPT_PATH, "application/javascript"); - } + @Test + public void defaultScriptShouldBeAvailable() throws Exception { + testStaticResource(DEFAULT_SCRIPT_RESOURCE, DEFAULT_SCRIPT_PATH, "application/javascript"); + } - @Test - public void defaultFaviconShouldBeAvailable() throws Exception { - testStaticResource(DEFAULT_FAVICON_RESOURCE, DEFAULT_FAVICON_PATH, "image/png"); - } + @Test + public void defaultFaviconShouldBeAvailable() throws Exception { + testStaticResource(DEFAULT_FAVICON_RESOURCE, DEFAULT_FAVICON_PATH, "image/png"); + } - @Test - public void defaultLogoShouldBeAvailable() throws Exception { - testStaticResource(DEFAULT_LOGO_RESOURCE, DEFAULT_LOGO_PATH, "image/png"); - } + @Test + public void defaultLogoShouldBeAvailable() throws Exception { + testStaticResource(DEFAULT_LOGO_RESOURCE, DEFAULT_LOGO_PATH, "image/png"); + } - private void testStaticResource( - final String resourcePath, - final String urlPath, - final String contentType - ) throws IOException { - // GIVEN - final byte[] expected = StreamUtils.copyToByteArray(new ClassPathResource(resourcePath).getInputStream()); - // WHEN - final byte[] actual = webTestClient - .mutateWith((builder, httpHandlerBuilder, connector) - -> builder.exchangeStrategies(ExchangeStrategies.builder().codecs(configurer - -> configurer - .defaultCodecs() - .maxInMemorySize(MAX_IN_MEMORY_SIZE)) - .build() - ) - ) - .get().uri(urlPath) + private void testStaticResource( + final String resourcePath, final String urlPath, final String contentType) + throws IOException { + // GIVEN + final byte[] expected = + StreamUtils.copyToByteArray(new ClassPathResource(resourcePath).getInputStream()); + // WHEN + final byte[] actual = + webTestClient + .mutateWith( + (builder, httpHandlerBuilder, connector) -> + builder.exchangeStrategies( + ExchangeStrategies.builder() + .codecs( + configurer -> + configurer.defaultCodecs().maxInMemorySize(MAX_IN_MEMORY_SIZE)) + .build())) + .get() + .uri(urlPath) .exchange() - .expectStatus().isOk() - .expectHeader().contentTypeCompatibleWith(contentType) - .expectBody().returnResult().getResponseBody(); - // THEN - assertThat(actual).isEqualTo(expected); - } + .expectStatus() + .isOk() + .expectHeader() + .contentTypeCompatibleWith(contentType) + .expectBody() + .returnResult() + .getResponseBody(); + // THEN + assertThat(actual).isEqualTo(expected); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxResourcesTestBase.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxResourcesTestBase.java index 28f213d1..2fba7a46 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxResourcesTestBase.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxResourcesTestBase.java @@ -1,35 +1,35 @@ package graphql.kickstart.playground.boot.webflux; +import static org.assertj.core.api.Assertions.assertThat; + import graphql.kickstart.playground.boot.PlaygroundTestHelper; +import java.nio.charset.StandardCharsets; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.web.reactive.server.WebTestClient; -import java.nio.charset.StandardCharsets; - -import static org.assertj.core.api.Assertions.assertThat; - public class PlaygroundWebFluxResourcesTestBase { - @Autowired - private WebTestClient webTestClient; + @Autowired private WebTestClient webTestClient; - void testPlaygroundResources( - final String cssUrl, - final String scriptUrl, - final String faviconUrl, - final String logoUrl - ) { - // WHEN - final byte[] actual = webTestClient.get().uri(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT) + void testPlaygroundResources( + final String cssUrl, final String scriptUrl, final String faviconUrl, final String logoUrl) { + // WHEN + final byte[] actual = + webTestClient + .get() + .uri(PlaygroundTestHelper.DEFAULT_PLAYGROUND_ENDPOINT) .exchange() - .expectStatus().isOk() - .expectBody().returnResult().getResponseBody(); + .expectStatus() + .isOk() + .expectBody() + .returnResult() + .getResponseBody(); - // THEN - assertThat(actual).isNotNull(); - final Document document = Jsoup.parse(new String(actual, StandardCharsets.UTF_8)); - PlaygroundTestHelper.assertStaticResources(document, cssUrl, scriptUrl, faviconUrl, logoUrl); - } + // THEN + assertThat(actual).isNotNull(); + final Document document = Jsoup.parse(new String(actual, StandardCharsets.UTF_8)); + PlaygroundTestHelper.assertStaticResources(document, cssUrl, scriptUrl, faviconUrl, logoUrl); + } } diff --git a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxTestConfig.java b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxTestConfig.java index 16017b71..6f695543 100644 --- a/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxTestConfig.java +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxTestConfig.java @@ -13,11 +13,11 @@ @EnableWebFlux @EnableWebFluxSecurity @SpringBootApplication -@EnableAutoConfiguration(exclude = { WebMvcAutoConfiguration.class, SecurityAutoConfiguration.class } ) +@EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class, SecurityAutoConfiguration.class}) class PlaygroundWebFluxTestConfig { - @Bean - public SecurityWebFilterChain securityWebFilterChain(final ServerHttpSecurity http) { - return http.authorizeExchange().anyExchange().permitAll().and().build(); - } + @Bean + public SecurityWebFilterChain securityWebFilterChain(final ServerHttpSecurity http) { + return http.authorizeExchange().anyExchange().permitAll().and().build(); + } } diff --git a/screenshot-reformat-code-before-commit.png b/screenshot-reformat-code-before-commit.png new file mode 100644 index 00000000..89ed1ff1 Binary files /dev/null and b/screenshot-reformat-code-before-commit.png differ diff --git a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/ReactiveVoyagerAutoConfiguration.java b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/ReactiveVoyagerAutoConfiguration.java index d93c1d43..0a80170f 100644 --- a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/ReactiveVoyagerAutoConfiguration.java +++ b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/ReactiveVoyagerAutoConfiguration.java @@ -1,8 +1,8 @@ package graphql.kickstart.voyager.boot; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; @@ -10,17 +10,13 @@ import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; -/** - * @author Max David Günther - */ +/** @author Max David Günther */ @Configuration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE) @ConditionalOnProperty(value = "voyager.enabled", havingValue = "true", matchIfMissing = true) +@EnableConfigurationProperties(VoyagerPropertiesConfiguration.class) public class ReactiveVoyagerAutoConfiguration { - @Value("${voyager.mapping:/voyager}") - private String voyagerPath; - @Bean ReactiveVoyagerController voyagerController() { return new ReactiveVoyagerController(); @@ -29,13 +25,12 @@ ReactiveVoyagerController voyagerController() { @Bean public RouterFunction voyagerStaticFilesRouter() { return RouterFunctions.resources( - "/vendor/voyager/**", - new ClassPathResource("static/vendor/voyager/") - ); + "/vendor/voyager/**", new ClassPathResource("static/vendor/voyager/")); } @Bean - VoyagerIndexHtmlTemplate voyagerIndexHtmlTemplate() { - return new VoyagerIndexHtmlTemplate(); + VoyagerIndexHtmlTemplate voyagerIndexHtmlTemplate( + final VoyagerPropertiesConfiguration voyagerPropertiesConfiguration) { + return new VoyagerIndexHtmlTemplate(voyagerPropertiesConfiguration); } } diff --git a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/ReactiveVoyagerController.java b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/ReactiveVoyagerController.java index c0fdc820..6766da32 100644 --- a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/ReactiveVoyagerController.java +++ b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/ReactiveVoyagerController.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.util.Map; +import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -9,14 +10,12 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -/** - * @author Max David Günther - */ +/** @author Max David Günther */ @Controller +@RequiredArgsConstructor public class ReactiveVoyagerController { - @Autowired - private VoyagerIndexHtmlTemplate indexTemplate; + @Autowired private VoyagerIndexHtmlTemplate indexTemplate; @GetMapping(path = "${voyager.mapping:/voyager}") public ResponseEntity voyager(@PathVariable Map params) diff --git a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerAutoConfiguration.java b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerAutoConfiguration.java index d0762a96..293c37be 100644 --- a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerAutoConfiguration.java +++ b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerAutoConfiguration.java @@ -2,15 +2,15 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -/** - * @author Guilherme Blanco - */ +/** @author Guilherme Blanco */ @Configuration @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnProperty(value = "voyager.enabled", havingValue = "true", matchIfMissing = true) +@EnableConfigurationProperties(VoyagerPropertiesConfiguration.class) public class VoyagerAutoConfiguration { @Bean @@ -19,7 +19,8 @@ VoyagerController voyagerController() { } @Bean - VoyagerIndexHtmlTemplate voyagerIndexHtmlTemplate() { - return new VoyagerIndexHtmlTemplate(); + VoyagerIndexHtmlTemplate voyagerIndexHtmlTemplate( + final VoyagerPropertiesConfiguration voyagerPropertiesConfiguration) { + return new VoyagerIndexHtmlTemplate(voyagerPropertiesConfiguration); } } diff --git a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerController.java b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerController.java index 5589f92d..9ad0a4a0 100644 --- a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerController.java +++ b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerController.java @@ -10,18 +10,15 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -/** - * @author Max David Günther - */ +/** @author Max David Günther */ @Controller public class VoyagerController { - @Autowired - private VoyagerIndexHtmlTemplate indexTemplate; + @Autowired private VoyagerIndexHtmlTemplate indexTemplate; @GetMapping(value = "${voyager.mapping:/voyager}") - public ResponseEntity voyager(HttpServletRequest request, - @PathVariable Map params) throws IOException { + public ResponseEntity voyager( + HttpServletRequest request, @PathVariable Map params) throws IOException { String contextPath = request.getContextPath(); String indexHtmlContent = indexTemplate.fillIndexTemplate(contextPath, params); return ResponseEntity.ok() diff --git a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerIndexHtmlTemplate.java b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerIndexHtmlTemplate.java index ead7ef71..e76e5d3d 100644 --- a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerIndexHtmlTemplate.java +++ b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerIndexHtmlTemplate.java @@ -4,70 +4,103 @@ import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringSubstitutor; -import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.RequestParam; -/** - * @author Guilherme Blanco - */ +/** @author Guilherme Blanco */ +@RequiredArgsConstructor public class VoyagerIndexHtmlTemplate { private static final String CDNJS_CLOUDFLARE_COM_AJAX_LIBS = "//cdnjs.cloudflare.com/ajax/libs/"; private static final String CDN_JSDELIVR_NET_NPM = "//cdn.jsdelivr.net/npm/"; private static final String VOYAGER = "graphql-voyager"; - private static final String FAVICON_APIS_GURU = "//apis.guru/graphql-voyager/icons/favicon-16x16.png"; + private static final String FAVICON_APIS_GURU = + "//apis.guru/graphql-voyager/icons/favicon-16x16.png"; - @Value("${voyager.endpoint:/graphql}") - private String graphqlEndpoint; - - @Value("${voyager.pageTitle:Voyager}") - private String pageTitle; - - @Value("${voyager.static.basePath:/}") - private String staticBasePath; - - @Value("${voyager.cdn.enabled:false}") - private boolean voyagerCdnEnabled; - - @Value("${voyager.cdn.version:1.0.0-rc.31}") - private String voyagerCdnVersion; + private final VoyagerPropertiesConfiguration voyagerConfiguration; public String fillIndexTemplate(String contextPath, Map params) throws IOException { - String template = StreamUtils - .copyToString(new ClassPathResource("voyager.html").getInputStream(), - Charset.defaultCharset()); + String template = + StreamUtils.copyToString( + new ClassPathResource("voyager.html").getInputStream(), Charset.defaultCharset()); + + String basePath = voyagerConfiguration.getBasePath(); + String voyagerCdnVersion = voyagerConfiguration.getCdn().getVersion(); + Map replacements = new HashMap<>(); replacements.put("graphqlEndpoint", constructGraphQlEndpoint(contextPath, params)); - replacements.put("pageTitle", pageTitle); - replacements - .put("pageFavicon", getResourceUrl(staticBasePath, "favicon.ico", FAVICON_APIS_GURU)); - replacements.put("es6PromiseJsUrl", getResourceUrl(staticBasePath, "es6-promise.auto.min.js", - joinCdnjsPath("es6-promise", "4.1.1", "es6-promise.auto.min.js"))); - replacements.put("fetchJsUrl", getResourceUrl(staticBasePath, "fetch.min.js", - joinCdnjsPath("fetch", "2.0.4", "fetch.min.js"))); - replacements.put("reactJsUrl", getResourceUrl(staticBasePath, "react.min.js", - joinCdnjsPath("react", "16.8.3", "umd/react.production.min.js"))); - replacements.put("reactDomJsUrl", getResourceUrl(staticBasePath, "react-dom.min.js", - joinCdnjsPath("react-dom", "16.8.3", "umd/react-dom.production.min.js"))); - replacements.put("voyagerCssUrl", getResourceUrl(staticBasePath, "voyager.css", - joinJsDelivrPath(voyagerCdnVersion, "dist/voyager.css"))); - replacements.put("voyagerJsUrl", getResourceUrl(staticBasePath, "voyager.min.js", - joinJsDelivrPath(voyagerCdnVersion, "dist/voyager.min.js"))); - replacements.put("voyagerWorkerJsUrl", getResourceUrl(staticBasePath, "voyager.worker.js", - joinJsDelivrPath(voyagerCdnVersion, "dist/voyager.worker.min.js"))); + replacements.put("pageTitle", voyagerConfiguration.getPageTitle()); + replacements.put("pageFavicon", getResourceUrl(basePath, "favicon.ico", FAVICON_APIS_GURU)); + replacements.put( + "es6PromiseJsUrl", + getResourceUrl( + basePath, + "es6-promise.auto.min.js", + joinCdnjsPath("es6-promise", "4.1.1", "es6-promise.auto.min.js"))); + replacements.put( + "fetchJsUrl", + getResourceUrl(basePath, "fetch.min.js", joinCdnjsPath("fetch", "2.0.4", "fetch.min.js"))); + replacements.put( + "reactJsUrl", + getResourceUrl( + basePath, + "react.min.js", + joinCdnjsPath("react", "16.8.3", "umd/react.production.min.js"))); + replacements.put( + "reactDomJsUrl", + getResourceUrl( + basePath, + "react-dom.min.js", + joinCdnjsPath("react-dom", "16.8.3", "umd/react-dom.production.min.js"))); + replacements.put( + "voyagerCssUrl", + getResourceUrl( + basePath, "voyager.css", joinJsDelivrPath(voyagerCdnVersion, "dist/voyager.css"))); + replacements.put( + "voyagerJsUrl", + getResourceUrl( + basePath, + "voyager.min.js", + joinJsDelivrPath(voyagerCdnVersion, "dist/voyager.min.js"))); + replacements.put( + "voyagerWorkerJsUrl", + getResourceUrl( + basePath, + "voyager.worker.js", + joinJsDelivrPath(voyagerCdnVersion, "dist/voyager.worker.min.js"))); replacements.put("contextPath", contextPath); + replacements.put( + "voyagerDisplayOptionsSkipRelay", + Boolean.toString(voyagerConfiguration.getDisplayOptions().isSkipRelay())); + replacements.put( + "voyagerDisplayOptionsSkipDeprecated", + Boolean.toString(voyagerConfiguration.getDisplayOptions().isSkipDeprecated())); + replacements.put( + "voyagerDisplayOptionsRootType", voyagerConfiguration.getDisplayOptions().getRootType()); + replacements.put( + "voyagerDisplayOptionsSortByAlphabet", + Boolean.toString(voyagerConfiguration.getDisplayOptions().isSortByAlphabet())); + replacements.put( + "voyagerDisplayOptionsShowLeafFields", + Boolean.toString(voyagerConfiguration.getDisplayOptions().isShowLeafFields())); + replacements.put( + "voyagerDisplayOptionsHideRoot", + Boolean.toString(voyagerConfiguration.getDisplayOptions().isHideRoot())); + replacements.put("voyagerHideDocs", Boolean.toString(voyagerConfiguration.isHideDocs())); + replacements.put( + "voyagerHideSettings", Boolean.toString(voyagerConfiguration.isHideSettings())); return StringSubstitutor.replace(template, replacements); } - private String constructGraphQlEndpoint(String contextPath, - @RequestParam Map params) { - String endpoint = graphqlEndpoint; + private String constructGraphQlEndpoint( + String contextPath, @RequestParam Map params) { + String endpoint = voyagerConfiguration.getEndpoint(); for (Map.Entry param : params.entrySet()) { endpoint = endpoint.replaceAll("\\{" + param.getKey() + "}", param.getValue()); } @@ -78,7 +111,7 @@ private String constructGraphQlEndpoint(String contextPath, } private String getResourceUrl(String staticBasePath, String staticFileName, String cdnUrl) { - if (voyagerCdnEnabled && StringUtils.isNotBlank(cdnUrl)) { + if (voyagerConfiguration.getCdn().isEnabled() && StringUtils.isNotBlank(cdnUrl)) { return cdnUrl; } return joinStaticPath(staticBasePath, staticFileName); @@ -93,6 +126,11 @@ private String joinCdnjsPath(String library, String cdnVersion, String cdnFileNa } private String joinJsDelivrPath(String cdnVersion, String cdnFileName) { - return CDN_JSDELIVR_NET_NPM + VoyagerIndexHtmlTemplate.VOYAGER + "@" + cdnVersion + "/" + cdnFileName; + return CDN_JSDELIVR_NET_NPM + + VoyagerIndexHtmlTemplate.VOYAGER + + "@" + + cdnVersion + + "/" + + cdnFileName; } } diff --git a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerPropertiesConfiguration.java b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerPropertiesConfiguration.java new file mode 100644 index 00000000..0ce00eaa --- /dev/null +++ b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/VoyagerPropertiesConfiguration.java @@ -0,0 +1,30 @@ +package graphql.kickstart.voyager.boot; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import graphql.kickstart.voyager.boot.properties.VoyagerCdn; +import graphql.kickstart.voyager.boot.properties.VoyagerDisplayOptions; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; +import org.springframework.validation.annotation.Validated; + +@Data +@ConfigurationProperties(prefix = "voyager") +@Validated +public class VoyagerPropertiesConfiguration { + + private String endpoint = "/graphql"; + + private String pageTitle = "Voyager"; + + private String basePath = "/"; + + @NestedConfigurationProperty @JsonIgnore private VoyagerCdn cdn = new VoyagerCdn(); + + @NestedConfigurationProperty @JsonIgnore + private VoyagerDisplayOptions displayOptions = new VoyagerDisplayOptions(); + + @JsonIgnore private boolean hideDocs; + + @JsonIgnore private boolean hideSettings; +} diff --git a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/properties/VoyagerCdn.java b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/properties/VoyagerCdn.java new file mode 100644 index 00000000..150b35b9 --- /dev/null +++ b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/properties/VoyagerCdn.java @@ -0,0 +1,10 @@ +package graphql.kickstart.voyager.boot.properties; + +import lombok.Data; + +@Data +public class VoyagerCdn { + + private boolean enabled; + private String version = "latest"; +} diff --git a/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/properties/VoyagerDisplayOptions.java b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/properties/VoyagerDisplayOptions.java new file mode 100644 index 00000000..6b9986a4 --- /dev/null +++ b/voyager-spring-boot-autoconfigure/src/main/java/graphql/kickstart/voyager/boot/properties/VoyagerDisplayOptions.java @@ -0,0 +1,16 @@ +package graphql.kickstart.voyager.boot.properties; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Data; + +@Data +@JsonInclude(JsonInclude.Include.NON_NULL) +public class VoyagerDisplayOptions { + + private boolean skipRelay = true; + private boolean skipDeprecated = true; + private String rootType = "Query"; + private boolean sortByAlphabet = false; + private boolean showLeafFields = true; + private boolean hideRoot = false; +} diff --git a/voyager-spring-boot-autoconfigure/src/main/resources/voyager.html b/voyager-spring-boot-autoconfigure/src/main/resources/voyager.html index 9bdc54dd..bfbb57ae 100644 --- a/voyager-spring-boot-autoconfigure/src/main/resources/voyager.html +++ b/voyager-spring-boot-autoconfigure/src/main/resources/voyager.html @@ -73,8 +73,15 @@

Transmitting...

GraphQLVoyager.init(document.getElementById('voyager'), { introspection: introspectionProvider, displayOptions: { - sortByAlphabet: true, - } + skipRelay: ${voyagerDisplayOptionsSkipRelay}, + skipDeprecated: ${voyagerDisplayOptionsSkipDeprecated}, + rootType: '${voyagerDisplayOptionsRootType}', + sortByAlphabet: ${voyagerDisplayOptionsSortByAlphabet}, + showLeafFields: ${voyagerDisplayOptionsShowLeafFields}, + hideRoot: ${voyagerDisplayOptionsHideRoot}, + }, + hideDocs: ${voyagerHideDocs}, + hideSettings: ${voyagerHideSettings}, }) diff --git a/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/AbstractAutoConfigurationTest.java b/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/AbstractAutoConfigurationTest.java index 97806d88..4c9a84f0 100644 --- a/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/AbstractAutoConfigurationTest.java +++ b/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/AbstractAutoConfigurationTest.java @@ -5,9 +5,7 @@ import org.springframework.context.annotation.AnnotationConfigRegistry; import org.springframework.context.support.AbstractApplicationContext; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ public abstract class AbstractAutoConfigurationTest { private final Class contextClass; @@ -19,8 +17,8 @@ protected AbstractAutoConfigurationTest(Class autoConfiguration) { this(AnnotationConfigApplicationContext.class, autoConfiguration); } - protected AbstractAutoConfigurationTest(Class contextClass, - Class autoConfiguration) { + protected AbstractAutoConfigurationTest( + Class contextClass, Class autoConfiguration) { assert AnnotationConfigRegistry.class.isAssignableFrom(contextClass); this.contextClass = contextClass; this.autoConfiguration = autoConfiguration; @@ -41,9 +39,9 @@ protected void load(Class config, String... environment) { throw new RuntimeException(e); } -// if (environment != null && environment.length > 0) { -// EnvironmentTestUtils.addEnvironment(getContext(), environment); -// } + // if (environment != null && environment.length > 0) { + // EnvironmentTestUtils.addEnvironment(getContext(), environment); + // } getRegistry().register(config); getRegistry().register(autoConfiguration); diff --git a/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/ReactiveVoyagerControllerTest.java b/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/ReactiveVoyagerControllerTest.java index 6618c925..af9a0867 100644 --- a/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/ReactiveVoyagerControllerTest.java +++ b/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/ReactiveVoyagerControllerTest.java @@ -14,13 +14,12 @@ import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -/** - * @author Max Günther - */ +/** @author Max Günther */ class ReactiveVoyagerControllerTest extends AbstractAutoConfigurationTest { public ReactiveVoyagerControllerTest() { - super(AnnotationConfigReactiveWebApplicationContext.class, + super( + AnnotationConfigReactiveWebApplicationContext.class, ReactiveVoyagerAutoConfiguration.class); } diff --git a/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/VoyagerControllerTest.java b/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/VoyagerControllerTest.java index 6fc5e23b..45546ceb 100644 --- a/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/VoyagerControllerTest.java +++ b/voyager-spring-boot-autoconfigure/src/test/java/graphql/kickstart/voyager/boot/test/VoyagerControllerTest.java @@ -14,9 +14,7 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -/** - * @author Andrew Potter - */ +/** @author Andrew Potter */ class VoyagerControllerTest extends AbstractAutoConfigurationTest { public VoyagerControllerTest() {