diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index faba2300..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 @@ -20,8 +48,9 @@ jobs: - name: Checkout uses: actions/checkout@v2 - name: Setup Java - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'zulu' java-version: 8 - name: Cache Gradle uses: actions/cache@v2 @@ -37,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 @@ -46,8 +76,9 @@ jobs: - name: Checkout uses: actions/checkout@v2 - name: Setup Java - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'zulu' java-version: 8 - name: Cache Gradle uses: actions/cache@v2 @@ -63,11 +94,12 @@ jobs: - name: Make gradlew executable run: chmod +x ./gradlew - name: Gradle Publish Snapshot - if: env.BINTRAY_USER != 'SKIP_BINTRAY_PUBLISH' + if: env.OSS_USER_TOKEN_KEY != null env: - BINTRAY_USER: ${{ secrets.BINTRAY_USER }} - BINTRAY_PASS: ${{ secrets.BINTRAY_PASSWORD }} - run: ./gradlew artifactoryPublish -Dsnapshot=true -Dbuild.number=${{ env.GITHUB_RUN_NUMBER }} + 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 -x verifyGoogleJavaFormat + sonar: name: Sonar analysis needs: validation @@ -77,17 +109,18 @@ jobs: with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - name: Set up JDK 11 - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'zulu' java-version: 11 - name: Cache SonarCloud packages - uses: actions/cache@v1 + uses: actions/cache@v2 with: path: ~/.sonar/cache key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar - name: Cache Gradle packages - uses: actions/cache@v1 + uses: actions/cache@v2 with: path: ~/.gradle/caches key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} @@ -96,4 +129,5 @@ 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 + if: env.SONAR_TOKEN != null + run: ./gradlew build jacocoTestReport sonarqube --info -x verifyGoogleJavaFormat diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 7cba5d2e..4f01d778 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -10,21 +10,50 @@ 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: fail-fast: false matrix: os: [ ubuntu-latest, macos-latest, windows-latest ] - java: [ 8, 11, 15 ] + java: [ 8, 11, 16 ] needs: validation runs-on: ${{ matrix.os }} steps: - name: Checkout uses: actions/checkout@v2 - name: Setup Java - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'zulu' java-version: ${{ matrix.java }} - name: Cache Gradle uses: actions/cache@v2 @@ -35,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 @@ -60,19 +89,20 @@ jobs: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - name: Set up JDK 11 if: env.SONAR_TOKEN != null - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'zulu' java-version: 11 - name: Cache SonarCloud packages if: env.SONAR_TOKEN != null - uses: actions/cache@v1 + uses: actions/cache@v2 with: path: ~/.sonar/cache key: ${{ runner.os }}-sonar restore-keys: ${{ runner.os }}-sonar - name: Cache Gradle packages if: env.SONAR_TOKEN != null - uses: actions/cache@v1 + uses: actions/cache@v2 with: path: ~/.gradle/caches key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle') }} @@ -82,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 b6901775..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 @@ -16,8 +17,9 @@ jobs: - name: Checkout uses: actions/checkout@v2 - name: Setup Java - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'zulu' java-version: 8 - name: Cache Gradle uses: actions/cache@v2 @@ -33,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 @@ -42,8 +45,9 @@ jobs: - name: Checkout uses: actions/checkout@v2 - name: Setup Java - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: + distribution: 'zulu' java-version: 8 - name: Cache Gradle uses: actions/cache@v2 @@ -58,10 +62,16 @@ jobs: ${{ runner.os }}-${{ env.java-version }}-gradle- - name: Make gradlew executable run: chmod +x ./gradlew + - name: Prepare environment + env: + GPG_KEY_CONTENTS: ${{ secrets.GPG_KEY_CONTENTS }} + SIGNING_SECRET_KEY_RING_FILE: ${{ secrets.GPG_SIGNING_SECRET_KEY_RING_FILE }} + run: sudo bash -c "echo '$GPG_KEY_CONTENTS' | base64 -d > '$SIGNING_SECRET_KEY_RING_FILE'" - name: Publish release env: - BINTRAY_USER: ${{ secrets.BINTRAY_USER }} - BINTRAY_PASS: ${{ secrets.BINTRAY_PASSWORD }} + SIGNING_KEY_ID: ${{ secrets.GPG_SIGNING_KEY_ID }} + SIGNING_PASSWORD: ${{ secrets.GPG_SIGNING_PASSWORD }} + SIGNING_SECRET_KEY_RING_FILE: ${{ secrets.GPG_SIGNING_SECRET_KEY_RING_FILE }} OSS_USER_TOKEN_KEY: ${{ secrets.OSS_USER_TOKEN_KEY }} OSS_USER_TOKEN_PASS: ${{ secrets.OSS_USER_TOKEN_PASS }} run: bash github-build.sh 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 1f78f2ed..8d115862 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,11 @@ # GraphQL and Graph*i*QL Spring Framework Boot Starters [![Maven Central](https://img.shields.io/maven-central/v/com.graphql-java-kickstart/graphql-spring-boot-starter.svg)](https://maven-badges.herokuapp.com/maven-central/com.graphql-java-kickstart/graphql-spring-boot-starter) -[![GitHub CI Workflow](https://github.com/graphql-java-kickstart/graphql-spring-boot/workflows/ci/badge.svg)](https://github.com/graphql-java-kickstart/graphql-spring-boot/actions?query=workflow%3ACI+branch%3Amaster) +[![GitHub CI Workflow](https://github.com/graphql-java-kickstart/graphql-spring-boot/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/graphql-java-kickstart/graphql-spring-boot/actions/workflows/ci.yml?query=workflow%3ACI+branch%3Amaster) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=graphql-java-kickstart_graphql-spring-boot&metric=alert_status)](https://sonarcloud.io/dashboard?id=graphql-java-kickstart_graphql-spring-boot) +[![GitHub contributors](https://img.shields.io/github/contributors/graphql-java-kickstart/graphql-spring-boot)](https://github.com/graphql-java-kickstart/graphql-spring-boot/graphs/contributors) +[![Discuss on GitHub](https://img.shields.io/badge/GitHub-discuss-orange)](https://github.com/graphql-java-kickstart/graphql-spring-boot/discussions) + #### We are looking for contributors! @@ -16,7 +19,7 @@ and join the team! **Table of Contents** - - [WARNING: NoClassDefFoundError when using GraphQL Java Tools > 5.4.x](#warning-noclassdeffounderror-when-using-graphql-java-tools--54x) + - [Quick start](#quick-start) - [Using Gradle](#using-gradle) - [Using Maven](#using-maven) - [Documentation](#documentation) @@ -25,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) @@ -42,21 +49,15 @@ and join the team! - [Extended scalars](#extended-scalars) - [Tracing and Metrics](#tracing-and-metrics) - [Usage](#usage) +- [FAQs](#faqs) + - [WARNING: NoClassDefFoundError when using GraphQL Java Tools > 5.4.x](#warning-noclassdeffounderror-when-using-graphql-java-tools--54x) + - [Contributions](#contributions) - [Licenses](#licenses) -## WARNING: NoClassDefFoundError when using GraphQL Java Tools > 5.4.x - -If you're using `graphql-java-tools` in combination with Spring Boot 2.1.x or below then you need to -set the -`kotlin.version` in your Spring Boot project explicitly to version >= 1.3.70, because Spring Boot -Starter parent of that Spring Boot version overrides it with a 1.2.* version of Kotlin. -`graphql-java-tools` requires 1.3.* however because of its coroutine support. If you don't override -this version you will run into a `NoClassDefFoundError`. - -Spring Boot team has indicated the Kotlin version will be upgraded to 1.3 in Spring Boot 2.2. +## Quick start ### Using Gradle @@ -76,7 +77,7 @@ Set the Kotlin version in your `` section ``` -# Documentation +## Documentation See our new [Documentation](https://www.graphql-java-kickstart.com/spring-boot/). @@ -84,16 +85,16 @@ Repository contains: * `graphql-spring-boot-starter` to turn your boot application into GraphQL server ( see [graphql-java-servlet](https://github.com/graphql-java-kickstart/graphql-java-servlet)) -* `altair-spring-boot-starter`to embed `Altair` tool for schema introspection and query debugging ( +* `altair-spring-boot-starter` to embed `Altair` tool for schema introspection and query debugging ( see [altair](https://github.com/imolorhe/altair)) -* `graphiql-spring-boot-starter`to embed `GraphiQL` tool for schema introspection and query +* `graphiql-spring-boot-starter` to embed `GraphiQL` tool for schema introspection and query debugging (see [graphiql](https://github.com/graphql/graphiql)) -* `playground-spring-boot-starter`to embed `GraphQL Playground` tool for schema introspection and +* `playground-spring-boot-starter` to embed `GraphQL Playground` tool for schema introspection and query debugging (see [GraphQL Playground](https://github.com/prisma/graphql-playground)) -* `voyager-spring-boot-starter`to embed `Voyager` tool for visually explore GraphQL APIs as an +* `voyager-spring-boot-starter` to embed `Voyager` tool for visually explore GraphQL APIs as an interactive graph (see [voyger](https://github.com/APIs-guru/graphql-voyager)) -# Requirements and Downloads +## Requirements and Downloads Requirements: @@ -104,7 +105,6 @@ Gradle: ```gradle repositories { - jcenter() mavenCentral() } @@ -117,6 +117,9 @@ dependencies { // to embed GraphiQL tool runtimeOnly 'com.graphql-java-kickstart:graphiql-spring-boot-starter:11.0.0' + // to embed GraphQL Playground tool + runtimeOnly 'com.graphql-java-kickstart:playground-spring-boot-starter:11.0.0' + // to embed Voyager tool runtimeOnly 'com.graphql-java-kickstart:voyager-spring-boot-starter:11.0.0' @@ -150,6 +153,14 @@ Maven: runtime + + + com.graphql-java-kickstart + playground-spring-boot-starter + 11.0.0 + runtime + + com.graphql-java-kickstart @@ -168,34 +179,15 @@ Maven: ``` -New releases will be available faster in the JCenter repository than in Maven Central. Add the -following to use for Maven - -```xml - - - jcenter - https://jcenter.bintray.com/ - - -``` - -For Gradle: - -```groovy -repositories { - jcenter() -} -``` ### Snapshots ```xml - jfrog-snapshots - oss-jfrog-artifactory-snapshots - https://oss.jfrog.org/artifactory/oss-snapshot-local + osshr-snapshots + osshr-sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots/ ``` @@ -204,7 +196,7 @@ For gradle: ```groovy repositories { - maven { url "https://oss.jfrog.org/artifactory/oss-snapshot-local" } + maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } } ``` @@ -266,13 +258,12 @@ graphiql: subscriptions: timeout: 30 reconnect: false - static: - basePath: / + basePath: / enabled: true pageTitle: GraphiQL cdn: enabled: false - version: 0.13.0 + version: latest props: resources: query: query.graphql @@ -446,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`. @@ -605,6 +652,22 @@ The following metrics are available for exposure: * `graphql.websocket.sessions` - number of active websocket sessions for subscriptions * `graphql.websocket.subscriptions` - number of active subscriptions + +## FAQs +### WARNING: NoClassDefFoundError when using GraphQL Java Tools > 5.4.x + +If you're using `graphql-java-tools` in combination with Spring Boot 2.1.x or below then you need to +set the +`kotlin.version` in your Spring Boot project explicitly to version >= 1.3.70, because Spring Boot +Starter parent of that Spring Boot version overrides it with a 1.2.* version of Kotlin. +`graphql-java-tools` requires 1.3.* however because of its coroutine support. If you don't override +this version you will run into a `NoClassDefFoundError`. + +Spring Boot team has indicated the Kotlin version will be upgraded to 1.3 in Spring Boot 2.2. + + + + # Contributions Contributions are welcome. Please respect 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 128bd07a..526d30b9 100644 --- a/build.gradle +++ b/build.gradle @@ -21,12 +21,11 @@ import org.gradle.api.tasks.testing.logging.TestExceptionFormat import org.gradle.api.tasks.testing.logging.TestLogEvent plugins { - id "com.jfrog.bintray" version "$LIB_BINTRAY_PLUGIN_VER" apply false - id 'net.researchgate.release' version "$LIB_RELEASE_PLUGIN_VER" id "org.springframework.boot" version "$LIB_SPRING_BOOT_VER" apply false - id "com.jfrog.artifactory" version "4.15.1" apply false - id "org.sonarqube" version "3.0" + id "org.sonarqube" version "$PLUGIN_SONARQUBE_VER" id "jacoco" + id 'io.codearte.nexus-staging' version "$PLUGIN_NEXUS_STAGING_VER" + id 'com.github.sherter.google-java-format' version "$PLUGIN_GOOGLE_JAVA_FORMAT_VER" apply false } sonarqube { @@ -37,83 +36,89 @@ sonarqube { } } +def bomProjectName = "graphql-spring-boot-dependencies" + subprojects { apply plugin: 'idea' - apply plugin: 'jacoco' - apply plugin: 'org.sonarqube' - apply plugin: 'java' - apply plugin: 'java-library' + if (it.name != bomProjectName) { + apply plugin: 'jacoco' + apply plugin: 'org.sonarqube' + apply plugin: 'java' + apply plugin: 'java-library' + apply plugin: "io.spring.dependency-management" + } apply plugin: 'maven-publish' - apply plugin: "com.jfrog.bintray" - apply plugin: "io.spring.dependency-management" - apply plugin: 'com.jfrog.artifactory' + apply plugin: 'signing' + apply plugin: 'com.github.sherter.google-java-format' group "$PROJECT_GROUP" repositories { mavenLocal() mavenCentral() - jcenter() - maven { url "https://dl.bintray.com/graphql-java-kickstart/releases" } maven { url "https://repo.spring.io/libs-milestone" } maven { url "https://oss.sonatype.org/content/repositories/snapshots" } maven { url "https://oss.jfrog.org/artifactory/oss-snapshot-local" } } - dependencyManagement { - imports { - mavenBom "org.springframework.boot:spring-boot-starter-parent:$LIB_SPRING_BOOT_VER" + if (it.name != bomProjectName) { + dependencyManagement { + imports { + mavenBom "org.springframework.boot:spring-boot-starter-parent:$LIB_SPRING_BOOT_VER" + } } - } - dependencies { - compileOnly "org.projectlombok:lombok" - annotationProcessor "org.projectlombok:lombok" + dependencies { + compileOnly "org.projectlombok:lombok" + annotationProcessor "org.projectlombok:lombok" - testCompileOnly "org.projectlombok:lombok" - testAnnotationProcessor "org.projectlombok:lombok" - } + testCompileOnly "org.projectlombok:lombok" + testAnnotationProcessor "org.projectlombok:lombok" + } - test { - useJUnitPlatform() - testLogging { - events TestLogEvent.FAILED, - TestLogEvent.PASSED, - TestLogEvent.SKIPPED, - TestLogEvent.STANDARD_ERROR, - TestLogEvent.STANDARD_OUT - exceptionFormat TestExceptionFormat.FULL - showCauses true - showExceptions true - showStackTraces true + test { + useJUnitPlatform() + testLogging { + events TestLogEvent.FAILED, + TestLogEvent.PASSED, + TestLogEvent.SKIPPED, + TestLogEvent.STANDARD_ERROR, + TestLogEvent.STANDARD_OUT + exceptionFormat TestExceptionFormat.FULL + showCauses true + showExceptions true + showStackTraces true + } } - } - jacoco { - toolVersion = "0.8.7-SNAPSHOT" - } + jacoco { + toolVersion = "$PLUGIN_JACOCO_VER" + } - jacocoTestReport { - reports { - xml.enabled = true - html.enabled = false - csv.enabled = false + jacocoTestReport { + reports { + xml.enabled = true + html.enabled = false + csv.enabled = false + } } - } - idea { - module { - downloadJavadoc = true - downloadSources = true + idea { + module { + downloadJavadoc = true + downloadSources = true + } } - } - compileJava { - sourceCompatibility = SOURCE_COMPATIBILITY - targetCompatibility = TARGET_COMPATIBILITY - } + compileJava { + sourceCompatibility = SOURCE_COMPATIBILITY + targetCompatibility = TARGET_COMPATIBILITY + } + + compileJava.dependsOn(processResources) - compileJava.dependsOn(processResources) + compileJava.mustRunAfter verifyGoogleJavaFormat + } if (!it.name.startsWith('example')) { @@ -122,19 +127,33 @@ subprojects { enabled = false } - jar { - from "LICENSE.md" + if (it.name != bomProjectName) { + jar { + from "LICENSE.md" + } + + java { + withSourcesJar() + withJavadocJar() + } } - java { - withSourcesJar() - withJavadocJar() + if (!version.toString().endsWith('-SNAPSHOT')) { + ext["signing.keyId"] = System.env.SIGNING_KEY_ID + ext["signing.password"] = System.env.SIGNING_PASSWORD + ext["signing.secretKeyRingFile"] = System.env.SIGNING_SECRET_KEY_RING_FILE + + signing { + sign publishing.publications + } } publishing { publications { - mainProjectPublication(MavenPublication) { - from components.java + mavenJava(MavenPublication) { + if (project.name != bomProjectName) { + from components.java + } // to avoid "Publication only contains dependencies and/or constraints without a version" error // see https://docs.gradle.org/6.2.1/userguide/publishing_maven.html#publishing_maven:resolved_dependencies @@ -148,7 +167,6 @@ subprojects { } pom { - resolveStrategy = DELEGATE_FIRST name = PROJECT_NAME description = PROJECT_DESC url = PROJECT_GIT_REPO_URL @@ -173,83 +191,27 @@ subprojects { } } } - } - - bintray { - user = System.env.BINTRAY_USER ?: project.findProperty('BINTRAY_USER') ?: '' - key = System.env.BINTRAY_PASS ?: project.findProperty('BINTRAY_PASS') ?: '' - publications = ['mainProjectPublication'] - publish = true - pkg { - repo = 'releases' - name = PROJECT_NAME - desc = PROJECT_DESC - licenses = [PROJECT_LICENSE] - vcsUrl = PROJECT_GIT_REPO_URL - userOrg = 'graphql-java-kickstart' - version { - name = project.version - gpg { - sign = true + repositories { + maven { + name 'ossrh' + if (version.toString().endsWith("-SNAPSHOT")) { + url "https://oss.sonatype.org/content/repositories/snapshots/" + } else { + url "https://oss.sonatype.org/service/local/staging/deploy/maven2" } - mavenCentralSync { - user = System.env.OSS_USER_TOKEN_KEY ?: project.findProperty('OSS_USER_TOKEN_KEY') ?: '' + credentials { + username = System.env.OSS_USER_TOKEN_KEY ?: project.findProperty('OSS_USER_TOKEN_KEY') ?: '' password = System.env.OSS_USER_TOKEN_PASS ?: project.findProperty('OSS_USER_TOKEN_PASS') ?: '' } } } } - - artifactory { - contextUrl = 'https://oss.jfrog.org' - publish { - repository { - if (project.version.endsWith("-SNAPSHOT")) { - repoKey = 'oss-snapshot-local' - } else { - repoKey = 'oss-release-local' - } - username = System.env.BINTRAY_USER ?: project.findProperty('BINTRAY_USER') ?: '' - password = System.env.BINTRAY_PASS ?: project.findProperty('BINTRAY_PASS') ?: '' - } - defaults { - publications('mainProjectPublication') - publishArtifacts = true - publishPom = true - } - } - resolve { - repoKey = 'oss-snapshot-local' - } - clientConfig.info.setBuildNumber(System.getProperty('build.number')) - } } } -release { - tagTemplate = 'v${version}' - failOnPublishNeeded = false - ignoredSnapshotDependencies = [ - 'com.graphql-java-kickstart:altair-spring-boot-autoconfigure', - 'com.graphql-java-kickstart:altair-spring-boot-starter', - 'com.graphql-java-kickstart:graphiql-spring-boot-autoconfigure', - 'com.graphql-java-kickstart:graphiql-spring-boot-starter', - 'com.graphql-java-kickstart:graphql-spring-boot-autoconfigure', - 'com.graphql-java-kickstart:graphql-spring-boot-starter', - 'com.graphql-java-kickstart:graphql-spring-boot-starter-test', - 'com.graphql-java-kickstart:graphql-spring-boot-test', - 'com.graphql-java-kickstart:graphql-spring-boot-test-autoconfigure', - 'com.graphql-java-kickstart:voyager-spring-boot-autoconfigure', - 'com.graphql-java-kickstart:voyager-spring-boot-starter', - 'com.graphql-java-kickstart:playground-spring-boot-autoconfigure', - 'com.graphql-java-kickstart:playground-spring-boot-starter' - ] -} - -task build { - dependsOn subprojects.findResults { it.tasks.findByName('assemble') } - dependsOn subprojects.findResults { it.tasks.findByName('check') } - dependsOn subprojects.findResults { it.tasks.findByName('bintray') } +nexusStaging { + username = System.env.OSS_USER_TOKEN_KEY ?: project.findProperty('OSS_USER_TOKEN_KEY') ?: '' + password = System.env.OSS_USER_TOKEN_PASS ?: project.findProperty('OSS_USER_TOKEN_PASS') ?: '' } wrapper { diff --git a/example-graphql-subscription/build.gradle b/example-graphql-subscription/build.gradle index 3f028f41..313a6d8c 100644 --- a/example-graphql-subscription/build.gradle +++ b/example-graphql-subscription/build.gradle @@ -3,6 +3,7 @@ apply plugin: "org.springframework.boot" dependencies { implementation(project(":graphql-spring-boot-starter")) implementation(project(":graphiql-spring-boot-starter")) + implementation(project(":playground-spring-boot-starter")) implementation "com.graphql-java-kickstart:graphql-java-tools:$LIB_GRAPHQL_JAVA_TOOLS_VER" implementation "io.reactivex.rxjava2:rxjava" @@ -13,6 +14,5 @@ dependencies { } jar.enabled = false -uploadArchives.enabled = false -bintrayUpload.enabled = false +publish.enabled = false publishToMavenLocal.enabled = false 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-subscription/src/main/resources/public/index.html b/example-graphql-subscription/src/main/resources/public/index.html index 3a8ab927..69beb433 100644 --- a/example-graphql-subscription/src/main/resources/public/index.html +++ b/example-graphql-subscription/src/main/resources/public/index.html @@ -43,7 +43,7 @@ - + diff --git a/example-graphql-tools/build.gradle b/example-graphql-tools/build.gradle index 110c7c69..dba360b4 100644 --- a/example-graphql-tools/build.gradle +++ b/example-graphql-tools/build.gradle @@ -32,6 +32,5 @@ dependencies { } jar.enabled = false -uploadArchives.enabled = false -bintrayUpload.enabled = false +publish.enabled = false publishToMavenLocal.enabled = false 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/build.gradle b/example-request-scoped-dataloader/build.gradle index a5e89641..d6cda098 100644 --- a/example-request-scoped-dataloader/build.gradle +++ b/example-request-scoped-dataloader/build.gradle @@ -12,6 +12,5 @@ dependencies { } jar.enabled = false -uploadArchives.enabled = false -bintrayUpload.enabled = false -publishToMavenLocal.enabled = false \ No newline at end of file +publish.enabled = false +publishToMavenLocal.enabled = false 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/build.gradle b/example-spring-common/build.gradle index ddb74e64..32a5917d 100644 --- a/example-spring-common/build.gradle +++ b/example-spring-common/build.gradle @@ -24,7 +24,7 @@ dependencies { implementation(project(":graphiql-spring-boot-starter")) implementation "com.embedler.moon.graphql:spring-graphql-common:2.1.0-2016-05-22T16-50-32" - implementation group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.3' + implementation group: 'commons-fileupload', name: 'commons-fileupload', version: '1.4' implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter-actuator") @@ -33,6 +33,5 @@ dependencies { } jar.enabled = false -uploadArchives.enabled = false -bintrayUpload.enabled = false +publish.enabled = false publishToMavenLocal.enabled = false 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/build.gradle b/example-webflux/build.gradle index 64556854..c182df41 100644 --- a/example-webflux/build.gradle +++ b/example-webflux/build.gradle @@ -23,12 +23,12 @@ dependencies { implementation(project(":graphql-kickstart-spring-boot-starter-webflux")) implementation(project(":graphql-kickstart-spring-boot-starter-tools")) implementation(project(":voyager-spring-boot-starter")) + implementation(project(":playground-spring-boot-starter")) implementation("org.springframework.boot:spring-boot-starter-webflux:$LIB_SPRING_BOOT_VER") implementation("org.springframework.boot:spring-boot-starter-actuator:$LIB_SPRING_BOOT_VER") } jar.enabled = false -uploadArchives.enabled = false -bintrayUpload.enabled = false +publish.enabled = false publishToMavenLocal.enabled = false 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/build.gradle b/example/build.gradle index 679121eb..b864f538 100644 --- a/example/build.gradle +++ b/example/build.gradle @@ -31,6 +31,5 @@ dependencies { } jar.enabled = false -uploadArchives.enabled = false -bintrayUpload.enabled = false +publish.enabled = false publishToMavenLocal.enabled = false 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 2f083bdd..6e9d498f 100644 --- a/github-build.sh +++ b/github-build.sh @@ -42,10 +42,10 @@ commitNextVersion() { git config --global user.email "actions@github.com" git config --global user.name "GitHub Actions" -echo "Deploying release to Bintray" +echo "Deploying release to Maven Central" removeSnapshots -./gradlew clean assemble && ./gradlew bintrayUpload -x check --info +./gradlew clean build publish closeAndReleaseRepository -x verifyGoogleJavaFormat commitRelease bumpVersion diff --git a/gradle.properties b/gradle.properties index ecabe910..afb3b439 100644 --- a/gradle.properties +++ b/gradle.properties @@ -32,18 +32,18 @@ SOURCE_COMPATIBILITY=1.8 TARGET_COMPATIBILITY=1.8 ### Dependencies LIB_GRAPHQL_JAVA_VER=16.2 -LIB_EXTENDED_SCALARS_VERSION=16.0.0 -LIB_SPRING_BOOT_VER=2.4.3 +LIB_EXTENDED_SCALARS_VER=16.0.1 +LIB_SPRING_BOOT_VER=2.4.5 LIB_GRAPHQL_SERVLET_VER=11.1.0 -LIB_GRAPHQL_JAVA_TOOLS_VER=11.0.0 +LIB_GRAPHQL_JAVA_TOOLS_VER=11.0.1 LIB_GRAPHQL_ANNOTATIONS_VER=8.3 LIB_REFLECTIONS_VER=0.9.11 -LIB_APACHE_COMMONS_TEXT=1.8 +LIB_APACHE_COMMONS_TEXT=1.9 LIB_JSOUP_VER=1.13.1 -### Gradle Plugins -LIB_BINTRAY_PLUGIN_VER=1.8.5 -LIB_RELEASE_PLUGIN_VER=2.8.1 +### Plugins +PLUGIN_JACOCO_VER=0.8.7-SNAPSHOT +PLUGIN_SONARQUBE_VER=3.2.0 +PLUGIN_NEXUS_STAGING_VER=0.30.0 +PLUGIN_GOOGLE_JAVA_FORMAT_VER=0.9 ### org.gradle.daemon=true -bintray.user=USER -bintray.key=KEY diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 1c4bcc29..3c4101c3 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists 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 7bf8cd3c..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,18 +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()); - return singletonList( - GraphqlErrorBuilder.newError() - .message(throwable.getMessage()) - .errorType(errorContext.getErrorType()) - .locations(errorContext.getLocations()) - .path(errorContext.getPath()) - .extensions(extensions) - .build() - ); + 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 new file mode 100644 index 00000000..83bc4131 --- /dev/null +++ b/graphql-kickstart-spring-support/src/test/java/graphql/kickstart/spring/error/GraphQLErrorFromExceptionHandlerTest.java @@ -0,0 +1,43 @@ +package graphql.kickstart.spring.error; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import graphql.ErrorType; +import graphql.GraphQLError; +import graphql.GraphqlErrorException; +import graphql.language.SourceLocation; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +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()); + + List processedErrors = sut.filterGraphQLErrors(errors); + + for (int i = 0; i < errors.size(); i++) { + GraphQLError error = errors.get(i); + GraphQLError processedError = processedErrors.get(i); + assertEquals(error.getMessage(), processedError.getMessage()); + assertEquals(error.getErrorType(), processedError.getErrorType()); + assertEquals(error.getLocations(), processedError.getLocations()); + assertEquals(error.getPath(), processedError.getPath()); + } + } +} 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/build.gradle b/graphql-spring-boot-autoconfigure/build.gradle index 04e59ca9..fb681c35 100644 --- a/graphql-spring-boot-autoconfigure/build.gradle +++ b/graphql-spring-boot-autoconfigure/build.gradle @@ -21,7 +21,7 @@ dependencies { api(project(":graphql-kickstart-spring-boot-starter-tools")) api(project(":graphql-kickstart-spring-support")) implementation "org.springframework.boot:spring-boot-autoconfigure" - api "com.graphql-java:graphql-java-extended-scalars:$LIB_EXTENDED_SCALARS_VERSION" + api "com.graphql-java:graphql-java-extended-scalars:$LIB_EXTENDED_SCALARS_VER" api "com.graphql-java-kickstart:graphql-java-kickstart:$LIB_GRAPHQL_SERVLET_VER" api "com.graphql-java-kickstart:graphql-java-servlet:$LIB_GRAPHQL_SERVLET_VER" api "com.graphql-java:graphql-java:$LIB_GRAPHQL_JAVA_VER" 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-dependencies/build.gradle b/graphql-spring-boot-dependencies/build.gradle new file mode 100644 index 00000000..93d5462e --- /dev/null +++ b/graphql-spring-boot-dependencies/build.gradle @@ -0,0 +1,31 @@ +apply plugin: "java-platform" + +dependencies { + constraints { + api "com.graphql-java:graphql-java-extended-scalars:$LIB_EXTENDED_SCALARS_VER" + api "com.graphql-java:graphql-java:$LIB_GRAPHQL_JAVA_VER" + api "com.graphql-java-kickstart:graphql-java-servlet:$LIB_GRAPHQL_SERVLET_VER" + api "com.graphql-java-kickstart:graphql-java-kickstart:$LIB_GRAPHQL_SERVLET_VER" + api "com.graphql-java-kickstart:graphql-java-tools:$LIB_GRAPHQL_JAVA_TOOLS_VER" + api "io.github.graphql-java:graphql-java-annotations:$LIB_GRAPHQL_ANNOTATIONS_VER" + api project(":graphql-spring-boot-starter") + runtime project(":altair-spring-boot-starter") + runtime project(":graphiql-spring-boot-starter") + runtime project(":voyager-spring-boot-starter") + runtime project(":playground-spring-boot-starter") + api project(":graphql-spring-boot-starter-test") + api project(":graphql-kickstart-spring-boot-starter-webflux") + api project(":graphql-kickstart-spring-boot-starter-tools") + api project(":graphql-kickstart-spring-boot-starter-graphql-annotations") + } +} + +publishing { + publications { + mainProjectPublication(MavenPublication) { + from components.javaPlatform + } + } +} + + 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 b47c50e3..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."); } @@ -300,9 +291,19 @@ public List awaitAndGetNextResponses( fail("Subscription already stopped. Forgot to call reset after test case?"); } - await() - .atMost(timeout, TimeUnit.MILLISECONDS) - .until(() -> state.getResponses().size() >= numExpectedResponses); + if (numExpectedResponses > 0) { + await() + .atMost(timeout, TimeUnit.MILLISECONDS) + .until(() -> state.getResponses().size() >= numExpectedResponses); + } else { + try { + Thread.sleep(timeout); + } catch (InterruptedException e) { + fail("Unable to wait the specified amount of time.", e); + // Restore interrupted state + Thread.currentThread().interrupt(); + } + } if (stopAfter) { stop(); @@ -312,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; } @@ -340,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; } @@ -374,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) { @@ -399,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 ""; } } @@ -414,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 @@ -460,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."); @@ -477,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 5959c8c8..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,6 +2,7 @@ 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; @@ -13,46 +14,52 @@ class GraphQLSubscriptionTestAwaitNoAnswerTest extends GraphQLTestSubscriptionTe @Test @DisplayName("Should succeed if no responses arrived / default stopAfter.") void shouldAwaitNoResponseSucceedIfNoResponsesArrivedDefaultStopAfter() { - // WHEN - THEN + // GIVEN + final Instant timeBeforeTestStart = Instant.now(); + // WHEN graphQLTestSubscription .start(SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE) .waitAndExpectNoResponse(TIMEOUT); + // THEN assertThatSubscriptionWasStopped(); + assertThatMinimumRequiredTimeElapsedSince(timeBeforeTestStart); } @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Should succeed if no responses arrive.") - void shouldAwaitNoResponseSucceedIfNoResponsesArrived( - final boolean stopAfter - ) { - // WHEN - THEN + void shouldAwaitNoResponseSucceedIfNoResponsesArrived(final boolean stopAfter) { + // GIVEN + final Instant timeBeforeTestStart = Instant.now(); + // WHEN graphQLTestSubscription .start(SUBSCRIPTION_THAT_TIMES_OUT_RESOURCE) .waitAndExpectNoResponse(TIMEOUT, stopAfter); + // THEN assertThatSubscriptionStoppedStatusIs(stopAfter); + assertThatMinimumRequiredTimeElapsedSince(timeBeforeTestStart); } @Test @DisplayName("Should raise assertion error if any response arrived / default stop after.") void shouldRaiseAssertionErrorIfResponseArrivedDefaultStopAfter() { - // WHEN - THEN + // WHEN graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE); - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> graphQLTestSubscription - .waitAndExpectNoResponse(TIMEOUT)); + // THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLTestSubscription.waitAndExpectNoResponse(TIMEOUT)); assertThatSubscriptionWasStopped(); } @ParameterizedTest @ValueSource(booleans = {true, false}) @DisplayName("Should raise assertion error if any response arrived.") - void shouldRaiseAssertionErrorIfResponseArrived( - final boolean stopAfter - ) { - // WHEN - THEN + void shouldRaiseAssertionErrorIfResponseArrived(final boolean stopAfter) { + // WHEN graphQLTestSubscription.start(TIMER_SUBSCRIPTION_RESOURCE); - assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> graphQLTestSubscription - .waitAndExpectNoResponse(TIMEOUT, stopAfter)); + // THEN + assertThatExceptionOfType(AssertionError.class) + .isThrownBy(() -> graphQLTestSubscription.waitAndExpectNoResponse(TIMEOUT, stopAfter)); assertThatSubscriptionStoppedStatusIs(stopAfter); } } 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 bcc42c3b..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 @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Map; @@ -11,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.") @@ -21,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(); } @@ -30,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)) @@ -43,50 +46,57 @@ void shouldAwaitAndGetMultipleResponses() { @Test @DisplayName("Should await and get all responses / default stopAfter.") 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)) .containsExactly(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); assertThatSubscriptionWasStopped(); + assertThatMinimumRequiredTimeElapsedSince(timeBeforeTest); } @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)) .containsExactly(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); assertThatSubscriptionStoppedStatusIs(stopAfter); + assertThatMinimumRequiredTimeElapsedSince(timeBeforeTest); } @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)) @@ -94,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)) @@ -113,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 @@ -121,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 280bad9b..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,40 +3,45 @@ 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; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.Environment; @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 @@ -53,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() { @@ -63,4 +66,10 @@ protected void assertThatSubscriptionWasNotStopped() { .as("Subscription should not be stopped.") .isFalse(); } + + protected void assertThatMinimumRequiredTimeElapsedSince(final Instant timeBeforeTestStart) { + assertThat(Duration.between(timeBeforeTestStart, Instant.now())) + .as("Should wait the specified amount of time") + .isGreaterThanOrEqualTo(Duration.ofMillis(TIMEOUT)); + } } 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/build.gradle b/playground-spring-boot-autoconfigure/build.gradle index 9083b867..4803fb78 100644 --- a/playground-spring-boot-autoconfigure/build.gradle +++ b/playground-spring-boot-autoconfigure/build.gradle @@ -20,13 +20,17 @@ dependencies{ annotationProcessor "org.springframework.boot:spring-boot-configuration-processor" implementation "org.springframework.boot:spring-boot-autoconfigure" - implementation "org.springframework.boot:spring-boot-starter-web" + compileOnly "org.springframework.boot:spring-boot-starter-web" + compileOnly "org.springframework.boot:spring-boot-starter-webflux" + compileOnly "org.springframework.boot:spring-boot-starter-security" implementation "org.springframework.boot:spring-boot-starter-thymeleaf" implementation "org.springframework.boot:spring-boot-starter-validation" testImplementation "org.springframework.boot:spring-boot-starter-web" + testImplementation "org.springframework.boot:spring-boot-starter-webflux" testImplementation "org.springframework.boot:spring-boot-starter-test" testImplementation "org.springframework.boot:spring-boot-starter-security" + testImplementation "org.springframework.security:spring-security-test" testImplementation "org.jsoup:jsoup:$LIB_JSOUP_VER" } 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 6a724b0a..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 @@ -1,24 +1,25 @@ package graphql.kickstart.playground.boot; import com.fasterxml.jackson.databind.ObjectMapper; -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.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.DispatcherServlet; @Configuration @ConditionalOnWebApplication -@ConditionalOnClass(DispatcherServlet.class) @EnableConfigurationProperties(PlaygroundPropertiesConfiguration.class) public class PlaygroundAutoConfiguration { - @Bean - @ConditionalOnProperty(value = "graphql.playground.enabled", havingValue = "true", matchIfMissing = true) - 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 4b58a9ff..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,67 +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 javax.servlet.http.HttpServletRequest; -import java.nio.file.Paths; +import org.springframework.web.bind.annotation.RequestAttribute; @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 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 HttpServletRequest request) { - if (propertiesConfiguration.getPlayground().getCdn().isEnabled()) { - setCdnUrls(model); - } else { - setLocalAssetUrls(model); - } - model.addAttribute("pageTitle", propertiesConfiguration.getPlayground().getPageTitle()); - model.addAttribute("properties", objectMapper.valueToTree(propertiesConfiguration.getPlayground())); - model.addAttribute("_csrf", request.getAttribute("_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 new file mode 100644 index 00000000..a095e944 --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundWebFluxAutoConfiguration.java @@ -0,0 +1,60 @@ +package graphql.kickstart.playground.boot; + +import java.nio.charset.StandardCharsets; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.core.io.ClassPathResource; +import org.springframework.web.reactive.config.ViewResolverRegistry; +import org.springframework.web.reactive.config.WebFluxConfigurer; +import org.springframework.web.reactive.function.server.RouterFunction; +import org.springframework.web.reactive.function.server.RouterFunctions; +import org.springframework.web.reactive.function.server.ServerResponse; +import org.thymeleaf.spring5.SpringWebFluxTemplateEngine; +import org.thymeleaf.spring5.view.reactive.ThymeleafReactiveViewResolver; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; + +@Configuration +@Import(PlaygroundWebFluxControllerAdvice.class) +@ConditionalOnClass(WebFluxConfigurer.class) +@ConditionalOnProperty( + value = "graphql.playground.enabled", + havingValue = "true", + matchIfMissing = true) +@RequiredArgsConstructor +public class PlaygroundWebFluxAutoConfiguration implements WebFluxConfigurer { + + private final ApplicationContext applicationContext; + + @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); + } +} 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 new file mode 100644 index 00000000..271181a6 --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/main/java/graphql/kickstart/playground/boot/PlaygroundWebFluxControllerAdvice.java @@ -0,0 +1,23 @@ +package graphql.kickstart.playground.boot; + +import lombok.NoArgsConstructor; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.security.web.reactive.result.view.CsrfRequestDataValueProcessor; +import org.springframework.security.web.server.csrf.CsrfToken; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +@NoArgsConstructor +@ControllerAdvice +@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()); + } +} 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/main/resources/META-INF/spring.factories b/playground-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories index 830e9efe..0f00e9a5 100644 --- a/playground-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories +++ b/playground-spring-boot-autoconfigure/src/main/resources/META-INF/spring.factories @@ -1 +1 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=graphql.kickstart.playground.boot.PlaygroundAutoConfiguration +org.springframework.boot.autoconfigure.EnableAutoConfiguration=graphql.kickstart.playground.boot.PlaygroundAutoConfiguration,graphql.kickstart.playground.boot.PlaygroundWebFluxAutoConfiguration 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 42dba75f..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 @@ -11,14 +11,14 @@ @SpringBootTest(classes = PlaygroundTestConfig.class) @AutoConfigureMockMvc @TestPropertySource("classpath:application-playground-cdn-custom-version-test.properties") -class PlaygroundCdnCustomVersionTest extends PlaygroundResourcesTestBase { +public class PlaygroundCdnCustomVersionTest extends PlaygroundResourcesTestBase { @Test - void shouldLoadSpecifiedVersionFromCdn() throws Exception { - String LOGO_CDN_PATH = "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/logo.png"; - String FAVICON_CDN_PATH = "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/favicon.png"; - String SCRIPT_CDN_PATH = "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/static/js/middleware.js"; - String CSS_CDN_PATH = "https://cdn.jsdelivr.net/npm/graphql-playground-react@1.7.10/build/static/css/index.css"; - testPlaygroundResources(CSS_CDN_PATH, SCRIPT_CDN_PATH, FAVICON_CDN_PATH, LOGO_CDN_PATH); + 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 1ee91efa..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 @@ -11,14 +11,14 @@ @SpringBootTest(classes = PlaygroundTestConfig.class) @AutoConfigureMockMvc @TestPropertySource("classpath:application-playground-cdn-test.properties") -class PlaygroundCdnTest extends PlaygroundResourcesTestBase { +public class PlaygroundCdnTest extends PlaygroundResourcesTestBase { @Test - void shouldLoadLatestVersionFromCdn() throws Exception { - String LOGO_CDN_PATH = "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/logo.png"; - String FAVICON_CDN_PATH = "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/favicon.png"; - String SCRIPT_CDN_PATH = "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/static/js/middleware.js"; - String CSS_CDN_PATH = "https://cdn.jsdelivr.net/npm/graphql-playground-react@latest/build/static/css/index.css"; - testPlaygroundResources(CSS_CDN_PATH, SCRIPT_CDN_PATH, FAVICON_CDN_PATH, LOGO_CDN_PATH); + 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 618bddf5..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 @@ -21,16 +21,14 @@ @SpringBootTest(classes = PlaygroundTestConfig.class) @AutoConfigureMockMvc @TestPropertySource("classpath:application-playground-mapping-test.properties") -class PlaygroundCustomMappingTest { +public class PlaygroundCustomMappingTest { - private static final String CONFIGURED_MAPPING = "/test-mapping"; - - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test - void shouldUseTheConfiguredRequestMapping() throws Exception { - mockMvc.perform(get(CONFIGURED_MAPPING)) + 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())) 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 a4ef063c..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 @@ -11,15 +11,14 @@ @SpringBootTest(classes = PlaygroundTestConfig.class) @AutoConfigureMockMvc @TestPropertySource("classpath:application-playground-custom-static-path.properties") -class PlaygroundCustomStaticPathTest extends PlaygroundResourcesTestBase { - - private static final String CUSTOM_CSS_URL = "/custom-static-path/static/css/index.css"; - private static final String CUSTOM_SCRIPT_URL = "/custom-static-path/static/js/middleware.js"; - private static final String CUSTOM_FAVICON_URL = "/custom-static-path/favicon.png"; - private static final String CUSTOM_LOGO_URL = "/custom-static-path/logo.png"; +public class PlaygroundCustomStaticPathTest extends PlaygroundResourcesTestBase { @Test - void shouldLoadStaticResourcesFromCustomPath() throws Exception { - testPlaygroundResources(CUSTOM_CSS_URL, CUSTOM_SCRIPT_URL, CUSTOM_FAVICON_URL, CUSTOM_LOGO_URL); + 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 54f081e0..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 @@ -20,22 +20,24 @@ @SpringBootTest(classes = PlaygroundTestConfig.class) @AutoConfigureMockMvc @TestPropertySource("classpath:application-playground-custom-title.properties") -class PlaygroundCustomTitleTest { +public class PlaygroundCustomTitleTest { - private static final String CUSTOM_TITLE = "My CustomTest Title"; - - @Autowired - private MockMvc mockMvc; + @Autowired private MockMvc mockMvc; @Test - 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, CUSTOM_TITLE)) - .andReturn(); + 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, CUSTOM_TITLE); + 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 7913ce6c..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 @@ -3,19 +3,24 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration; +import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.test.context.ContextConfiguration; -@EnableAutoConfiguration +@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 acc4a203..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,39 +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 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); + } + + 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(); + } -final class PlaygroundTestHelper { - static final String DEFAULT_PLAYGROUND_ENDPOINT = "/playground"; - static final String CSS_URL_FIELD_NAME = "cssUrl"; - static final String SCRIPT_URL_FIELD_NAME = "scriptUrl"; - static final String FAVICON_URL_FIELD_NAME = "faviconUrl"; - static final String LOGO_URL_FIELD_NAME = "logoUrl"; - static final String PAGE_TITLE_FIELD_NAME = "pageTitle"; - - static void assertTitle(final Document document, final String title) { - assertThat(document.select("head title")).extracting(Element::text).containsExactly(title); - } - - 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(); - } - 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 new file mode 100644 index 00000000..0576f866 --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCSRFTest.java @@ -0,0 +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; + +@SpringBootTest(classes = PlaygroundWebFluxTestConfig.class) +@AutoConfigureWebTestClient +public class PlaygroundWebFluxCSRFTest { + + @Autowired private WebTestClient webTestClient; + + @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\"}"); + } +} 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 new file mode 100644 index 00000000..cfbd229b --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCdnTest.java @@ -0,0 +1,22 @@ +package graphql.kickstart.playground.boot.webflux; + +import graphql.kickstart.playground.boot.PlaygroundTestHelper; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; + +@SpringBootTest(classes = PlaygroundWebFluxTestConfig.class) +@AutoConfigureWebTestClient +@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); + } +} 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 new file mode 100644 index 00000000..51cecc4b --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomCdnVersionTest.java @@ -0,0 +1,22 @@ +package graphql.kickstart.playground.boot.webflux; + +import graphql.kickstart.playground.boot.PlaygroundTestHelper; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; + +@SpringBootTest(classes = PlaygroundWebFluxTestConfig.class) +@AutoConfigureWebTestClient +@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); + } +} 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 new file mode 100644 index 00000000..fc61e7c3 --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomMappingTest.java @@ -0,0 +1,30 @@ +package graphql.kickstart.playground.boot.webflux; + +import graphql.kickstart.playground.boot.PlaygroundTestHelper; +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.http.MediaType; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.web.reactive.server.WebTestClient; + +@SpringBootTest(classes = PlaygroundWebFluxTestConfig.class) +@AutoConfigureWebTestClient +@TestPropertySource("classpath:application-playground-mapping-test.properties") +public class PlaygroundWebFluxCustomMappingTest { + + @Autowired private WebTestClient webTestClient; + + @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 new file mode 100644 index 00000000..d90b9aa1 --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomStaticPathTest.java @@ -0,0 +1,22 @@ +package graphql.kickstart.playground.boot.webflux; + +import graphql.kickstart.playground.boot.PlaygroundTestHelper; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; + +@SpringBootTest(classes = PlaygroundWebFluxTestConfig.class) +@AutoConfigureWebTestClient +@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); + } +} 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 new file mode 100644 index 00000000..a2afcfb1 --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxCustomTitleTest.java @@ -0,0 +1,42 @@ +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; +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.context.TestPropertySource; +import org.springframework.test.web.reactive.server.WebTestClient; + +@SpringBootTest(classes = PlaygroundWebFluxTestConfig.class) +@AutoConfigureWebTestClient +@TestPropertySource("classpath:application-playground-custom-title.properties") +public class PlaygroundWebFluxCustomTitleTest { + + @Autowired private WebTestClient webTestClient; + + @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); + } +} 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 new file mode 100644 index 00000000..8b9754ad --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxDisabledTest.java @@ -0,0 +1,40 @@ +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; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +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.context.ApplicationContext; +import org.springframework.test.web.reactive.server.WebTestClient; + +@SpringBootTest( + classes = PlaygroundWebFluxTestConfig.class, + properties = "graphql.playground.enabled=false") +@AutoConfigureWebTestClient +public class PlaygroundWebFluxDisabledTest { + + @Autowired private ApplicationContext applicationContext; + + @Autowired private WebTestClient webTestClient; + + @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(); + } +} 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 new file mode 100644 index 00000000..cac1eca9 --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxEnabledTest.java @@ -0,0 +1,126 @@ +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; +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.context.ApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.MediaType; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.util.StreamUtils; +import org.springframework.web.reactive.function.client.ExchangeStrategies; + +@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"; + + @Autowired private ApplicationContext applicationContext; + + @Autowired private WebTestClient webTestClient; + + @Autowired private ObjectMapper objectMapper; + + @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) + .accept(MediaType.TEXT_HTML) + .acceptCharset(StandardCharsets.UTF_8) + .exchange() + .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); + } + + @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 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"); + } + + 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); + } +} 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 new file mode 100644 index 00000000..2fba7a46 --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxResourcesTestBase.java @@ -0,0 +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; + +public class PlaygroundWebFluxResourcesTestBase { + + @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) + .exchange() + .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); + } +} 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 new file mode 100644 index 00000000..6f695543 --- /dev/null +++ b/playground-spring-boot-autoconfigure/src/test/java/graphql/kickstart/playground/boot/webflux/PlaygroundWebFluxTestConfig.java @@ -0,0 +1,23 @@ +package graphql.kickstart.playground.boot.webflux; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.web.reactive.config.EnableWebFlux; + +@EnableWebFlux +@EnableWebFluxSecurity +@SpringBootApplication +@EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class, SecurityAutoConfiguration.class}) +class PlaygroundWebFluxTestConfig { + + @Bean + public SecurityWebFilterChain securityWebFilterChain(final ServerHttpSecurity http) { + return http.authorizeExchange().anyExchange().permitAll().and().build(); + } +} diff --git a/renovate.json b/renovate.json new file mode 100644 index 00000000..f9b21313 --- /dev/null +++ b/renovate.json @@ -0,0 +1,16 @@ +{ + "extends": [ + "config:base" + ], + "includeForks" : true, + "packageRules": [ + { + "matchPackagePatterns": ["^com.graphql-java"], + "allowedVersions": "/^[0-9]+\\.[0-9]+\\.[0-9]+?$/" + }, + { + "matchPackageNames": ["io.github.graphql-java:graphql-java-annotations"], + "allowedVersions": "/^[0-9]+\\.[0-9]+\\.[0-9]+?$/" + } + ] +} \ No newline at end of file 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/settings.gradle b/settings.gradle index 9b81e8b9..03f5209b 100644 --- a/settings.gradle +++ b/settings.gradle @@ -38,6 +38,8 @@ include ":voyager-spring-boot-starter" include ":playground-spring-boot-autoconfigure" include ":playground-spring-boot-starter" +include ':graphql-spring-boot-dependencies' + include ':graphql-kickstart-spring-boot-autoconfigure-graphql-annotations' include ':graphql-kickstart-spring-boot-starter-graphql-annotations' include ':graphql-kickstart-spring-boot-autoconfigure-tools' 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 9b6b4656..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.26}") - 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/static/vendor/voyager/fetch.min.js b/voyager-spring-boot-autoconfigure/src/main/resources/static/vendor/voyager/fetch.min.js index f16e6af1..78e9c372 100644 --- a/voyager-spring-boot-autoconfigure/src/main/resources/static/vendor/voyager/fetch.min.js +++ b/voyager-spring-boot-autoconfigure/src/main/resources/static/vendor/voyager/fetch.min.js @@ -1 +1 @@ -!function(t){"use strict";if(!t.fetch){var s={searchParams:"URLSearchParams"in t,iterable:"Symbol"in t&&"iterator"in Symbol,blob:"FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in t,arrayBuffer:"ArrayBuffer"in t};if(s.arrayBuffer)var e=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],r=function(t){return t&&DataView.prototype.isPrototypeOf(t)},o=ArrayBuffer.isView||function(t){return t&&-1this.eventPool.length&&this.eventPool.push(a)}function Ne(a){a.eventPool=[];a.getPooled=yh;a.release=zh}function Oe(a,b){switch(a){case "keyup":return-1!==Ah.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "blur":return!0;default:return!1}}function Pe(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}function Bh(a,b){switch(a){case "compositionend":return Pe(b); -case "keypress":if(32!==b.which)return null;Qe=!0;return Re;case "textInput":return a=b.data,a===Re&&Qe?null:a;default:return null}}function Ch(a,b){if(Sa)return"compositionend"===a||!hd&&Oe(a,b)?(a=Me(),hc=gd=qa=null,Sa=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1b}return!1}function K(a,b,c,d,e){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b}function rd(a,b,c,d){var e=A.hasOwnProperty(b)? -A[b]:null;var f=null!==e?0===e.type:d?!1:!(2rc.length&&rc.push(a)}}}function zf(a){Object.prototype.hasOwnProperty.call(a,sc)||(a[sc]=Vh++,Af[a[sc]]= -{});return Af[a[sc]]}function xd(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}function Bf(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function Cf(a,b){var c=Bf(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Bf(c)}}function Df(a,b){return a&&b?a=== -b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Df(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}function Ef(){for(var a=window,b=xd();b instanceof a.HTMLIFrameElement;){try{a=b.contentDocument.defaultView}catch(c){break}b=xd(a.document)}return b}function yd(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b|| -"true"===a.contentEditable)}function Wh(){var a=Ef();if(yd(a)){if("selectionStart"in a)var b={start:a.selectionStart,end:a.selectionEnd};else a:{b=(b=a.ownerDocument)&&b.defaultView||window;var c=b.getSelection&&b.getSelection();if(c&&0!==c.rangeCount){b=c.anchorNode;var d=c.anchorOffset,e=c.focusNode;c=c.focusOffset;try{b.nodeType,e.nodeType}catch(cj){b=null;break a}var f=0,g=-1,h=-1,l=0,k=0,m=a,n=null;b:for(;;){for(var p;;){m!==b||0!==d&&3!==m.nodeType||(g=f+d);m!==e||0!==c&&3!==m.nodeType||(h= -f+c);3===m.nodeType&&(f+=m.nodeValue.length);if(null===(p=m.firstChild))break;n=m;m=p}for(;;){if(m===a)break b;n===b&&++l===d&&(g=f);n===e&&++k===c&&(h=f);if(null!==(p=m.nextSibling))break;m=n;n=m.parentNode}m=p}b=-1===g||-1===h?null:{start:g,end:h}}else b=null}b=b||{start:0,end:0}}else b=null;return{focusedElem:a,selectionRange:b}}function Xh(a){var b=Ef(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Df(c.ownerDocument.documentElement,c)){if(null!==d&&yd(c))if(b=d.start,a=d.end, -void 0===a&&(a=b),"selectionStart"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Cf(c,f);var g=Cf(c,d);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset), -a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});"function"===typeof c.focus&&c.focus();for(c=0;c=b.length?void 0:n("93"),b=b[0]),c=b),null==c&&(c=""));a._wrapperState={initialValue:ua(c)}}function Jf(a,b){var c=ua(b.value),d=ua(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function Kf(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML"; -default:return"http://www.w3.org/1999/xhtml"}}function Dd(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?Kf(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}function Lf(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||yb.hasOwnProperty(a)&&yb[a]?(""+b).trim():b+"px"}function Mf(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=Lf(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c, -e):a[c]=e}}function Ed(a,b){b&&(Zh[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML?n("137",a,""):void 0),null!=b.dangerouslySetInnerHTML&&(null!=b.children?n("60"):void 0,"object"===typeof b.dangerouslySetInnerHTML&&"__html"in b.dangerouslySetInnerHTML?void 0:n("61")),null!=b.style&&"object"!==typeof b.style?n("62",""):void 0)}function Fd(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1; -default:return!0}}function ha(a,b){a=9===a.nodeType||11===a.nodeType?a:a.ownerDocument;var c=zf(a);b=$c[b];for(var d=0;dYa||(a.current= -Id[Ya],Id[Ya]=null,Ya--)}function L(a,b,c){Ya++;Id[Ya]=a.current;a.current=b}function Za(a,b){var c=a.type.contextTypes;if(!c)return va;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function E(a){a=a.childContextTypes;return null!==a&&void 0!==a}function uc(a){D(M,a); -D(F,a)}function Jd(a){D(M,a);D(F,a)}function Qf(a,b,c){F.current!==va?n("168"):void 0;L(F,b,a);L(M,c,a)}function Rf(a,b,c){var d=a.stateNode;a=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)e in a?void 0:n("108",sa(b)||"Unknown",e);return B({},c,d)}function vc(a){var b=a.stateNode;b=b&&b.__reactInternalMemoizedMergedChildContext||va;Fa=F.current;L(F,b,a);L(M,M.current,a);return!0}function Sf(a,b,c){var d=a.stateNode;d?void 0:n("169");c?(b= -Rf(a,b,Fa),d.__reactInternalMemoizedMergedChildContext=b,D(M,a),D(F,a),L(F,b,a)):D(M,a);L(M,c,a)}function Tf(a){return function(b){try{return a(b)}catch(c){}}}function ai(a){if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)return!0;try{var c=b.inject(a);Kd=Tf(function(a){return b.onCommitFiberRoot(c,a)});Ld=Tf(function(a){return b.onCommitFiberUnmount(c,a)})}catch(d){}return!0}function bi(a,b,c,d){this.tag=a;this.key= -c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.contextDependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.effectTag=0;this.lastEffect=this.firstEffect=this.nextEffect=null;this.childExpirationTime=this.expirationTime=0;this.alternate=null}function Md(a){a=a.prototype;return!(!a||!a.isReactComponent)}function ci(a){if("function"===typeof a)return Md(a)?1:0;if(void 0!==a&& -null!==a){a=a.$$typeof;if(a===od)return 11;if(a===pd)return 14}return 2}function Ga(a,b,c){c=a.alternate;null===c?(c=S(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.effectTag=0,c.nextEffect=null,c.firstEffect=null,c.lastEffect=null);c.childExpirationTime=a.childExpirationTime;c.expirationTime=a.expirationTime;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue; -c.contextDependencies=a.contextDependencies;c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}function wc(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)Md(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ta:return wa(c.children,e,f,b);case ld:return Uf(c,e|3,f,b);case md:return Uf(c,e|2,f,b);case lc:return a=S(12,c,b,e|4),a.elementType=lc,a.type=lc,a.expirationTime=f,a;case nd:return a=S(13,c,b,e),b=nd,a.elementType=b,a.type=b,a.expirationTime=f,a;default:if("object"===typeof a&& -null!==a)switch(a.$$typeof){case ff:g=10;break a;case ef:g=9;break a;case od:g=11;break a;case pd:g=14;break a;case gf:g=16;d=null;break a}n("130",null==a?a:typeof a,"")}b=S(g,c,b,e);b.elementType=a;b.type=d;b.expirationTime=f;return b}function wa(a,b,c,d){a=S(7,a,d,b);a.expirationTime=c;return a}function Uf(a,b,c,d){a=S(8,a,d,b);b=0===(b&1)?md:ld;a.elementType=b;a.type=b;a.expirationTime=c;return a}function Nd(a,b,c){a=S(6,a,null,b);a.expirationTime=c;return a}function Od(a,b,c){b=S(4,null!==a.children? -a.children:[],a.key,b);b.expirationTime=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}function Bb(a,b){a.didError=!1;var c=a.earliestPendingTime;0===c?a.earliestPendingTime=a.latestPendingTime=b:cb&&(a.latestPendingTime=b);xc(b,a)}function di(a,b){a.didError=!1;if(0===b)a.earliestPendingTime=0,a.latestPendingTime=0,a.earliestSuspendedTime=0,a.latestSuspendedTime=0,a.latestPingedTime=0;else{b< -a.latestPingedTime&&(a.latestPingedTime=0);var c=a.latestPendingTime;0!==c&&(c>b?a.earliestPendingTime=a.latestPendingTime=0:a.earliestPendingTime>b&&(a.earliestPendingTime=a.latestPendingTime));c=a.earliestSuspendedTime;0===c?Bb(a,b):bc&&Bb(a,b)}xc(0,a)}function Vf(a,b){a.didError=!1;a.latestPingedTime>=b&&(a.latestPingedTime=0);var c=a.earliestPendingTime,d=a.latestPendingTime;c===b?a.earliestPendingTime= -d===b?a.latestPendingTime=0:d:d===b&&(a.latestPendingTime=c);c=a.earliestSuspendedTime;d=a.latestSuspendedTime;0===c?a.earliestSuspendedTime=a.latestSuspendedTime=b:cb&&(a.latestSuspendedTime=b);xc(b,a)}function Wf(a,b){var c=a.earliestPendingTime;a=a.earliestSuspendedTime;c>b&&(b=c);a>b&&(b=a);return b}function xc(a,b){var c=b.earliestSuspendedTime,d=b.latestSuspendedTime,e=b.earliestPendingTime,f=b.latestPingedTime;e=0!==e?e:f;0===e&&(0===a||da&&(a=c);b.nextExpirationTimeToWorkOn=e;b.expirationTime=a}function P(a,b){if(a&&a.defaultProps){b=B({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c])}return b}function ei(a){var b=a._result;switch(a._status){case 1:return b;case 2:throw b;case 0:throw b;default:a._status=0;b=a._ctor;b=b();b.then(function(b){0===a._status&&(b=b.default,a._status=1,a._result=b)},function(b){0===a._status&&(a._status=2,a._result=b)});switch(a._status){case 1:return a._result;case 2:throw a._result; -}a._result=b;throw b;}}function yc(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:B({},b,c);a.memoizedState=c;d=a.updateQueue;null!==d&&0===a.expirationTime&&(d.baseState=c)}function Xf(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!vb(c,d)||!vb(e,f):!0}function Yf(a,b,c,d){var e=!1;d=va;var f=b.contextType;"object"===typeof f&&null!==f?f=T(f):(d=E(b)?Fa:F.current,e=b.contextTypes, -f=(e=null!==e&&void 0!==e)?Za(a,d):va);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=zc;a.stateNode=b;b._reactInternalFiber=a;e&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=d,a.__reactInternalMemoizedMaskedChildContext=f);return b}function Zf(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!== -a&&zc.enqueueReplaceState(b,b.state,null)}function Pd(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs=$f;var f=b.contextType;"object"===typeof f&&null!==f?e.context=T(f):(f=E(b)?Fa:F.current,e.context=Za(a,f));f=a.updateQueue;null!==f&&(Cb(a,f,c,e,d),e.state=a.memoizedState);f=b.getDerivedStateFromProps;"function"===typeof f&&(yc(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&& -"function"!==typeof e.componentWillMount||(b=e.state,"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&zc.enqueueReplaceState(e,e.state,null),f=a.updateQueue,null!==f&&(Cb(a,f,c,e,d),e.state=a.memoizedState));"function"===typeof e.componentDidMount&&(a.effectTag|=4)}function Db(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;var d=void 0;c&&(1!== -c.tag?n("309"):void 0,d=c.stateNode);d?void 0:n("147",a);var e=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===e)return b.ref;b=function(a){var b=d.refs;b===$f&&(b=d.refs={});null===a?delete b[e]:b[e]=a};b._stringRef=e;return b}"string"!==typeof a?n("284"):void 0;c._owner?void 0:n("290",a)}return a}function Ac(a,b){"textarea"!==a.type&&n("31","[object Object]"===Object.prototype.toString.call(b)?"object with keys {"+Object.keys(b).join(", ")+"}":b,"")}function ag(a){function b(b, -c){if(a){var d=b.lastEffect;null!==d?(d.nextEffect=c,b.lastEffect=c):b.firstEffect=b.lastEffect=c;c.nextEffect=null;c.effectTag=8}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b,c){a=Ga(a,b,c);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return c;d=b.alternate;if(null!==d)return d=d.index,dq?(v=n,n=null):v=n.sibling;var Q=p(e,n,h[q],k);if(null===Q){null===n&&(n=v);break}a&& -n&&null===Q.alternate&&b(e,n);g=f(Q,g,q);null===m?l=Q:m.sibling=Q;m=Q;n=v}if(q===h.length)return c(e,n),l;if(null===n){for(;qv?(Q=q,q=null):Q=q.sibling;var u=p(e,q,t.value,k);if(null===u){q||(q=Q);break}a&&q&&null===u.alternate&&b(e,q);g=f(u,g,v);null===m?l=u:m.sibling=u;m=u;q=Q}if(t.done)return c(e,q),l;if(null===q){for(;!t.done;v++,t=h.next())t=Ff(e,t.value,k),null!==t&&(g=f(t,g,v),null===m?l=t:m.sibling=t,m=t);return l}for(q=d(e,q);!t.done;v++,t=h.next())t=r(q,e,v,t.value,k),null!==t&&(a&&null!==t.alternate&&q.delete(null===t.key? -v:t.key),g=f(t,g,v),null===m?l=t:m.sibling=t,m=t);a&&q.forEach(function(a){return b(e,a)});return l}return function(a,d,f,h){var k="object"===typeof f&&null!==f&&f.type===ta&&null===f.key;k&&(f=f.props.children);var l="object"===typeof f&&null!==f;if(l)switch(f.$$typeof){case Bc:a:{l=f.key;for(k=d;null!==k;){if(k.key===l)if(7===k.tag?f.type===ta:k.elementType===f.type){c(a,k.sibling);d=e(k,f.type===ta?f.props.children:f.props,h);d.ref=Db(a,k,f);d.return=a;a=d;break a}else{c(a,k);break}else b(a,k); -k=k.sibling}f.type===ta?(d=wa(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=wc(f.type,f.key,f.props,null,a.mode,h),h.ref=Db(a,d,f),h.return=a,a=h)}return g(a);case Va:a:{for(k=f.key;null!==d;){if(d.key===k)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[],h);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=Od(f,a.mode,h);d.return=a;a=d}return g(a)}if("string"===typeof f||"number"=== -typeof f)return f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f,h),d.return=a,a=d):(c(a,d),d=Nd(f,a.mode,h),d.return=a,a=d),g(a);if(Cc(f))return u(a,d,f,h);if(sb(f))return x(a,d,f,h);l&&Ac(a,f);if("undefined"===typeof f&&!k)switch(a.tag){case 1:case 0:h=a.type,n("152",h.displayName||h.name||"Component")}return c(a,d)}}function Ha(a){a===Eb?n("174"):void 0;return a}function Qd(a,b){L(Fb,b,a);L(Gb,a,a);L(U,Eb,a);var c=b.nodeType;switch(c){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:Dd(null, -"");break;default:c=8===c?b.parentNode:b,b=c.namespaceURI||null,c=c.tagName,b=Dd(b,c)}D(U,a);L(U,b,a)}function $a(a){D(U,a);D(Gb,a);D(Fb,a)}function bg(a){Ha(Fb.current);var b=Ha(U.current);var c=Dd(b,a.type);b!==c&&(L(Gb,a,a),L(U,c,a))}function Rd(a){Gb.current===a&&(D(U,a),D(Gb,a))}function V(){n("307")}function Sd(a,b){if(null===b)return!1;for(var c=0;cKb&&(Kb=m)):f=l.eagerReducer===a?l.eagerState:a(f,l.action);g=l;l=l.next}while(null!==l&&l!==d);k||(h= -g,e=f);Ea(f,b.memoizedState)||(ja=!0);b.memoizedState=f;b.baseUpdate=h;b.baseState=e;c.eagerReducer=a;c.eagerState=f}return[b.memoizedState,c.dispatch]}function Wd(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};null===X?(X={lastEffect:null},X.lastEffect=a.next=a):(b=X.lastEffect,null===b?X.lastEffect=a.next=a:(c=b.next,b.next=a,a.next=c,X.lastEffect=a));return a}function Xd(a,b,c,d){var e=cb();Lb|=a;e.memoizedState=Wd(b,c,void 0,void 0===d?null:d)}function Yd(a,b,c,d){var e=Mb();d=void 0=== -d?null:d;var f=void 0;if(null!==y){var g=y.memoizedState;f=g.destroy;if(null!==d&&Sd(d,g.deps)){Wd(db,c,f,d);return}}Lb|=a;e.memoizedState=Wd(b,c,f,d)}function fg(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function gg(a,b){}function hg(a,b,c){25>Jb?void 0:n("301");var d=a.alternate;if(a===xa||null!==d&&d===xa)if(Ib=!0,a={expirationTime:Hb,action:c,eagerReducer:null,eagerState:null,next:null},null=== -ia&&(ia=new Map),c=ia.get(b),void 0===c)ia.set(b,a);else{for(b=c;null!==b.next;)b=b.next;b.next=a}else{eb();var e=ka();e=fb(e,a);var f={expirationTime:e,action:c,eagerReducer:null,eagerState:null,next:null},g=b.last;if(null===g)f.next=f;else{var h=g.next;null!==h&&(f.next=h);g.next=f}b.last=f;if(0===a.expirationTime&&(null===d||0===d.expirationTime)&&(d=b.eagerReducer,null!==d))try{var l=b.eagerState,k=d(l,c);f.eagerReducer=d;f.eagerState=k;if(Ea(k,l))return}catch(m){}finally{}ya(a,e)}}function ig(a, -b){var c=S(5,null,null,0);c.elementType="DELETED";c.type="DELETED";c.stateNode=b;c.return=a;c.effectTag=8;null!==a.lastEffect?(a.lastEffect.nextEffect=c,a.lastEffect=c):a.firstEffect=a.lastEffect=c}function jg(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,!0):!1;case 13:return!1;default:return!1}}function kg(a){if(Ia){var b= -gb;if(b){var c=b;if(!jg(a,b)){b=Hd(c);if(!b||!jg(a,b)){a.effectTag|=2;Ia=!1;la=a;return}ig(la,c)}la=a;gb=Pf(b)}else a.effectTag|=2,Ia=!1,la=a}}function lg(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&18!==a.tag;)a=a.return;la=a}function Zd(a){if(a!==la)return!1;if(!Ia)return lg(a),Ia=!0,!1;var b=a.type;if(5!==a.tag||"head"!==b&&"body"!==b&&!Gd(b,a.memoizedProps))for(b=gb;b;)ig(a,b),b=Hd(b);lg(a);gb=la?Hd(a.stateNode):null;return!0}function $d(){gb=la=null;Ia=!1}function N(a,b,c,d){b.child=null=== -a?ae(b,null,c,d):hb(b,a.child,c,d)}function mg(a,b,c,d,e){c=c.render;var f=b.ref;ib(b,e);d=Td(a,b,c,d,f,e);if(null!==a&&!ja)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),ma(a,b,e);b.effectTag|=1;N(a,b,d,e);return b.child}function ng(a,b,c,d,e,f){if(null===a){var g=c.type;if("function"===typeof g&&!Md(g)&&void 0===g.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=g,og(a,b,g,d,e,f);a=wc(c.type,null,d,null,b.mode,f);a.ref= -b.ref;a.return=b;return b.child=a}g=a.child;if(e=c)return sg(a,b,c);b=ma(a,b,c);return null!==b?b.sibling:null}}return ma(a,b,c)}}else ja=!1;b.expirationTime=0;switch(b.tag){case 2:d=b.elementType;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;var e=Za(b,F.current);ib(b,c);e=Td(null,b,d,a,e,c);b.effectTag|=1;if("object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof){b.tag= -1;Vd();if(E(d)){var f=!0;vc(b)}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;var g=d.getDerivedStateFromProps;"function"===typeof g&&yc(b,d,g,a);e.updater=zc;b.stateNode=e;e._reactInternalFiber=b;Pd(b,d,a,c);b=ce(null,b,d,!0,f,c)}else b.tag=0,N(null,b,e,c),b=b.child;return b;case 16:e=b.elementType;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);f=b.pendingProps;a=ei(e);b.type=a;e=b.tag=ci(a);f=P(a,f);g=void 0;switch(e){case 0:g=be(null,b,a,f,c);break;case 1:g= -qg(null,b,a,f,c);break;case 11:g=mg(null,b,a,f,c);break;case 14:g=ng(null,b,a,P(a.type,f),d,c);break;default:n("306",a,"")}return g;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:P(d,e),be(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:P(d,e),qg(a,b,d,e,c);case 3:rg(b);d=b.updateQueue;null===d?n("282"):void 0;e=b.memoizedState;e=null!==e?e.element:null;Cb(b,d,b.pendingProps,null,c);d=b.memoizedState.element;if(d===e)$d(),b=ma(a,b,c);else{e=b.stateNode;if(e= -(null===a||null===a.child)&&e.hydrate)gb=Pf(b.stateNode.containerInfo),la=b,e=Ia=!0;e?(b.effectTag|=2,b.child=ae(b,null,d,c)):(N(a,b,d,c),$d());b=b.child}return b;case 5:return bg(b),null===a&&kg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Gd(d,e)?g=null:null!==f&&Gd(d,f)&&(b.effectTag|=16),pg(a,b),1!==c&&b.mode&1&&e.hidden?(b.expirationTime=b.childExpirationTime=1,b=null):(N(a,b,g,c),b=b.child),b;case 6:return null===a&&kg(b),null;case 13:return sg(a,b,c);case 4:return Qd(b, -b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=hb(b,null,d,c):N(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:P(d,e),mg(a,b,d,e,c);case 7:return N(a,b,b.pendingProps,c),b.child;case 8:return N(a,b,b.pendingProps.children,c),b.child;case 12:return N(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;g=b.memoizedProps;f=e.value;tg(b,f);if(null!==g){var h=g.value;f=Ea(h,f)?0:("function"===typeof d._calculateChangedBits? -d._calculateChangedBits(h,f):1073741823)|0;if(0===f){if(g.children===e.children&&!M.current){b=ma(a,b,c);break a}}else for(h=b.child,null!==h&&(h.return=b);null!==h;){var l=h.contextDependencies;if(null!==l){g=h.child;for(var k=l.first;null!==k;){if(k.context===d&&0!==(k.observedBits&f)){1===h.tag&&(k=Aa(c),k.tag=Ec,na(h,k));h.expirationTime=b&&(ja=!0);a.contextDependencies=null}function T(a,b){if(Ob!==a&&!1!==b&&0!==b){if("number"!==typeof b||1073741823===b)Ob=a,b=1073741823;b={context:a,observedBits:b,next:null};null===Ja?(null===Nb?n("308"):void 0,Ja=b,Nb.contextDependencies={first:b,expirationTime:0}):Ja=Ja.next=b}return a._currentValue}function Fc(a){return{baseState:a, -firstUpdate:null,lastUpdate:null,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function fe(a){return{baseState:a.baseState,firstUpdate:a.firstUpdate,lastUpdate:a.lastUpdate,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Aa(a){return{expirationTime:a,tag:ug,payload:null,callback:null,next:null,nextEffect:null}}function Gc(a, -b){null===a.lastUpdate?a.firstUpdate=a.lastUpdate=b:(a.lastUpdate.next=b,a.lastUpdate=b)}function na(a,b){var c=a.alternate;if(null===c){var d=a.updateQueue;var e=null;null===d&&(d=a.updateQueue=Fc(a.memoizedState))}else d=a.updateQueue,e=c.updateQueue,null===d?null===e?(d=a.updateQueue=Fc(a.memoizedState),e=c.updateQueue=Fc(c.memoizedState)):d=a.updateQueue=fe(e):null===e&&(e=c.updateQueue=fe(d));null===e||d===e?Gc(d,b):null===d.lastUpdate||null===e.lastUpdate?(Gc(d,b),Gc(e,b)):(Gc(d,b),e.lastUpdate= -b)}function vg(a,b){var c=a.updateQueue;c=null===c?a.updateQueue=Fc(a.memoizedState):wg(a,c);null===c.lastCapturedUpdate?c.firstCapturedUpdate=c.lastCapturedUpdate=b:(c.lastCapturedUpdate.next=b,c.lastCapturedUpdate=b)}function wg(a,b){var c=a.alternate;null!==c&&b===c.updateQueue&&(b=a.updateQueue=fe(b));return b}function xg(a,b,c,d,e,f){switch(c.tag){case yg:return a=c.payload,"function"===typeof a?a.call(f,d,e):a;case ge:a.effectTag=a.effectTag&-2049|64;case ug:a=c.payload;e="function"===typeof a? -a.call(f,d,e):a;if(null===e||void 0===e)break;return B({},d,e);case Ec:za=!0}return d}function Cb(a,b,c,d,e){za=!1;b=wg(a,b);for(var f=b.baseState,g=null,h=0,l=b.firstUpdate,k=f;null!==l;){var m=l.expirationTime;md?e:d);Kg.current=null;d=void 0;1c?b:c;0===b&&(Ba=null);wi(a,b)}function Mg(a){for(;;){var b=a.alternate,c=a.return,d=a.sibling;if(0===(a.effectTag&1024)){x=a;a:{var e=b;b=a;var f=H;var g=b.pendingProps;switch(b.tag){case 2:break;case 16:break;case 15:case 0:break;case 1:E(b.type)&&uc(b);break;case 3:$a(b);Jd(b);g=b.stateNode;g.pendingContext&&(g.context=g.pendingContext,g.pendingContext=null);if(null===e||null===e.child)Zd(b),b.effectTag&= --3;pe(b);break;case 5:Rd(b);var h=Ha(Fb.current);f=b.type;if(null!==e&&null!=b.stateNode)Ng(e,b,f,g,h),e.ref!==b.ref&&(b.effectTag|=128);else if(g){var l=Ha(U.current);if(Zd(b)){g=b;e=g.stateNode;var k=g.type,m=g.memoizedProps,p=h;e[ea]=g;e[ec]=m;f=void 0;h=k;switch(h){case "iframe":case "object":r("load",e);break;case "video":case "audio":for(k=0;k\x3c/script>",k=e.removeChild(e.firstChild)): -"string"===typeof p.is?k=k.createElement(e,{is:p.is}):(k=k.createElement(e),"select"===e&&p.multiple&&(k.multiple=!0)):k=k.createElementNS(l,e);e=k;e[ea]=m;e[ec]=g;Og(e,b,!1,!1);m=e;k=f;p=g;var t=h,y=Fd(k,p);switch(k){case "iframe":case "object":r("load",m);h=p;break;case "video":case "audio":for(h=0;hg&&(g=e),h>g&&(g=h),f=f.sibling;b.childExpirationTime=g}if(null!==x)return x;null!==c&&0===(c.effectTag&1024)&&(null===c.firstEffect&&(c.firstEffect=a.firstEffect),null!==a.lastEffect&&(null!==c.lastEffect&&(c.lastEffect.nextEffect=a.firstEffect),c.lastEffect=a.lastEffect),1=u)t=0;else if(-1===t||u component higher in the tree to provide a loading indicator or placeholder to display."+qd(k))}je=!0;m=Hc(m,k);h= -l;do{switch(h.tag){case 3:h.effectTag|=2048;h.expirationTime=g;g=he(h,m,g);vg(h,g);break a;case 1:if(t=m,r=h.type,k=h.stateNode,0===(h.effectTag&64)&&("function"===typeof r.getDerivedStateFromError||null!==k&&"function"===typeof k.componentDidCatch&&(null===Ba||!Ba.has(k)))){h.effectTag|=2048;h.expirationTime=g;g=Ig(h,t,g);vg(h,g);break a}}h=h.return}while(null!==h)}x=Mg(f);continue}}}break}while(1);Ca=!1;qe.current=c;Ob=Ja=Nb=null;Vd();if(e)Y=null,a.finishedWork=null;else if(null!==x)a.finishedWork= -null;else{c=a.current.alternate;null===c?n("281"):void 0;Y=null;if(je){e=a.latestPendingTime;f=a.latestSuspendedTime;g=a.latestPingedTime;if(0!==e&&eb?0:b)):(a.pendingCommitExpirationTime=d,a.finishedWork= -c)}}function Ka(a,b){for(var c=a.return;null!==c;){switch(c.tag){case 1:var d=c.stateNode;if("function"===typeof c.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===Ba||!Ba.has(d))){a=Hc(b,a);a=Ig(c,a,1073741823);na(c,a);ya(c,1073741823);return}break;case 3:a=Hc(b,a);a=he(c,a,1073741823);na(c,a);ya(c,1073741823);return}c=c.return}3===a.tag&&(c=Hc(b,a),c=he(a,c,1073741823),na(a,c),ya(a,1073741823))}function fb(a,b){var c=zi(),d=void 0;if(0===(b.mode&1))d=1073741823;else if(Ca&& -!Lc)d=H;else{switch(c){case se:d=1073741823;break;case te:d=1073741822-10*(((1073741822-a+15)/10|0)+1);break;case Lg:d=1073741822-25*(((1073741822-a+500)/25|0)+1);break;case Ai:case Bi:d=1;break;default:n("313")}null!==Y&&d===H&&--d}c===te&&(0===oa||d=d){a.didError=!1;b=a.latestPingedTime;if(0===b||b>c)a.latestPingedTime= -c;xc(c,a);c=a.expirationTime;0!==c&&Kc(a,c)}}function li(a,b){var c=a.stateNode;null!==c&&c.delete(b);b=ka();b=fb(b,a);a=Sg(a,b);null!==a&&(Bb(a,b),b=a.expirationTime,0!==b&&Kc(a,b))}function Sg(a,b){a.expirationTimeH&&Jg(),Bb(a,b),Ca&&!Lc&&Y===a||Kc(a,a.expirationTime),Tb>Ci&&(Tb=0,n("185")))}function Tg(a,b,c,d,e){return Mc(se,function(){return a(b,c,d,e)})}function Ub(){aa=1073741822-((ue()-ve)/10|0)}function Ug(a,b){if(0!==Oc){if(ba.expirationTime&&(a.expirationTime=b);w||(z?Rc&&(ca= -a,C=1073741823,Sc(a,1073741823,!1)):1073741823===b?Z(1073741823,!1):Ug(a,b))}function Qc(){var a=0,b=null;if(null!==I)for(var c=I,d=ba;null!==d;){var e=d.expirationTime;if(0===e){null===c||null===I?n("244"):void 0;if(d===d.nextScheduledRoot){ba=I=d.nextScheduledRoot=null;break}else if(d===ba)ba=e=d.nextScheduledRoot,I.nextScheduledRoot=e,d.nextScheduledRoot=null;else if(d===I){I=c;I.nextScheduledRoot=ba;d.nextScheduledRoot=null;break}else c.nextScheduledRoot=d.nextScheduledRoot,d.nextScheduledRoot= -null;d=c.nextScheduledRoot}else{e>a&&(a=e,b=d);if(d===I)break;if(1073741823===a)break;c=d;d=d.nextScheduledRoot}}ca=b;C=a}function Nc(){return Tc?!0:Gi()?Tc=!0:!1}function Di(){try{if(!Nc()&&null!==ba){Ub();var a=ba;do{var b=a.expirationTime;0!==b&&aa<=b&&(a.nextExpirationTimeToWorkOn=aa);a=a.nextScheduledRoot}while(a!==ba)}Z(0,!0)}finally{Tc=!1}}function Z(a,b){Qc();if(b)for(Ub(),jb=aa;null!==ca&&0!==C&&a<=C&&!(Tc&&aa>C);)Sc(ca,C,aa>C),Qc(),Ub(),jb=aa;else for(;null!==ca&&0!==C&&a<=C;)Sc(ca,C,!1), -Qc();b&&(Oc=0,Pc=null);0!==C&&Ug(ca,C);Tb=0;we=null;if(null!==kb)for(a=kb,kb=null,b=0;b=c&&(null===kb?kb=[d]:kb.push(d),d._defer)){a.finishedWork=b;a.expirationTime=0;return}a.finishedWork=null;a===we?Tb++:(we=a,Tb=0);Mc(se,function(){ui(a,b)})}function ie(a){null===ca?n("246"):void 0;ca.expirationTime=0;lb||(lb=!0,Uc=a)}function Zg(a,b){var c=z;z=!0;try{return a(b)}finally{(z= -c)||w||Z(1073741823,!1)}}function $g(a,b){if(z&&!Rc){Rc=!0;try{return a(b)}finally{Rc=!1}}return a(b)}function ah(a,b,c){z||w||0===oa||(Z(oa,!1),oa=0);var d=z;z=!0;try{return Mc(te,function(){return a(b,c)})}finally{(z=d)||w||Z(1073741823,!1)}}function bh(a,b,c,d,e){var f=b.current;a:if(c){c=c._reactInternalFiber;b:{2===wb(c)&&1===c.tag?void 0:n("170");var g=c;do{switch(g.tag){case 3:g=g.stateNode.context;break b;case 1:if(E(g.type)){g=g.stateNode.__reactInternalMemoizedMergedChildContext;break b}}g= -g.return}while(null!==g);n("171");g=void 0}if(1===c.tag){var h=c.type;if(E(h)){c=Rf(c,h,g);break a}}c=g}else c=va;null===b.context?b.context=c:b.pendingContext=c;b=e;e=Aa(d);e.payload={element:a};b=void 0===b?null:b;null!==b&&(e.callback=b);eb();na(f,e);ya(f,d);return d}function xe(a,b,c,d){var e=b.current,f=ka();e=fb(f,e);return bh(a,b,c,e,d)}function ye(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function Hi(a,b,c){var d= -3=ze&&(b=ze-1);this._expirationTime=ze=b;this._root=a;this._callbacks=this._next=null;this._hasChildren=this._didComplete=!1;this._children=null;this._defer=!0}function mb(){this._callbacks=null;this._didCommit=!1;this._onCommit=this._onCommit.bind(this)}function nb(a,b,c){b=S(3,null,null, -b?3:0);a={current:b,containerInfo:a,pendingChildren:null,pingCache:null,earliestPendingTime:0,latestPendingTime:0,earliestSuspendedTime:0,latestSuspendedTime:0,latestPingedTime:0,didError:!1,pendingCommitExpirationTime:0,finishedWork:null,timeoutHandle:-1,context:null,pendingContext:null,hydrate:c,nextExpirationTimeToWorkOn:0,expirationTime:0,firstBatch:null,nextScheduledRoot:null};this._internalRoot=b.stateNode=a}function ob(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType|| -" react-mount-point-unstable "!==a.nodeValue))}function Ii(a,b){b||(b=a?9===a.nodeType?a.documentElement:a.firstChild:null,b=!(!b||1!==b.nodeType||!b.hasAttribute("data-reactroot")));if(!b)for(var c;c=a.lastChild;)a.removeChild(c);return new nb(a,!1,b)}function Wc(a,b,c,d,e){var f=c._reactRootContainer;if(f){if("function"===typeof e){var g=e;e=function(){var a=ye(f._internalRoot);g.call(a)}}null!=a?f.legacy_renderSubtreeIntoContainer(a,b,e):f.render(b,e)}else{f=c._reactRootContainer=Ii(c,d);if("function"=== -typeof e){var h=e;e=function(){var a=ye(f._internalRoot);h.call(a)}}$g(function(){null!=a?f.legacy_renderSubtreeIntoContainer(a,b,e):f.render(b,e)})}return ye(f._internalRoot)}function ch(a,b){var c=2=Wb),Re=String.fromCharCode(32),pa={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput", -captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate", -captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},Qe=!1,Sa=!1,Mi={eventTypes:pa,extractEvents:function(a,b,c,d){var e=void 0;var f=void 0;if(hd)b:{switch(a){case "compositionstart":e=pa.compositionStart;break b;case "compositionend":e=pa.compositionEnd;break b;case "compositionupdate":e=pa.compositionUpdate;break b}e=void 0}else Sa?Oe(a,c)&&(e=pa.compositionEnd):"keydown"===a&&229===c.keyCode&&(e=pa.compositionStart);e?(Se&& -"ko"!==c.locale&&(Sa||e!==pa.compositionStart?e===pa.compositionEnd&&Sa&&(f=Me()):(qa=d,gd="value"in qa?qa.value:qa.textContent,Sa=!0)),e=Ji.getPooled(e,b,c,d),f?e.data=f:(f=Pe(c),null!==f&&(e.data=f)),Qa(e),f=e):f=null;(a=Li?Bh(a,c):Ch(a,c))?(b=Ki.getPooled(pa.beforeInput,b,c,d),b.data=a,Qa(b)):b=null;return null===f?b:null===b?f:[f,b]}},id=null,Ta=null,Ua=null,Ye=function(a,b){return a(b)},yf=function(a,b,c){return a(b,c)},Ze=function(){},jd=!1,Dh={color:!0,date:!0,datetime:!0,"datetime-local":!0, -email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0},Ma=da.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;Ma.hasOwnProperty("ReactCurrentDispatcher")||(Ma.ReactCurrentDispatcher={current:null});var Fh=/^(.*)[\\\/]/,O="function"===typeof Symbol&&Symbol.for,Bc=O?Symbol.for("react.element"):60103,Va=O?Symbol.for("react.portal"):60106,ta=O?Symbol.for("react.fragment"):60107,md=O?Symbol.for("react.strict_mode"):60108,lc=O?Symbol.for("react.profiler"):60114, -ff=O?Symbol.for("react.provider"):60109,ef=O?Symbol.for("react.context"):60110,ld=O?Symbol.for("react.concurrent_mode"):60111,od=O?Symbol.for("react.forward_ref"):60112,nd=O?Symbol.for("react.suspense"):60113,pd=O?Symbol.for("react.memo"):60115,gf=O?Symbol.for("react.lazy"):60116,df="function"===typeof Symbol&&Symbol.iterator,Hh=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, -hf=Object.prototype.hasOwnProperty,kf={},jf={},A={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){A[a]=new K(a,0,!1,a,null)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];A[b]=new K(b,1,!1,a[1],null)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){A[a]=new K(a,2,!1, -a.toLowerCase(),null)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){A[a]=new K(a,2,!1,a,null)});"allowFullScreen async autoFocus autoPlay controls default defer disabled formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){A[a]=new K(a,3,!1,a.toLowerCase(),null)});["checked","multiple","muted","selected"].forEach(function(a){A[a]=new K(a,3,!0,a,null)});["capture", -"download"].forEach(function(a){A[a]=new K(a,4,!1,a,null)});["cols","rows","size","span"].forEach(function(a){A[a]=new K(a,6,!1,a,null)});["rowSpan","start"].forEach(function(a){A[a]=new K(a,5,!1,a.toLowerCase(),null)});var Be=/[\-:]([a-z])/g,Ce=function(a){return a[1].toUpperCase()};"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b= -a.replace(Be,Ce);A[b]=new K(b,1,!1,a,null)});"xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(Be,Ce);A[b]=new K(b,1,!1,a,"http://www.w3.org/1999/xlink")});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(Be,Ce);A[b]=new K(b,1,!1,a,"http://www.w3.org/XML/1998/namespace")});["tabIndex","crossOrigin"].forEach(function(a){A[a]=new K(a,1,!1,a.toLowerCase(),null)});var pf={change:{phasedRegistrationNames:{bubbled:"onChange", -captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}},tb=null,ub=null,De=!1;ra&&(De=af("input")&&(!document.documentMode||9=document.documentMode,Hf={select:{phasedRegistrationNames:{bubbled:"onSelect", -captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},Wa=null,Ad=null,xb=null,zd=!1,aj={eventTypes:Hf,extractEvents:function(a,b,c,d){var e=d.window===d?d.document:9===d.nodeType?d:d.ownerDocument,f;if(!(f=!e)){a:{e=zf(e);f=$c.onSelect;for(var g=0;g"+b+"";for(b=Xc.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}}), -Ab=function(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b},yb={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0, -lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},bj=["Webkit","ms","Moz","O"];Object.keys(yb).forEach(function(a){bj.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);yb[b]=yb[a]})});var Zh=B({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0, -source:!0,track:!0,wbr:!0}),R=da.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Scheduler,Vg=R.unstable_cancelCallback,ue=R.unstable_now,Wg=R.unstable_scheduleCallback,Gi=R.unstable_shouldYield,Mc=R.unstable_runWithPriority,zi=R.unstable_getCurrentPriorityLevel,se=R.unstable_ImmediatePriority,te=R.unstable_UserBlockingPriority,Lg=R.unstable_NormalPriority,Ai=R.unstable_LowPriority,Bi=R.unstable_IdlePriority,ne=null,oe=null,Ei="function"===typeof setTimeout?setTimeout:void 0,Yg="function"===typeof clearTimeout? -clearTimeout:void 0,vi=Wg,ti=Vg;new Set;var Id=[],Ya=-1,va={},F={current:va},M={current:!1},Fa=va,Kd=null,Ld=null,S=function(a,b,c,d){return new bi(a,b,c,d)},$f=(new da.Component).refs,zc={isMounted:function(a){return(a=a._reactInternalFiber)?2===wb(a):!1},enqueueSetState:function(a,b,c){a=a._reactInternalFiber;var d=ka();d=fb(d,a);var e=Aa(d);e.payload=b;void 0!==c&&null!==c&&(e.callback=c);eb();na(a,e);ya(a,d)},enqueueReplaceState:function(a,b,c){a=a._reactInternalFiber;var d=ka();d=fb(d,a);var e= -Aa(d);e.tag=yg;e.payload=b;void 0!==c&&null!==c&&(e.callback=c);eb();na(a,e);ya(a,d)},enqueueForceUpdate:function(a,b){a=a._reactInternalFiber;var c=ka();c=fb(c,a);var d=Aa(c);d.tag=Ec;void 0!==b&&null!==b&&(d.callback=b);eb();na(a,d);ya(a,c)}},Cc=Array.isArray,hb=ag(!0),ae=ag(!1),Eb={},U={current:Eb},Gb={current:Eb},Fb={current:Eb},db=0,pi=2,Rb=4,ji=8,ri=16,Sb=32,me=64,le=128,Dc=Ma.ReactCurrentDispatcher,Hb=0,xa=null,y=null,W=null,bb=null,G=null,ab=null,Kb=0,X=null,Lb=0,Ib=!1,ia=null,Jb=0,Ud={readContext:T, -useCallback:V,useContext:V,useEffect:V,useImperativeHandle:V,useLayoutEffect:V,useMemo:V,useReducer:V,useRef:V,useState:V,useDebugValue:V},fi={readContext:T,useCallback:function(a,b){cb().memoizedState=[a,void 0===b?null:b];return a},useContext:T,useEffect:function(a,b){return Xd(516,le|me,a,b)},useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Xd(4,Rb|Sb,fg.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Xd(4,Rb|Sb,a,b)},useMemo:function(a,b){var c=cb(); -b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=cb();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a=d.queue={last:null,dispatch:null,eagerReducer:a,eagerState:b};a=a.dispatch=hg.bind(null,xa,a);return[d.memoizedState,a]},useRef:function(a){var b=cb();a={current:a};return b.memoizedState=a},useState:function(a){var b=cb();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={last:null,dispatch:null,eagerReducer:dg,eagerState:a};a=a.dispatch= -hg.bind(null,xa,a);return[b.memoizedState,a]},useDebugValue:gg},cg={readContext:T,useCallback:function(a,b){var c=Mb();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Sd(b,d[1]))return d[0];c.memoizedState=[a,b];return a},useContext:T,useEffect:function(a,b){return Yd(516,le|me,a,b)},useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Yd(4,Rb|Sb,fg.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Yd(4,Rb|Sb,a,b)},useMemo:function(a,b){var c= -Mb();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&Sd(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a},useReducer:eg,useRef:function(a){return Mb().memoizedState},useState:function(a){return eg(dg,a)},useDebugValue:gg},la=null,gb=null,Ia=!1,gi=Ma.ReactCurrentOwner,ja=!1,de={current:null},Nb=null,Ja=null,Ob=null,ug=0,yg=1,Ec=2,ge=3,za=!1,Og=void 0,pe=void 0,Ng=void 0,Pg=void 0;Og=function(a,b,c,d){for(c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode); -else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};pe=function(a){};Ng=function(a,b,c,d,e){var f=a.memoizedProps;if(f!==d){var g=b.stateNode;Ha(U.current);a=null;switch(c){case "input":f=sd(g,f);d=sd(g,d);a=[];break;case "option":f=Bd(g,f);d=Bd(g,d);a=[];break;case "select":f=B({},f,{value:void 0});d=B({},d,{value:void 0});a=[];break;case "textarea":f= -Cd(g,f);d=Cd(g,d);a=[];break;default:"function"!==typeof f.onClick&&"function"===typeof d.onClick&&(g.onclick=tc)}Ed(c,d);g=c=void 0;var h=null;for(c in f)if(!d.hasOwnProperty(c)&&f.hasOwnProperty(c)&&null!=f[c])if("style"===c){var l=f[c];for(g in l)l.hasOwnProperty(g)&&(h||(h={}),h[g]="")}else"dangerouslySetInnerHTML"!==c&&"children"!==c&&"suppressContentEditableWarning"!==c&&"suppressHydrationWarning"!==c&&"autoFocus"!==c&&(Oa.hasOwnProperty(c)?a||(a=[]):(a=a||[]).push(c,null));for(c in d){var k= -d[c];l=null!=f?f[c]:void 0;if(d.hasOwnProperty(c)&&k!==l&&(null!=k||null!=l))if("style"===c)if(l){for(g in l)!l.hasOwnProperty(g)||k&&k.hasOwnProperty(g)||(h||(h={}),h[g]="");for(g in k)k.hasOwnProperty(g)&&l[g]!==k[g]&&(h||(h={}),h[g]=k[g])}else h||(a||(a=[]),a.push(c,h)),h=k;else"dangerouslySetInnerHTML"===c?(k=k?k.__html:void 0,l=l?l.__html:void 0,null!=k&&l!==k&&(a=a||[]).push(c,""+k)):"children"===c?l===k||"string"!==typeof k&&"number"!==typeof k||(a=a||[]).push(c,""+k):"suppressContentEditableWarning"!== -c&&"suppressHydrationWarning"!==c&&(Oa.hasOwnProperty(c)?(null!=k&&ha(e,c),a||l===k||(a=[])):(a=a||[]).push(c,k))}h&&(a=a||[]).push("style",h);e=a;(b.updateQueue=e)&&Pb(b)}};Pg=function(a,b,c,d){c!==d&&Pb(b)};var ki="function"===typeof WeakSet?WeakSet:Set,xi="function"===typeof WeakMap?WeakMap:Map,qe=Ma.ReactCurrentDispatcher,Kg=Ma.ReactCurrentOwner,ze=1073741822,Ca=!1,x=null,Y=null,H=0,La=-1,je=!1,p=null,Lc=!1,ke=null,Jc=null,Ic=null,Ba=null,ba=null,I=null,Oc=0,Pc=void 0,w=!1,ca=null,C=0,oa=0,lb= -!1,Uc=null,z=!1,Rc=!1,kb=null,ve=ue(),aa=1073741822-(ve/10|0),jb=aa,Ci=50,Tb=0,we=null,Tc=!1;id=function(a,b,c){switch(b){case "input":td(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b=b;)c=d,d=d._next;a._next=d;null!==c&&(c._next=a)}return a}; -(function(a,b,c){Ye=a;yf=b;Ze=c})(Zg,ah,function(){w||0===oa||(Z(oa,!1),oa=0)});var oh={createPortal:ch,findDOMNode:function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternalFiber;void 0===b&&("function"===typeof a.render?n("188"):n("268",Object.keys(a)));a=tf(b);a=null===a?null:a.stateNode;return a},hydrate:function(a,b,c){ob(b)?void 0:n("200");return Wc(null,a,b,!0,c)},render:function(a,b,c){ob(b)?void 0:n("200");return Wc(null,a,b,!1,c)},unstable_renderSubtreeIntoContainer:function(a, -b,c,d){ob(c)?void 0:n("200");null==a||void 0===a._reactInternalFiber?n("38"):void 0;return Wc(a,b,c,!1,d)},unmountComponentAtNode:function(a){ob(a)?void 0:n("40");return a._reactRootContainer?($g(function(){Wc(null,null,a,!1,function(){a._reactRootContainer=null})}),!0):!1},unstable_createPortal:function(){return ch.apply(void 0,arguments)},unstable_batchedUpdates:Zg,unstable_interactiveUpdates:ah,flushSync:function(a,b){w?n("187"):void 0;var c=z;z=!0;try{return Tg(a,b)}finally{z=c,Z(1073741823,!1)}}, -unstable_createRoot:function(a,b){ob(a)?void 0:n("299","unstable_createRoot");return new nb(a,!0,null!=b&&!0===b.hydrate)},unstable_flushControlled:function(a){var b=z;z=!0;try{Tg(a)}finally{(z=b)||w||Z(1073741823,!1)}},__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{Events:[Je,Da,dd,Ae.injectEventPluginsByName,Zc,Qa,function(a){ad(a,xh)},Ve,We,oc,cd]}};(function(a){var b=a.findFiberByHostInstance;return ai(B({},a,{overrideProps:null,currentDispatcherRef:Ma.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a= -tf(a);return null===a?null:a.stateNode},findFiberByHostInstance:function(a){return b?b(a):null}}))})({findFiberByHostInstance:dc,bundleType:0,version:"16.8.3",rendererPackageName:"react-dom"});var ph={default:oh},qh=ph&&oh||ph;return qh.default||qh}); \ No newline at end of file +'use strict';(function(I,ea){"object"===typeof exports&&"undefined"!==typeof module?ea(exports,require("react")):"function"===typeof define&&define.amd?define(["exports","react"],ea):(I=I||self,ea(I.ReactDOM={},I.React))})(this,function(I,ea){function k(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;cb}return!1}function L(a, +b,c,d,e,f){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f}function xd(a,b,c,d){var e=E.hasOwnProperty(b)?E[b]:null;var f=null!==e?0===e.type:d?!1:!(2=c.length))throw Error(k(93));c=c[0]}b=c}null==b&&(b="");c=b}a._wrapperState={initialValue:va(c)}}function Lf(a,b){var c=va(b.value),d=va(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function Mf(a,b){b=a.textContent;b===a._wrapperState.initialValue&&""!== +b&&null!==b&&(a.value=b)}function Nf(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Hd(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?Nf(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}function nc(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}function oc(a){if(Id[a])return Id[a]; +if(!ib[a])return a;var b=ib[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Of)return Id[a]=b[c];return a}function Jd(a){var b=Pf.get(a);void 0===b&&(b=new Map,Pf.set(a,b));return b}function Na(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.effectTag&1026)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function Qf(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function Rf(a){if(Na(a)!== +a)throw Error(k(188));}function vi(a){var b=a.alternate;if(!b){b=Na(a);if(null===b)throw Error(k(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return Rf(e),a;if(f===d)return Rf(e),b;f=f.sibling}throw Error(k(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h= +f.child;h;){if(h===c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(k(189));}}if(c.alternate!==d)throw Error(k(190));}if(3!==c.tag)throw Error(k(188));return c.stateNode.current===c?a:b}function Sf(a){a=vi(a);if(!a)return null;for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b.child.return=b,b=b.child;else{if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}}return null}function jb(a,b){if(null== +b)throw Error(k(30));if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]}function Kd(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a)}function pc(a){null!==a&&(Ab=jb(Ab,a));a=Ab;Ab=null;if(a){Kd(a,wi);if(Ab)throw Error(k(95));if(hc)throw a=pd,hc=!1,pd=null,a;}}function Ld(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode: +a}function Tf(a){if(!wa)return!1;a="on"+a;var b=a in document;b||(b=document.createElement("div"),b.setAttribute(a,"return;"),b="function"===typeof b[a]);return b}function Uf(a){a.topLevelType=null;a.nativeEvent=null;a.targetInst=null;a.ancestors.length=0;10>qc.length&&qc.push(a)}function Vf(a,b,c,d){if(qc.length){var e=qc.pop();e.topLevelType=a;e.eventSystemFlags=d;e.nativeEvent=b;e.targetInst=c;return e}return{topLevelType:a,eventSystemFlags:d,nativeEvent:b,targetInst:c,ancestors:[]}}function Wf(a){var b= +a.targetInst,c=b;do{if(!c){a.ancestors.push(c);break}var d=c;if(3===d.tag)d=d.stateNode.containerInfo;else{for(;d.return;)d=d.return;d=3!==d.tag?null:d.stateNode.containerInfo}if(!d)break;b=c.tag;5!==b&&6!==b||a.ancestors.push(c);c=Bb(d)}while(c);for(c=0;c=b)return{node:c, +offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=hg(c)}}function jg(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?jg(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}function kg(){for(var a=window,b=Wd();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Wd(a.document)}return b} +function Xd(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}function lg(a,b){switch(a){case "button":case "input":case "select":case "textarea":return!!b.autoFocus}return!1}function Yd(a,b){return"textarea"===a||"option"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&& +null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}function kb(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break}return a}function mg(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(c===ng||c===Zd||c===$d){if(0===b)return a;b--}else c===og&&b++}a=a.previousSibling}return null}function Bb(a){var b=a[Aa];if(b)return b;for(var c=a.parentNode;c;){if(b=c[Lb]||c[Aa]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=mg(a);null!== +a;){if(c=a[Aa])return c;a=mg(a)}return b}a=c;c=a.parentNode}return null}function Hb(a){a=a[Aa]||a[Lb];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function Pa(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(k(33));}function ae(a){return a[vc]||null}function pa(a){do a=a.return;while(a&&5!==a.tag);return a?a:null}function pg(a,b){var c=a.stateNode;if(!c)return null;var d=td(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d= +!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&"function"!==typeof c)throw Error(k(231,b,typeof c));return c}function qg(a,b,c){if(b=pg(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=jb(c._dispatchListeners,b),c._dispatchInstances=jb(c._dispatchInstances,a)}function Ji(a){if(a&&a.dispatchConfig.phasedRegistrationNames){for(var b=a._targetInst,c=[];b;)c.push(b),b=pa(b);for(b=c.length;0this.eventPool.length&&this.eventPool.push(a)}function sg(a){a.eventPool=[];a.getPooled=Li;a.release=Mi}function tg(a,b){switch(a){case "keyup":return-1!==Ni.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "blur":return!0;default:return!1}}function ug(a){a=a.detail;return"object"===typeof a&&"data"in +a?a.data:null}function Oi(a,b){switch(a){case "compositionend":return ug(b);case "keypress":if(32!==b.which)return null;vg=!0;return wg;case "textInput":return a=b.data,a===wg&&vg?null:a;default:return null}}function Pi(a,b){if(mb)return"compositionend"===a||!de&&tg(a,b)?(a=rg(),wc=ce=Ba=null,mb=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1ob||(a.current=ie[ob],ie[ob]=null,ob--)}function y(a,b,c){ob++; +ie[ob]=a.current;a.current=b}function pb(a,b){var c=a.type.contextTypes;if(!c)return Ca;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function N(a){a=a.childContextTypes;return null!==a&&void 0!==a}function Fg(a,b,c){if(B.current!==Ca)throw Error(k(168));y(B,b);y(G,c)} +function Gg(a,b,c){var d=a.stateNode;a=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in a))throw Error(k(108,na(b)||"Unknown",e));return M({},c,{},d)}function Bc(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Ca;Ra=B.current;y(B,a);y(G,G.current);return!0}function Hg(a,b,c){var d=a.stateNode;if(!d)throw Error(k(169));c?(a=Gg(a,b,Ra),d.__reactInternalMemoizedMergedChildContext=a,q(G),q(B),y(B,a)):q(G);y(G,c)}function Cc(){switch(aj()){case Dc:return 99; +case Ig:return 98;case Jg:return 97;case Kg:return 96;case Lg:return 95;default:throw Error(k(332));}}function Mg(a){switch(a){case 99:return Dc;case 98:return Ig;case 97:return Jg;case 96:return Kg;case 95:return Lg;default:throw Error(k(332));}}function Da(a,b){a=Mg(a);return bj(a,b)}function Ng(a,b,c){a=Mg(a);return je(a,b,c)}function Og(a){null===qa?(qa=[a],Ec=je(Dc,Pg)):qa.push(a);return Qg}function ha(){if(null!==Ec){var a=Ec;Ec=null;Rg(a)}Pg()}function Pg(){if(!ke&&null!==qa){ke=!0;var a=0; +try{var b=qa;Da(99,function(){for(;a=b&&(ia=!0),a.firstContext=null)}function W(a,b){if(Gc!==a&&!1!==b&&0!==b){if("number"!==typeof b||1073741823===b)Gc=a,b=1073741823;b={context:a,observedBits:b,next:null};if(null===qb){if(null=== +Hc)throw Error(k(308));qb=b;Hc.dependencies={expirationTime:0,firstContext:b,responders:null}}else qb=qb.next=b}return a._currentValue}function ne(a){a.updateQueue={baseState:a.memoizedState,baseQueue:null,shared:{pending:null},effects:null}}function oe(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,baseQueue:a.baseQueue,shared:a.shared,effects:a.effects})}function Ea(a,b){a={expirationTime:a,suspenseConfig:b,tag:Tg,payload:null,callback:null,next:null};return a.next= +a}function Fa(a,b){a=a.updateQueue;if(null!==a){a=a.shared;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}}function Ug(a,b){var c=a.alternate;null!==c&&oe(c,a);a=a.updateQueue;c=a.baseQueue;null===c?(a.baseQueue=b.next=b,b.next=b):(b.next=c.next,c.next=b)}function Qb(a,b,c,d){var e=a.updateQueue;Ga=!1;var f=e.baseQueue,g=e.shared.pending;if(null!==g){if(null!==f){var h=f.next;f.next=g.next;g.next=h}f=g;e.shared.pending=null;h=a.alternate;null!==h&&(h=h.updateQueue,null!==h&& +(h.baseQueue=g))}if(null!==f){h=f.next;var m=e.baseState,n=0,k=null,ba=null,l=null;if(null!==h){var p=h;do{g=p.expirationTime;if(gn&&(n=g)}else{null!==l&&(l=l.next={expirationTime:1073741823,suspenseConfig:p.suspenseConfig,tag:p.tag,payload:p.payload,callback:p.callback,next:null});Vg(g,p.suspenseConfig);a:{var q=a,r=p;g=b;t=c;switch(r.tag){case 1:q= +r.payload;if("function"===typeof q){m=q.call(t,m,g);break a}m=q;break a;case 3:q.effectTag=q.effectTag&-4097|64;case Tg:q=r.payload;g="function"===typeof q?q.call(t,m,g):q;if(null===g||void 0===g)break a;m=M({},m,g);break a;case Jc:Ga=!0}}null!==p.callback&&(a.effectTag|=32,g=e.effects,null===g?e.effects=[p]:g.push(p))}p=p.next;if(null===p||p===h)if(g=e.shared.pending,null===g)break;else p=f.next=g.next,g.next=h,e.baseQueue=f=g,e.shared.pending=null}while(1)}null===l?k=m:l.next=ba;e.baseState=k;e.baseQueue= +l;Kc(n);a.expirationTime=n;a.memoizedState=m}}function Wg(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;br?(C=l,l=null):C=l.sibling;var O=p(e,l,h[r],m);if(null===O){null===l&&(l=C);break}a&&l&&null===O.alternate&&b(e,l);g=f(O,g,r);null===k?n=O:k.sibling=O;k=O;l=C}if(r===h.length)return c(e,l),n;if(null===l){for(;rC?(O=r,r=null):O=r.sibling;var q=p(e,r,v.value,n);if(null===q){null===r&&(r=O);break}a&&r&&null===q.alternate&&b(e,r);g=f(q,g,C);null===l?m=q:l.sibling=q;l=q;r=O}if(v.done)return c(e,r),m; +if(null===r){for(;!v.done;C++,v=h.next())v=ba(e,v.value,n),null!==v&&(g=f(v,g,C),null===l?m=v:l.sibling=v,l=v);return m}for(r=d(e,r);!v.done;C++,v=h.next())v=t(r,e,C,v.value,n),null!==v&&(a&&null!==v.alternate&&r.delete(null===v.key?C:v.key),g=f(v,g,C),null===l?m=v:l.sibling=v,l=v);a&&r.forEach(function(a){return b(e,a)});return m}return function(a,d,f,h){var m="object"===typeof f&&null!==f&&f.type===Ma&&null===f.key;m&&(f=f.props.children);var n="object"===typeof f&&null!==f;if(n)switch(f.$$typeof){case Pc:a:{n= +f.key;for(m=d;null!==m;){if(m.key===n){switch(m.tag){case 7:if(f.type===Ma){c(a,m.sibling);d=e(m,f.props.children);d.return=a;a=d;break a}break;default:if(m.elementType===f.type){c(a,m.sibling);d=e(m,f.props);d.ref=Rb(a,m,f);d.return=a;a=d;break a}}c(a,m);break}else b(a,m);m=m.sibling}f.type===Ma?(d=Ha(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Oc(f.type,f.key,f.props,null,a.mode,h),h.ref=Rb(a,d,f),h.return=a,a=h)}return g(a);case gb:a:{for(m=f.key;null!==d;){if(d.key===m)if(4===d.tag&&d.stateNode.containerInfo=== +f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=re(f,a.mode,h);d.return=a;a=d}return g(a)}if("string"===typeof f||"number"===typeof f)return f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=qe(f,a.mode,h),d.return=a,a=d),g(a);if(Qc(f))return q(a,d,f,h);if(zb(f))return w(a,d,f,h);n&&Nc(a,f);if("undefined"===typeof f&&!m)switch(a.tag){case 1:case 0:throw a= +a.type,Error(k(152,a.displayName||a.name||"Component"));}return c(a,d)}}function Ta(a){if(a===Sb)throw Error(k(174));return a}function se(a,b){y(Tb,b);y(Ub,a);y(ja,Sb);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:Hd(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=Hd(b,a)}q(ja);y(ja,b)}function tb(a){q(ja);q(Ub);q(Tb)}function bh(a){Ta(Tb.current);var b=Ta(ja.current);var c=Hd(b,a.type);b!==c&&(y(Ub,a),y(ja,c))}function te(a){Ub.current=== +a&&(q(ja),q(Ub))}function Rc(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||c.data===$d||c.data===Zd))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.effectTag&64))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}function ue(a,b){return{responder:a,props:b}} +function S(){throw Error(k(321));}function ve(a,b){if(null===b)return!1;for(var c=0;cf))throw Error(k(301));f+=1;J=K=null;b.updateQueue=null;Sc.current=fj;a=c(d,e)}while(b.expirationTime===Ia)}Sc.current=Tc;b=null!==K&&null!==K.next; +Ia=0;J=K=z=null;Uc=!1;if(b)throw Error(k(300));return a}function ub(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===J?z.memoizedState=J=a:J=J.next=a;return J}function vb(){if(null===K){var a=z.alternate;a=null!==a?a.memoizedState:null}else a=K.next;var b=null===J?z.memoizedState:J.next;if(null!==b)J=b,K=a;else{if(null===a)throw Error(k(310));K=a;a={memoizedState:K.memoizedState,baseState:K.baseState,baseQueue:K.baseQueue,queue:K.queue,next:null};null===J?z.memoizedState= +J=a:J=J.next=a}return J}function Ua(a,b){return"function"===typeof b?b(a):b}function Vc(a,b,c){b=vb();c=b.queue;if(null===c)throw Error(k(311));c.lastRenderedReducer=a;var d=K,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){e=e.next;d=d.baseState;var h=g=f=null,m=e;do{var n=m.expirationTime;if(nz.expirationTime&&(z.expirationTime=n,Kc(n))}else null!==h&&(h=h.next={expirationTime:1073741823,suspenseConfig:m.suspenseConfig,action:m.action,eagerReducer:m.eagerReducer,eagerState:m.eagerState,next:null}),Vg(n,m.suspenseConfig),d=m.eagerReducer===a?m.eagerState:a(d,m.action);m=m.next}while(null!==m&&m!==e);null===h?f=d:h.next=g;Qa(d,b.memoizedState)||(ia=!0);b.memoizedState=d;b.baseState=f;b.baseQueue=h;c.lastRenderedState=d}return[b.memoizedState, +c.dispatch]}function Wc(a,b,c){b=vb();c=b.queue;if(null===c)throw Error(k(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);Qa(f,b.memoizedState)||(ia=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}function xe(a){var b=ub();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={pending:null,dispatch:null,lastRenderedReducer:Ua, +lastRenderedState:a};a=a.dispatch=ch.bind(null,z,a);return[b.memoizedState,a]}function ye(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=z.updateQueue;null===b?(b={lastEffect:null},z.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}function dh(a){return vb().memoizedState}function ze(a,b,c,d){var e=ub();z.effectTag|=a;e.memoizedState=ye(1|b,c,void 0,void 0===d?null:d)}function Ae(a,b,c,d){var e=vb(); +d=void 0===d?null:d;var f=void 0;if(null!==K){var g=K.memoizedState;f=g.destroy;if(null!==d&&ve(d,g.deps)){ye(b,c,f,d);return}}z.effectTag|=a;e.memoizedState=ye(1|b,c,f,d)}function eh(a,b){return ze(516,4,a,b)}function Xc(a,b){return Ae(516,4,a,b)}function fh(a,b){return Ae(4,2,a,b)}function gh(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function hh(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null; +return Ae(4,2,gh.bind(null,b,a),c)}function Be(a,b){}function ih(a,b){ub().memoizedState=[a,void 0===b?null:b];return a}function Yc(a,b){var c=vb();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&ve(b,d[1]))return d[0];c.memoizedState=[a,b];return a}function jh(a,b){var c=vb();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&ve(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Ce(a,b,c){var d=Cc();Da(98>d?98:d,function(){a(!0)});Da(97\x3c/script>",a=a.removeChild(a.firstChild)):"string"===typeof d.is?a=g.createElement(e,{is:d.is}):(a=g.createElement(e),"select"===e&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,e);a[Aa]=b;a[vc]=d;jj(a,b,!1,!1);b.stateNode=a;g=Vd(e,d);switch(e){case "iframe":case "object":case "embed":w("load",a);h=d;break;case "video":case "audio":for(h=0;hd.tailExpiration&& +1a?c:a;return 2>=a&&b!==a?0:a}function V(a){if(0!==a.lastExpiredTime)a.callbackExpirationTime=1073741823,a.callbackPriority=99,a.callbackNode=Og(Te.bind(null,a));else{var b=fd(a),c=a.callbackNode;if(0===b)null!==c&&(a.callbackNode=null,a.callbackExpirationTime=0,a.callbackPriority=90);else{var d=ka(); +1073741823===b?d=99:1===b||2===b?d=95:(d=10*(1073741821-b)-10*(1073741821-d),d=0>=d?99:250>=d?98:5250>=d?97:95);if(null!==c){var e=a.callbackPriority;if(a.callbackExpirationTime===b&&e>=d)return;c!==Qg&&Rg(c)}a.callbackExpirationTime=b;a.callbackPriority=d;b=1073741823===b?Og(Te.bind(null,a)):Ng(d,Lh.bind(null,a),{timeout:10*(1073741821-b)-Y()});a.callbackNode=b}}}function Lh(a,b){dd=0;if(b)return b=ka(),Ue(a,b),V(a),null;var c=fd(a);if(0!==c){b=a.callbackNode;if((p&(ca|ma))!==H)throw Error(k(327)); +xb();a===U&&c===P||$a(a,c);if(null!==t){var d=p;p|=ca;var e=Mh();do try{rj();break}catch(h){Nh(a,h)}while(1);le();p=d;gd.current=e;if(F===hd)throw b=id,$a(a,c),Ya(a,c),V(a),b;if(null===t)switch(e=a.finishedWork=a.current.alternate,a.finishedExpirationTime=c,d=F,U=null,d){case Xa:case hd:throw Error(k(345));case Oh:Ue(a,2=c){a.lastPingedTime= +c;$a(a,c);break}}f=fd(a);if(0!==f&&f!==c)break;if(0!==d&&d!==c){a.lastPingedTime=d;break}a.timeoutHandle=We(ab.bind(null,a),e);break}ab(a);break;case bd:Ya(a,c);d=a.lastSuspendedTime;c===d&&(a.nextKnownPendingLevel=Ve(e));if(jd&&(e=a.lastPingedTime,0===e||e>=c)){a.lastPingedTime=c;$a(a,c);break}e=fd(a);if(0!==e&&e!==c)break;if(0!==d&&d!==c){a.lastPingedTime=d;break}1073741823!==Yb?d=10*(1073741821-Yb)-Y():1073741823===ta?d=0:(d=10*(1073741821-ta)-5E3,e=Y(),c=10*(1073741821-c)-e,d=e-d,0>d&&(d=0),d= +(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*sj(d/1960))-d,c=d?d=0:(e=g.busyDelayMs|0,f=Y()-(10*(1073741821-f)-(g.timeoutMs|0||5E3)),d=f<=e?0:e+d-f);if(10 component higher in the tree to provide a loading indicator or placeholder to display."+ +Bd(g))}F!==Xe&&(F=Oh);h=Le(h,g);k=f;do{switch(k.tag){case 3:m=h;k.effectTag|=4096;k.expirationTime=b;var A=Ih(k,m,b);Ug(k,A);break a;case 1:m=h;var u=k.type,B=k.stateNode;if(0===(k.effectTag&64)&&("function"===typeof u.getDerivedStateFromError||null!==B&&"function"===typeof B.componentDidCatch&&(null===La||!La.has(B)))){k.effectTag|=4096;k.expirationTime=b;var H=Jh(k,m,b);Ug(k,H);break a}}k=k.return}while(null!==k)}t=Sh(t)}catch(cj){b=cj;continue}break}while(1)}function Mh(a){a=gd.current;gd.current= +Tc;return null===a?Tc:a}function Vg(a,b){aXb&&(Xb=a)}function tj(){for(;null!==t;)t=Th(t)}function rj(){for(;null!==t&&!yj();)t=Th(t)}function Th(a){var b=zj(a.alternate,a,P);a.memoizedProps=a.pendingProps;null===b&&(b=Sh(a));Uh.current=null;return b}function Sh(a){t=a;do{var b=t.alternate;a=t.return;if(0===(t.effectTag&2048)){b=hj(b,t,P);if(1===P||1!==t.childExpirationTime){for(var c=0,d=t.child;null!==d;){var e=d.expirationTime, +f=d.childExpirationTime;e>c&&(c=e);f>c&&(c=f);d=d.sibling}t.childExpirationTime=c}if(null!==b)return b;null!==a&&0===(a.effectTag&2048)&&(null===a.firstEffect&&(a.firstEffect=t.firstEffect),null!==t.lastEffect&&(null!==a.lastEffect&&(a.lastEffect.nextEffect=t.firstEffect),a.lastEffect=t.lastEffect),1a?b:a}function ab(a){var b=Cc();Da(99,Aj.bind(null,a,b));return null}function Aj(a,b){do xb();while(null!==Zb);if((p&(ca|ma))!==H)throw Error(k(327));var c=a.finishedWork,d=a.finishedExpirationTime;if(null===c)return null;a.finishedWork=null;a.finishedExpirationTime=0;if(c===a.current)throw Error(k(177));a.callbackNode=null;a.callbackExpirationTime= +0;a.callbackPriority=90;a.nextKnownPendingLevel=0;var e=Ve(c);a.firstPendingTime=e;d<=a.lastSuspendedTime?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:d<=a.firstSuspendedTime&&(a.firstSuspendedTime=d-1);d<=a.lastPingedTime&&(a.lastPingedTime=0);d<=a.lastExpiredTime&&(a.lastExpiredTime=0);a===U&&(t=U=null,P=0);1h&&(n=h,h=g,g=n),n=ig(x,g),q=ig(x,h),n&&q&&(1!==u.rangeCount||u.anchorNode!==n.node||u.anchorOffset!==n.offset||u.focusNode!==q.node||u.focusOffset!==q.offset)&&(A=A.createRange(), +A.setStart(n.node,n.offset),u.removeAllRanges(),g>h?(u.addRange(A),u.extend(q.node,q.offset)):(A.setEnd(q.node,q.offset),u.addRange(A))))));A=[];for(u=x;u=u.parentNode;)1===u.nodeType&&A.push({element:u,left:u.scrollLeft,top:u.scrollTop});"function"===typeof x.focus&&x.focus();for(x=0;x=b&&a<=b}function Ya(a,b){var c=a.firstSuspendedTime,d=a.lastSuspendedTime; +cb||0===c)a.lastSuspendedTime=b;b<=a.lastPingedTime&&(a.lastPingedTime=0);b<=a.lastExpiredTime&&(a.lastExpiredTime=0)}function yh(a,b){b>a.firstPendingTime&&(a.firstPendingTime=b);var c=a.firstSuspendedTime;0!==c&&(b>=c?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:b>=a.lastSuspendedTime&&(a.lastSuspendedTime=b+1),b>a.nextKnownPendingLevel&&(a.nextKnownPendingLevel=b))}function Ue(a,b){var c=a.lastExpiredTime;if(0===c||c>b)a.lastExpiredTime=b} +function md(a,b,c,d){var e=b.current,f=ka(),g=Vb.suspense;f=Va(f,e,g);a:if(c){c=c._reactInternalFiber;b:{if(Na(c)!==c||1!==c.tag)throw Error(k(170));var h=c;do{switch(h.tag){case 3:h=h.stateNode.context;break b;case 1:if(N(h.type)){h=h.stateNode.__reactInternalMemoizedMergedChildContext;break b}}h=h.return}while(null!==h);throw Error(k(171));}if(1===c.tag){var m=c.type;if(N(m)){c=Gg(c,m,h);break a}}c=h}else c=Ca;null===b.context?b.context=c:b.pendingContext=c;b=Ea(f,g);b.payload={element:a};d=void 0=== +d?null:d;null!==d&&(b.callback=d);Fa(e,b);Ja(e,f);return f}function cf(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function Wh(a,b){a=a.memoizedState;null!==a&&null!==a.dehydrated&&a.retryTime