├── .circleci
├── codecov.yml
├── config.yml
└── settings.xml
├── .github
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── ISSUE_TEMPLATE
│ ├── BUG_REPORT.md
│ └── FEATURE_REQUEST.md
└── PULL_REQUEST_TEMPLATE.md
├── .gitignore
├── LICENSE
├── README.md
├── eclipse-formatter.xml
├── pom.xml
└── src
├── main
├── java
│ └── com
│ │ └── adobe
│ │ └── cq
│ │ └── commerce
│ │ └── graphql
│ │ └── client
│ │ ├── CachingStrategy.java
│ │ ├── GraphqlClient.java
│ │ ├── GraphqlClientConfiguration.java
│ │ ├── GraphqlRequest.java
│ │ ├── GraphqlResponse.java
│ │ ├── HttpMethod.java
│ │ ├── RequestOptions.java
│ │ ├── impl
│ │ ├── CacheInvalidator.java
│ │ ├── CacheKey.java
│ │ ├── GraphqlClientAdapterFactory.java
│ │ ├── GraphqlClientConfigurationImpl.java
│ │ ├── GraphqlClientImpl.java
│ │ ├── GraphqlClientMetrics.java
│ │ └── GraphqlClientMetricsImpl.java
│ │ └── package-info.java
└── resources
│ └── com
│ └── adobe
│ └── cq
│ └── commerce
│ └── graphql
│ └── client
│ └── version.properties
└── test
├── java
└── com
│ └── adobe
│ └── cq
│ └── commerce
│ └── graphql
│ └── client
│ ├── GraphqlClientTest.java
│ ├── GraphqlRequestTest.java
│ ├── RequestOptionsTest.java
│ └── impl
│ ├── CacheInvalidatorTest.java
│ ├── CacheKeyTest.java
│ ├── ConcurrencyTest.java
│ ├── GraphqlAemContext.java
│ ├── GraphqlClientAdapterFactoryTest.java
│ ├── GraphqlClientConfigurationImplTest.java
│ ├── GraphqlClientImplCachingTest.java
│ ├── GraphqlClientImplMetricsTest.java
│ ├── GraphqlClientImplTest.java
│ ├── MockGraphqlClientConfiguration.java
│ ├── MockServerHelper.java
│ ├── ProtocolTest.java
│ └── TestUtils.java
└── resources
├── com
└── adobe
│ └── cq
│ └── commerce
│ └── graphql
│ └── client
│ └── version.properties
├── context
└── graphql-client-adapter-factory-context.json
├── logback-test.xml
├── sample-graphql-request.json
└── sample-graphql-response.json
/.circleci/codecov.yml:
--------------------------------------------------------------------------------
1 | coverage:
2 | status:
3 | project:
4 | default:
5 | enabled: true
6 | target: 80%
7 | threshold: 10%
8 | base: auto
9 | patch:
10 | default:
11 | enabled: true
12 | target: 80%
13 | threshold: 10%
14 | base: auto
--------------------------------------------------------------------------------
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | jobs:
3 | build:
4 | docker:
5 | - image: circleci/openjdk:8-jdk
6 | steps:
7 | - checkout
8 | - restore_cache:
9 | keys:
10 | - maven-repo-v1-{{ checksum "pom.xml" }}
11 | - maven-repo-v1-
12 | - run:
13 | name: Build
14 | command: |
15 | java -version
16 | mvn -v
17 | mvn -B clean install -s .circleci/settings.xml
18 | - save_cache:
19 | paths:
20 | - ~/.m2
21 | key: maven-repo-v1-{{ checksum "pom.xml" }}
22 | - store_test_results:
23 | path: target/surefire-reports
24 | - store_artifacts:
25 | path: target/surefire-reports
26 | - run:
27 | name: Upload Code Coverage
28 | command: bash <(curl -s https://codecov.io/bash)
29 |
30 | release:
31 | docker:
32 | - image: circleci/openjdk:8-jdk
33 | steps:
34 | - checkout
35 | - restore_cache:
36 | keys:
37 | - maven-repo-v1-{{ checksum "pom.xml" }}
38 | - maven-repo-v1-
39 | - run:
40 | name: Release
41 | # Only performs a 'mvn deploy' after the 'mvn release:prepare' because circleCI
42 | # already checks out the git tag like 'mvn release:perform' would do.
43 | command: |
44 | echo $GPG_PRIVATE_KEY | base64 --decode | gpg --batch --import
45 | mvn -B -s .circleci/settings.xml clean deploy -P release-sign-artifacts
46 | rm -rf /home/circleci/.gnupg
47 |
48 | # The 'release' workflow is trigged by the release tags committed by 'mvn release:prepare'
49 | workflows:
50 | version: 2
51 | build-and-release:
52 | jobs:
53 | - build:
54 | filters:
55 | tags:
56 | only: /.*/
57 | - release:
58 | context:
59 | - CIF Maven Central
60 | requires:
61 | - build
62 | filters:
63 | branches:
64 | ignore: /.*/
65 | tags:
66 | only: /^graphql-client-.*/
--------------------------------------------------------------------------------
/.circleci/settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
15 |
16 |
17 |
18 |
19 | ossrh
20 |
21 | true
22 |
23 |
24 | gpg
25 | ${env.GPG_PASSPHRASE}
26 |
27 |
28 |
29 |
30 |
31 |
32 | ossrh
33 | ${env.SONATYPE_USER}
34 | ${env.SONATYPE_PASS}
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/.github/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Adobe Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, gender identity and expression, level of experience,
9 | nationality, personal appearance, race, religion, or sexual identity and
10 | orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at Grp-opensourceoffice@adobe.com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at [http://contributor-covenant.org/version/1/4][version]
72 |
73 | [homepage]: http://contributor-covenant.org
74 | [version]: http://contributor-covenant.org/version/1/4/
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Thanks for choosing to contribute!
4 |
5 | The following are a set of guidelines to follow when contributing to this project.
6 |
7 | ## Code Of Conduct
8 |
9 | This project adheres to the Adobe [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to the team.
10 |
11 | ## Contributor License Agreement
12 |
13 | All third-party contributions to this project must be accompanied by a signed contributor license agreement. This gives Adobe permission to redistribute your contributions as part of the project. [Sign our CLA](http://opensource.adobe.com/cla.html). You only need to submit an Adobe CLA one time, so if you have submitted one previously, you are good to go!
14 |
15 | ## How to contribute
16 |
17 | New code contributions should be made primarily using GitHub pull requests. This involves creating a fork of the project in your personal space, adding your new code in a branch and triggering a pull request.
18 |
19 | See how to perform pull requests at https://help.github.com/articles/using-pull-requests.
20 |
21 | Please follow the [pull request template](PULL_REQUEST_TEMPLATE.md) when submitting a pull request!
22 |
23 | ## New Feature request
24 | Please follow the [feature template](ISSUE_TEMPLATE/FEATURE_REQUEST.md) to open new feature requests.
25 |
26 |
27 | ## Issues
28 |
29 | Please follow the [issue template](ISSUE_TEMPLATE/BUG_REPORT.md) to open new [issues](https://github.com/adobe/commerce-cif-graphql-client/issues) and join the conversations to provide feedback.
30 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/BUG_REPORT.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Issue report
3 | about: Having an issue? Please create a report to explain what it is about.
4 |
5 | ---
6 |
7 | ### Expected Behaviour
8 |
9 | ### Actual Behaviour
10 |
11 | ### Reproduce Scenario (including but not limited to)
12 |
13 | #### Steps to Reproduce
14 |
15 | #### Platform and Version
16 |
17 | #### Sample Code that illustrates the problem
18 |
19 | #### Logs taken while reproducing problem
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Do you have new ideas for this project? Please fill in a request.
4 |
5 | ---
6 |
7 | ### User Story
8 |
9 |
10 |
11 | ### Description & Motivation
12 |
13 |
14 | ### Deliverables
15 |
16 |
17 |
18 |
19 |
20 | ### Acceptance Criteria
21 |
22 |
23 |
24 |
25 |
26 | ### Verification Steps
27 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Description
4 |
5 |
6 |
7 | ## Related Issue
8 |
9 |
10 |
11 |
12 |
13 |
14 | ## Motivation and Context
15 |
16 |
17 |
18 | ## How Has This Been Tested?
19 |
20 |
21 |
22 |
23 |
24 | ## Screenshots (if appropriate):
25 |
26 | ## Types of changes
27 |
28 |
29 |
30 | - [ ] Bug fix (non-breaking change which fixes an issue)
31 | - [ ] New feature (non-breaking change which adds functionality)
32 | - [ ] Breaking change (fix or feature that would cause existing functionality to change)
33 |
34 | ## Checklist:
35 |
36 |
37 |
38 |
39 | - [ ] I have signed the [Adobe Open Source CLA](http://opensource.adobe.com/cla.html).
40 | - [ ] My change requires a change to the documentation.
41 | - [ ] I have updated the documentation accordingly.
42 | - [ ] I have read the **CONTRIBUTING** document.
43 | - [ ] I have added tests to cover my changes and the overall coverage did not decrease.
44 | - [ ] All unit tests pass on CircleCi.
45 | - [ ] I ran all tests locally and they pass.
46 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | *.iml
3 | .classpath
4 | .metadata
5 | .project
6 | .settings
7 | /target/
8 | pom.xml.releaseBackup
9 | release.properties
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://circleci.com/gh/adobe/commerce-cif-graphql-client)
2 | [](https://codecov.io/gh/adobe/commerce-cif-graphql-client)
3 | [](https://search.maven.org/search?q=g:com.adobe.commerce.cif%20AND%20a:graphql-client)
4 |
5 | # GraphQL client
6 |
7 | This project is a GraphQL client for AEM. It is an OSGi bundle that can be instantiated with an OSGi configuration in the AEM OSGi configuration console. It can also be instantiated directly with java code.
8 |
9 | ## Installation
10 |
11 | To build and install the latest version in a running AEM instance, simply do
12 |
13 | ```
14 | mvn clean install sling:install
15 | ```
16 | This installs everything by default to `localhost:4502` without any context path. You can also configure the install location with the following maven properties:
17 | * `aem.host`: the name of the AEM instance
18 | * `aem.port`: the port number of the AEM instance
19 | * `aem.contextPath`: the context path (if any) of your AEM instance, starting with `/`
20 |
21 | ## Using the GraphQL client
22 |
23 | To use this library in your project, just add the following maven dependency to your project and install the bundle in your AEM instance:
24 |
25 | ```xml
26 |
27 | com.adobe.commerce.cif
28 | graphql-client
29 | ...
30 | provided
31 |
32 | ```
33 |
34 | You'll then have to setup and configure the client in your AEM instance.
35 |
36 | ## OSGi configuration
37 |
38 | To instantiate instances of this GraphQL client, simply go the AEM OSGi configuration console and look for "GraphQL Client Configuration Factory". Add a configuration and set the following mandatory parameters:
39 | * `identifier`: must be unique among all GraphQL clients.
40 | * `url`: the URL of the GraphQL server endpoint used by this client.
41 | * `httpMethod`: the default HTTP method used to send requests, can be either GET or POST. This can be overriden on a request basis.
42 |
43 | The `identifier` is used by the adapter factory to resolve clients via the `cq:graphqlClient` property set on any JCR node. When this is set on a resource or the resource ancestors, one can write `GraphqlClient client = resource.adaptTo(GraphqlClient.class);`.
44 |
45 | ### Caching
46 |
47 | Starting with version `1.4.0`, the client can cache GraphQL `query` requests based on the `cacheConfigurations` parameter. This supports the configuration of multiple caches, each being identified by a name and having its own set of caching parameters. This ensures that multiple components and services using cached data can have their own caching strategy and that those will not collide, for example when one component/service starves a common cache with a very large amount of requests. On the Java side, caching is controlled by the `CachingStrategy` class that can be set in the `RequestOptions` class.
48 |
49 | Because of the limitations of the AEM OSGi configuration console when defining multiple parameters with multiple values, each cache configuration entry must be specified with the following format:
50 | * `NAME:ENABLE:MAXSIZE:TIMEOUT` like for example `mycache:true:1000:60` where each attribute is defined as:
51 | * NAME (String) : the name of the cache
52 | * ENABLE (true|false) : enables or disables that cache entry (useful to temporarily disable a cache)
53 | * MAXSIZE (Integer) : the maximum size of the cache in number of entries
54 | * TIMEOUT (Integer) : the timeout for each cache entry, in seconds
55 |
56 | Note that even if it is enabled, a cache is only used if the `RequestOptions` set by the caller component/service defines the cache name and explicitly sets the `DataFetchingPolicy` to `CACHE_FIRST`. This ensures that the behavior of the client is backwards compatible (= caching is skipped by default). In addition, a caller can explicitly set the `DataFetchingPolicy` to `NETWORK_ONLY` to skip caching programmatically, even if caching is enabled in the OSGi configuration.
57 |
58 | ## Releases to Maven Central
59 |
60 | Releases are triggered by manually running `mvn release:prepare release:clean` on the `master` branch. This automatically pushes a commit with a release git tag like `graphql-client-x.y.z.` which triggers a dedicated `CircleCI` build that performs the deployment of the artifact to Maven Central.
61 |
62 | ## Code Formatting
63 | You can find the code formatting rules in the `eclipse-formatter.xml` file. The code formatting is automatically checked for each build. To automatically format your code, please run:
64 | ```bash
65 | mvn clean install -Pformat-code
66 | ```
67 |
68 | ### Contributing
69 |
70 | Contributions are welcomed! Read the [Contributing Guide](.github/CONTRIBUTING.md) for more information.
71 |
72 | ### Licensing
73 |
74 | This project is licensed under the Apache V2 License. See [LICENSE](LICENSE) for more information.
75 |
--------------------------------------------------------------------------------
/src/main/java/com/adobe/cq/commerce/graphql/client/CachingStrategy.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | *
3 | * Copyright 2020 Adobe. All rights reserved.
4 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License. You may obtain a copy
6 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software distributed under
9 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
10 | * OF ANY KIND, either express or implied. See the License for the specific language
11 | * governing permissions and limitations under the License.
12 | *
13 | ******************************************************************************/
14 |
15 | package com.adobe.cq.commerce.graphql.client;
16 |
17 | public class CachingStrategy {
18 |
19 | private String cacheName;
20 | private DataFetchingPolicy dataFetchingPolicy;
21 |
22 | public String getCacheName() {
23 | return cacheName;
24 | }
25 |
26 | public CachingStrategy withCacheName(String cacheName) {
27 | this.cacheName = cacheName;
28 | return this;
29 | }
30 |
31 | public DataFetchingPolicy getDataFetchingPolicy() {
32 | return dataFetchingPolicy;
33 | }
34 |
35 | public CachingStrategy withDataFetchingPolicy(DataFetchingPolicy dataFetchingPolicy) {
36 | this.dataFetchingPolicy = dataFetchingPolicy;
37 | return this;
38 | }
39 |
40 | /**
41 | * The data fetching policy with respect to caching.
42 | */
43 | public static enum DataFetchingPolicy {
44 |
45 | /**
46 | * Fetch data from the cache first. If the response doesn't exist or is expired, then fetch a response from the network.
47 | */
48 | CACHE_FIRST,
49 |
50 | /**
51 | * Fetch data from the network only, ignoring any cached responses.
52 | */
53 | NETWORK_ONLY
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/com/adobe/cq/commerce/graphql/client/GraphqlClient.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | *
3 | * Copyright 2019 Adobe. All rights reserved.
4 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License. You may obtain a copy
6 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software distributed under
9 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
10 | * OF ANY KIND, either express or implied. See the License for the specific language
11 | * governing permissions and limitations under the License.
12 | *
13 | ******************************************************************************/
14 |
15 | package com.adobe.cq.commerce.graphql.client;
16 |
17 | import java.lang.reflect.Type;
18 |
19 | import org.osgi.annotation.versioning.ProviderType;
20 |
21 | @ProviderType
22 | public interface GraphqlClient {
23 |
24 | /**
25 | * Returns the identifier of this GraphQL client and backing OSGi service.
26 | * This can be set on JCR resources with the cq:graphqlClient property.
27 | *
28 | * @return The identifier value of this client.
29 | */
30 | public String getIdentifier();
31 |
32 | /**
33 | * Returns the URL of the used GraphQL server endpoint.
34 | *
35 | * @return The backend GraphQL server endpoint used by this client.
36 | */
37 | public String getGraphQLEndpoint();
38 |
39 | /**
40 | * Returns the complete configuration of the GraphQL client.
41 | *
42 | * @return GraphQL client configuration.
43 | */
44 | public GraphqlClientConfiguration getConfiguration();
45 |
46 | /**
47 | * Executes the given GraphQL request and deserializes the response data based on the types T and U.
48 | * The type T is used to deserialize the 'data' object of the GraphQL response, and the type U is used
49 | * to deserialize the 'errors' array of the GraphQL response.
50 | * Each generic type can be a simple class or a generic class. To specify a simple class, just do:
51 | *
52 | *
57 | *
58 | * To specify a generic type (usually for the type T), one can use
59 | * the {@link com.google.gson.reflect.TypeToken} class. For example:
60 | *
61 | *
62 | * Type typeOfT = new TypeToken<List<String>>() {}.getType();
63 | * GraphqlResponse<List<String>, MyError> response = graphqlClient.execute(request, typeOfT, MyError.class);
64 | * List<String> data = response.getData();
65 | *
66 | *
67 | * @param request The GraphQL request.
68 | * @param typeOfT The type of the expected GraphQL response 'data' field.
69 | * @param typeOfU The type of the elements of the expected GraphQL response 'errors' field.
70 | *
71 | * @param The generic type of the 'data' object in the JSON GraphQL response.
72 | * @param The generic type of the elements of the 'errors' array in the JSON GraphQL response.
73 | *
74 | * @return A GraphQL response.
75 | *
76 | * @exception RuntimeException if the GraphQL HTTP request does not return 200 or if the JSON response cannot be parsed or deserialized.
77 | */
78 | public GraphqlResponse execute(GraphqlRequest request, Type typeOfT, Type typeOfU);
79 |
80 | /**
81 | * Executes the given GraphQL request and deserializes the response data based on the types T and U.
82 | * The type T is used to deserialize the 'data' object of the GraphQL response, and the type U is used
83 | * to deserialize the 'errors' array of the GraphQL response.
84 | * Each generic type can be a simple class or a generic class. To specify a simple class, just do:
85 | *
86 | *
91 | *
92 | * To specify a generic type (usually for the type T), one can use
93 | * the {@link com.google.gson.reflect.TypeToken} class. For example:
94 | *
95 | *
96 | * Type typeOfT = new TypeToken<List<String>>() {}.getType();
97 | * GraphqlResponse<List<String>, MyError> response = graphqlClient.execute(request, typeOfT, MyError.class);
98 | * List<String> data = response.getData();
99 | *
100 | *
101 | * @param request The GraphQL request.
102 | * @param typeOfT The type of the expected GraphQL response 'data' field.
103 | * @param typeOfU The type of the elements of the expected GraphQL response 'errors' field.
104 | * @param options An object holding options that can be set when executing the request.
105 | *
106 | * @param The generic type of the 'data' object in the JSON GraphQL response.
107 | * @param The generic type of the elements of the 'errors' array in the JSON GraphQL response.
108 | *
109 | * @return A GraphQL response.
110 | *
111 | * @exception RuntimeException if the GraphQL HTTP request does not return 200 or if the JSON response cannot be parsed or deserialized.
112 | */
113 | public GraphqlResponse execute(GraphqlRequest request, Type typeOfT, Type typeOfU, RequestOptions options);
114 |
115 | /**
116 | * Delete cache entries from in-memory cache based on the params entries.
117 | * If all params are null or empty, all cache entries are deleted.
118 | * If some params are not null or empty, then based on its corresponding cache entries will be deleted.
119 | *
120 | * @param storeView The store view to invalidate cache for.
121 | * @param cacheNames The cache names to invalidate.
122 | * @param patterns The patterns to invalidate cache for.
123 | */
124 | default void invalidateCache(String storeView, String[] cacheNames, String[] patterns) {
125 | // Default implementation does nothing
126 | }
127 | }
128 |
--------------------------------------------------------------------------------
/src/main/java/com/adobe/cq/commerce/graphql/client/GraphqlClientConfiguration.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | *
3 | * Copyright 2019 Adobe. All rights reserved.
4 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License. You may obtain a copy
6 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software distributed under
9 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
10 | * OF ANY KIND, either express or implied. See the License for the specific language
11 | * governing permissions and limitations under the License.
12 | *
13 | ******************************************************************************/
14 |
15 | package com.adobe.cq.commerce.graphql.client;
16 |
17 | import org.osgi.service.metatype.annotations.AttributeDefinition;
18 | import org.osgi.service.metatype.annotations.AttributeType;
19 | import org.osgi.service.metatype.annotations.ObjectClassDefinition;
20 |
21 | @ObjectClassDefinition(name = "CIF GraphQL Client Configuration Factory")
22 | public @interface GraphqlClientConfiguration {
23 |
24 | String CQ_GRAPHQL_CLIENT = "cq:graphqlClient";
25 | String DEFAULT_IDENTIFIER = "default";
26 |
27 | int MAX_HTTP_CONNECTIONS_DEFAULT = 20;
28 | boolean ACCEPT_SELF_SIGNED_CERTIFICATES = false;
29 | boolean ALLOW_HTTP_PROTOCOL = false;
30 |
31 | int DEFAULT_CONNECTION_TIMEOUT = 5000;
32 | int DEFAULT_SOCKET_TIMEOUT = 5000;
33 | int DEFAULT_REQUESTPOOL_TIMEOUT = 2000;
34 | int DEFAULT_CONNECTION_KEEP_ALIVE = -1;
35 | int DEFAULT_CONNECTION_TTL = -1;
36 |
37 | @AttributeDefinition(
38 | name = "GraphQL Service Identifier",
39 | description = "A unique identifier for this GraphQL client, used by the JCR resource property " + CQ_GRAPHQL_CLIENT
40 | + " to identify the service.",
41 | type = AttributeType.STRING,
42 | required = true)
43 | String identifier() default DEFAULT_IDENTIFIER;
44 |
45 | @AttributeDefinition(
46 | name = "GraphQL Service URL",
47 | description = "The URL of the GraphQL server endpoint, this must be a secure host using HTTPS.",
48 | type = AttributeType.STRING,
49 | required = true)
50 | String url();
51 |
52 | @AttributeDefinition(
53 | name = "Default HTTP method",
54 | description = "The default HTTP method used to send GraphQL requests.",
55 | required = true)
56 | HttpMethod httpMethod() default HttpMethod.POST;
57 |
58 | @AttributeDefinition(
59 | name = "Accept self-signed SSL certificates",
60 | description = "Enable insecure/developer mode to accept self-signed SSL certificates. Do NOT activate on production systems!",
61 | type = AttributeType.BOOLEAN)
62 | boolean acceptSelfSignedCertificates() default ACCEPT_SELF_SIGNED_CERTIFICATES;
63 |
64 | @AttributeDefinition(
65 | name = "Allow HTTP communication",
66 | description = "Enable insecure/developer mode to allow communication via HTTP. Do NOT activate on production systems!",
67 | type = AttributeType.BOOLEAN)
68 | boolean allowHttpProtocol() default ALLOW_HTTP_PROTOCOL;
69 |
70 | @AttributeDefinition(
71 | name = "Max HTTP connections",
72 | description = "The maximum number of concurrent HTTP connections the connector can make",
73 | type = AttributeType.INTEGER)
74 | int maxHttpConnections() default MAX_HTTP_CONNECTIONS_DEFAULT;
75 |
76 | @AttributeDefinition(
77 | name = "Http connection timeout",
78 | description = "The timeout in milliseconds until a connection is established. Is the timeout longer than the default timeout a "
79 | + "warning will be logged. Is it 0 or smaller it will fallback to the default timeout and a warning will be logged. Defaults "
80 | + "to " + DEFAULT_CONNECTION_TIMEOUT,
81 | type = AttributeType.INTEGER)
82 | int connectionTimeout() default DEFAULT_CONNECTION_TIMEOUT;
83 |
84 | @AttributeDefinition(
85 | name = "Http socket timeout",
86 | description = "The socket timeout in milliseconds, which is the timeout for waiting for data or, put differently, a maximum period "
87 | + "inactivity between two consecutive data packets. Is the timeout longer than the default timeout a warning will be logged. "
88 | + "Is it 0 or smaller it will fallback to the default timeout and a warning will be logged. Defaults to "
89 | + DEFAULT_SOCKET_TIMEOUT,
90 | type = AttributeType.INTEGER)
91 | int socketTimeout() default DEFAULT_SOCKET_TIMEOUT;
92 |
93 | @AttributeDefinition(
94 | name = "Request pool timeout",
95 | description = "The timeout in milliseconds used when requesting a connection from the connection manager. Is the timeout longer "
96 | + "than the default timeout a warning will be logged. Is it 0 or smaller it will fallback to the default timeout and a "
97 | + "warning will be logged. Defaults to " + DEFAULT_REQUESTPOOL_TIMEOUT,
98 | type = AttributeType.INTEGER)
99 | int requestPoolTimeout() default DEFAULT_REQUESTPOOL_TIMEOUT;
100 |
101 | @AttributeDefinition(
102 | name = "Connection keep alive timeout",
103 | description = "The maximum number of seconds an unused connections is kept alive in the connection pool after the last response. "
104 | + "If the value is < 0 then connections are kept alive indefinitely. If the value is 0 then connections will never be reused. "
105 | + "Defaults to " + DEFAULT_CONNECTION_KEEP_ALIVE,
106 | type = AttributeType.INTEGER)
107 | int connectionKeepAlive() default DEFAULT_CONNECTION_KEEP_ALIVE;
108 |
109 | @AttributeDefinition(
110 | name = "Connection time to live",
111 | description = "The maximum number of seconds a connections is reused for. If the value is < 0 then the connection may be reused "
112 | + "indefinitely, depending on the configured connection keep alive timeout. If the value is 0 then connections will never be "
113 | + "reused. Defaults to " + DEFAULT_CONNECTION_TTL,
114 | type = AttributeType.INTEGER)
115 | int connectionTtl() default DEFAULT_CONNECTION_TTL;
116 |
117 | @AttributeDefinition(
118 | name = "Default HTTP Headers",
119 | description = "HTTP Headers which shall be sent with each request. Might be used for authentication. The format of each header is "
120 | + "name:value",
121 | type = AttributeType.STRING)
122 | String[] httpHeaders();
123 |
124 | @AttributeDefinition(
125 | name = "GraphQL cache configurations",
126 | description = "Each entry must follow the format NAME:ENABLE:MAXSIZE:TIMEOUT like for example product:true:1000:5 - "
127 | + "NAME (String) : the name of the cache - "
128 | + "ENABLE (true|false) : enables or disables the cache with that NAME - "
129 | + "MAXSIZE (Integer) : the maximum size of the cache in number of entries - "
130 | + "TIMEOUT (Integer) : the timeout for each cache entry, in seconds.",
131 | type = AttributeType.STRING)
132 | String[] cacheConfigurations();
133 |
134 | @AttributeDefinition(
135 | name = "Ranking",
136 | description = "Integer value defining the ranking of this queue configuration. If more than one GraphQL Client use the same "
137 | + "identifier the one with the higher ranking will be used. Defaults to 0")
138 | int service_ranking() default 0;
139 | }
140 |
--------------------------------------------------------------------------------
/src/main/java/com/adobe/cq/commerce/graphql/client/GraphqlRequest.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | *
3 | * Copyright 2019 Adobe. All rights reserved.
4 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License. You may obtain a copy
6 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software distributed under
9 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
10 | * OF ANY KIND, either express or implied. See the License for the specific language
11 | * governing permissions and limitations under the License.
12 | *
13 | ******************************************************************************/
14 |
15 | package com.adobe.cq.commerce.graphql.client;
16 |
17 | import java.util.Objects;
18 |
19 | import org.apache.commons.lang3.StringUtils;
20 | import org.apache.commons.lang3.builder.HashCodeBuilder;
21 |
22 | public class GraphqlRequest {
23 |
24 | protected String query;
25 | protected String operationName;
26 | protected Object variables;
27 |
28 | private Integer hash;
29 |
30 | public GraphqlRequest(String query) {
31 | this.query = query;
32 | }
33 |
34 | public String getQuery() {
35 | return query;
36 | }
37 |
38 | public void setQuery(String query) {
39 | this.query = query;
40 | }
41 |
42 | public String getOperationName() {
43 | return operationName;
44 | }
45 |
46 | public void setOperationName(String operationName) {
47 | this.operationName = operationName;
48 | }
49 |
50 | public Object getVariables() {
51 | return variables;
52 | }
53 |
54 | public void setVariables(Object variables) {
55 | this.variables = variables;
56 | }
57 |
58 | @Override
59 | public boolean equals(Object o) {
60 | if (this == o) {
61 | return true;
62 | }
63 | if (o == null || getClass() != o.getClass()) {
64 | return false;
65 | }
66 | GraphqlRequest that = (GraphqlRequest) o;
67 | if (!StringUtils.equals(query, that.query)) {
68 | return false;
69 | }
70 | if (!StringUtils.equals(operationName, that.operationName)) {
71 | return false;
72 | }
73 | return Objects.equals(variables, that.variables);
74 | }
75 |
76 | @Override
77 | public int hashCode() {
78 | if (hash != null) {
79 | return hash.intValue();
80 | }
81 | hash = new HashCodeBuilder()
82 | .append(query)
83 | .append(operationName)
84 | .append(variables)
85 | .toHashCode();
86 | return hash.intValue();
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/main/java/com/adobe/cq/commerce/graphql/client/GraphqlResponse.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | *
3 | * Copyright 2019 Adobe. All rights reserved.
4 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License. You may obtain a copy
6 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software distributed under
9 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
10 | * OF ANY KIND, either express or implied. See the License for the specific language
11 | * governing permissions and limitations under the License.
12 | *
13 | ******************************************************************************/
14 |
15 | package com.adobe.cq.commerce.graphql.client;
16 |
17 | import java.util.List;
18 |
19 | public class GraphqlResponse {
20 |
21 | protected T data;
22 | protected List errors;
23 |
24 | public T getData() {
25 | return data;
26 | }
27 |
28 | public void setData(T data) {
29 | this.data = data;
30 | }
31 |
32 | public List getErrors() {
33 | return errors;
34 | }
35 |
36 | public void setErrors(List errors) {
37 | this.errors = errors;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/com/adobe/cq/commerce/graphql/client/HttpMethod.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | *
3 | * Copyright 2019 Adobe. All rights reserved.
4 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License. You may obtain a copy
6 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software distributed under
9 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
10 | * OF ANY KIND, either express or implied. See the License for the specific language
11 | * governing permissions and limitations under the License.
12 | *
13 | ******************************************************************************/
14 |
15 | package com.adobe.cq.commerce.graphql.client;
16 |
17 | /**
18 | * Represents the allowed and supported HTTP methods to send GraphQL requests.
19 | */
20 | public enum HttpMethod {
21 | POST, GET
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/com/adobe/cq/commerce/graphql/client/RequestOptions.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | *
3 | * Copyright 2019 Adobe. All rights reserved.
4 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License. You may obtain a copy
6 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software distributed under
9 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
10 | * OF ANY KIND, either express or implied. See the License for the specific language
11 | * governing permissions and limitations under the License.
12 | *
13 | ******************************************************************************/
14 |
15 | package com.adobe.cq.commerce.graphql.client;
16 |
17 | import java.util.Comparator;
18 | import java.util.List;
19 | import java.util.Objects;
20 | import java.util.stream.Collectors;
21 |
22 | import org.apache.commons.collections.CollectionUtils;
23 | import org.apache.commons.lang3.StringUtils;
24 | import org.apache.commons.lang3.builder.HashCodeBuilder;
25 | import org.apache.http.Header;
26 | import org.apache.http.message.BasicHeader;
27 |
28 | import com.google.gson.Gson;
29 |
30 | /**
31 | * This class is used to set various options when executing a GraphQL request.
32 | */
33 | public class RequestOptions {
34 |
35 | /**
36 | * To compare headers, we will sort them by name and value.
37 | */
38 | private static final Comparator HEADER_COMPARATOR = Comparator.comparing(Header::getName).thenComparing(Header::getValue);
39 |
40 | private Gson gson;
41 | private List headers;
42 | private HttpMethod httpMethod;
43 | private CachingStrategy cachingStrategy;
44 |
45 | private Integer hash;
46 |
47 | /**
48 | * Sets the {@link Gson} instance that will be used to deserialise the JSON response. This should only be used when the JSON
49 | * response cannot be deserialised by a standard Gson instance, or when some custom deserialisation is needed.
50 | *
51 | * @param gson A custom {@link Gson} instance.
52 | * @return This RequestOptions object.
53 | */
54 | public RequestOptions withGson(Gson gson) {
55 | this.gson = gson;
56 | return this;
57 | }
58 |
59 | /**
60 | * Permits to define HTTP headers that will be sent with the GraphQL request.
61 | * See {@link BasicHeader} for an implementation of the Header interface.
62 | *
63 | * @param headers The HTTP headers.
64 | * @return This RequestOptions object.
65 | */
66 | public RequestOptions withHeaders(List headers) {
67 | this.headers = headers;
68 | return this;
69 | }
70 |
71 | /**
72 | * Sets the HTTP method used to send the request, only GET or POST are supported.
73 | * By default, the client sends a POST request. If GET is used, the underlying HTTP client
74 | * will automatically URL-Encode the GraphQL query, operation name, and variables.
75 | *
76 | * @param httpMethod The HTTP method.
77 | * @return This RequestOptions object.
78 | */
79 | public RequestOptions withHttpMethod(HttpMethod httpMethod) {
80 | this.httpMethod = httpMethod;
81 | return this;
82 | }
83 |
84 | public RequestOptions withCachingStrategy(CachingStrategy cachingStrategy) {
85 | this.cachingStrategy = cachingStrategy;
86 | return this;
87 | }
88 |
89 | public Gson getGson() {
90 | return gson;
91 | }
92 |
93 | public List getHeaders() {
94 | return headers;
95 | }
96 |
97 | public HttpMethod getHttpMethod() {
98 | return httpMethod;
99 | }
100 |
101 | public CachingStrategy getCachingStrategy() {
102 | return cachingStrategy;
103 | }
104 |
105 | @Override
106 | public boolean equals(Object o) {
107 | if (this == o) {
108 | return true;
109 | }
110 | if (o == null || getClass() != o.getClass()) {
111 | return false;
112 | }
113 | RequestOptions that = (RequestOptions) o;
114 | if (!Objects.equals(httpMethod, that.httpMethod)) {
115 | return false;
116 | }
117 |
118 | if (CollectionUtils.isEmpty(headers) && CollectionUtils.isEmpty(that.headers)) {
119 | return true;
120 | }
121 | if ((headers == null) ^ (that.headers == null)) { // one is null but not the other
122 | return false;
123 | }
124 | if (headers.size() != that.headers.size()) {
125 | return false;
126 | }
127 |
128 | // We cannot use Objects.equals with lists because this checks object equality for all list elements
129 | // and elements must be in the same order.
130 |
131 | List sortedHeaders = headers.stream()
132 | .sorted(HEADER_COMPARATOR)
133 | .collect(Collectors.toList());
134 |
135 | List thatSortedHeaders = that.headers.stream()
136 | .sorted(HEADER_COMPARATOR)
137 | .collect(Collectors.toList());
138 |
139 | for (int i = 0, l = sortedHeaders.size(); i < l; i++) {
140 | Header header = sortedHeaders.get(i);
141 | Header thatHeader = thatSortedHeaders.get(i);
142 | if (!StringUtils.equals(header.getName(), thatHeader.getName())) {
143 | return false;
144 | }
145 | if (!StringUtils.equals(header.getValue(), thatHeader.getValue())) {
146 | return false;
147 | }
148 | }
149 | return true;
150 | }
151 |
152 | @Override
153 | public int hashCode() {
154 | if (hash != null) {
155 | return hash.intValue();
156 | }
157 | HashCodeBuilder builder = new HashCodeBuilder();
158 | builder.append(httpMethod);
159 | if (headers != null) {
160 | headers.stream()
161 | .sorted(HEADER_COMPARATOR)
162 | .forEach(h -> builder.append(h.getName()).append(h.getValue()));
163 | } else {
164 | builder.append(headers);
165 | }
166 | hash = builder.toHashCode();
167 | return hash.intValue();
168 | }
169 | }
170 |
--------------------------------------------------------------------------------
/src/main/java/com/adobe/cq/commerce/graphql/client/impl/CacheInvalidator.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | *
3 | * Copyright 2024 Adobe. All rights reserved.
4 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License. You may obtain a copy
6 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software distributed under
9 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
10 | * OF ANY KIND, either express or implied. See the License for the specific language
11 | * governing permissions and limitations under the License.
12 | *
13 | ******************************************************************************/
14 | package com.adobe.cq.commerce.graphql.client.impl;
15 |
16 | import java.util.Arrays;
17 | import java.util.List;
18 | import java.util.Map;
19 | import java.util.regex.Matcher;
20 | import java.util.regex.Pattern;
21 |
22 | import org.apache.commons.lang3.StringUtils;
23 | import org.apache.http.Header;
24 | import org.slf4j.Logger;
25 | import org.slf4j.LoggerFactory;
26 |
27 | import com.adobe.cq.commerce.graphql.client.GraphqlResponse;
28 | import com.google.common.cache.Cache;
29 | import com.google.gson.Gson;
30 | import com.google.gson.GsonBuilder;
31 |
32 | class CacheInvalidator {
33 | private static final Logger LOGGER = LoggerFactory.getLogger(CacheInvalidator.class);
34 | private static final String STORE_HEADER_NAME = "Store";
35 | private Map>> caches;
36 | private Gson gson;
37 |
38 | CacheInvalidator(Map>> caches) {
39 | this.caches = caches;
40 | this.gson = new GsonBuilder()
41 | .disableHtmlEscaping()
42 | .create();
43 | }
44 |
45 | private boolean isAllParametersEmpty(String storeView, String[] cacheNames, String[] patterns) {
46 | return StringUtils.isBlank(storeView) &&
47 | (cacheNames == null || cacheNames.length == 0) &&
48 | (patterns == null || patterns.length == 0);
49 | }
50 |
51 | private boolean isOnlyStoreViewProvided(String storeView, String[] cacheNames, String[] patterns) {
52 | return !StringUtils.isBlank(storeView) &&
53 | (cacheNames == null || cacheNames.length == 0) &&
54 | (patterns == null || patterns.length == 0);
55 | }
56 |
57 | private boolean isCacheNamesProvided(String[] cacheNames, String[] patterns) {
58 | return (cacheNames != null && cacheNames.length > 0) &&
59 | (patterns == null || patterns.length == 0);
60 | }
61 |
62 | /**
63 | * Invalidates cache entries based on the provided criteria.
64 | *
65 | * @param storeView The store view to match against cache entries
66 | * @param cacheNames Array of cache names to invalidate
67 | * @param patterns Array of regex patterns to match against cache entries
68 | */
69 | void invalidateCache(String storeView, String[] cacheNames, String[] patterns) {
70 | if (isAllParametersEmpty(storeView, cacheNames, patterns)) {
71 | invalidateAll();
72 | } else if (isOnlyStoreViewProvided(storeView, cacheNames, patterns)) {
73 | invalidateStoreView(storeView);
74 | } else if (isCacheNamesProvided(cacheNames, patterns)) {
75 | invalidateSpecificCaches(storeView, cacheNames);
76 | } else {
77 | for (String pattern : patterns) {
78 | if (pattern != null && !pattern.isEmpty()) {
79 | invalidateCacheBasedOnPattern(pattern, storeView, cacheNames);
80 | } else {
81 | LOGGER.debug("Skipping null pattern in patterns array");
82 | }
83 | }
84 | }
85 | }
86 |
87 | private void invalidateStoreView(String storeView) {
88 | caches.forEach((cacheName, cache) -> {
89 | cache.asMap().entrySet().stream()
90 | .filter(entry -> checkIfStorePresent(storeView, entry.getKey()))
91 | .forEach(entry -> {
92 | LOGGER.debug("Invalidating key based StoreView: {} in cache: {}", entry.getKey(), cacheName);
93 | cache.invalidate(entry.getKey());
94 | });
95 | });
96 | }
97 |
98 | private void invalidateAll() {
99 | LOGGER.debug("Invalidating all caches...");
100 | caches.values().forEach(Cache::invalidateAll);
101 | }
102 |
103 | private void invalidateSpecificCaches(String storeView, String[] cacheNames) {
104 | for (String cacheName : cacheNames) {
105 | Cache> cache = caches.get(cacheName);
106 | if (cache != null) {
107 | if (storeView == null) {
108 | LOGGER.debug("Invalidating entire cache: {}", cacheName);
109 | cache.invalidateAll();
110 | } else {
111 | cache.asMap().entrySet().stream()
112 | .filter(entry -> checkIfStorePresent(storeView, entry.getKey()))
113 | .forEach(entry -> {
114 | LOGGER.debug("Invalidating key based SpecificCaches & storeView: {} in cache: {}", entry.getKey(), cacheName);
115 | cache.invalidate(entry.getKey());
116 | });
117 | }
118 | } else {
119 | LOGGER.debug("Cache not found: {}", cacheName);
120 | }
121 | }
122 | }
123 |
124 | private void invalidateCacheBasedOnPattern(String pattern, String storeView, String[] listOfCacheToSearch) {
125 | Pattern regex = Pattern.compile(pattern);
126 | caches.forEach((cacheName, cache) -> {
127 | if (listOfCacheToSearch != null && listOfCacheToSearch.length > 0
128 | && !Arrays.asList(listOfCacheToSearch).contains(cacheName)) {
129 | return;
130 | }
131 | cache.asMap().entrySet().stream()
132 | .filter(entry -> {
133 | if (!checkIfStorePresent(storeView, entry.getKey())) {
134 | return false;
135 | }
136 | GraphqlResponse, ?> value = entry.getValue();
137 | String jsonResponse = gson.toJson(value);
138 | Matcher matcher = regex.matcher(jsonResponse);
139 | return matcher.find();
140 | })
141 | .forEach(entry -> {
142 | LOGGER.debug("Invalidating key: {} in cache based on pattern: {}", entry.getKey(), cacheName);
143 | cache.invalidate(entry.getKey());
144 | });
145 | });
146 | }
147 |
148 | private boolean checkIfStorePresent(String storeView, CacheKey cacheKey) {
149 | if (storeView == null || cacheKey == null || cacheKey.getRequestOptions() == null) {
150 | return false;
151 | }
152 | List headers = cacheKey.getRequestOptions().getHeaders();
153 | if (headers != null && !headers.isEmpty()) {
154 | return headers.stream()
155 | .anyMatch(
156 | header -> STORE_HEADER_NAME.equalsIgnoreCase(header.getName())
157 | && storeView.equalsIgnoreCase(header.getValue()));
158 | }
159 | return false;
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/src/main/java/com/adobe/cq/commerce/graphql/client/impl/CacheKey.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | *
3 | * Copyright 2020 Adobe. All rights reserved.
4 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License. You may obtain a copy
6 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software distributed under
9 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
10 | * OF ANY KIND, either express or implied. See the License for the specific language
11 | * governing permissions and limitations under the License.
12 | *
13 | ******************************************************************************/
14 |
15 | package com.adobe.cq.commerce.graphql.client.impl;
16 |
17 | import java.util.Objects;
18 |
19 | import com.adobe.cq.commerce.graphql.client.GraphqlRequest;
20 | import com.adobe.cq.commerce.graphql.client.RequestOptions;
21 |
22 | public class CacheKey {
23 |
24 | private GraphqlRequest request;
25 | private RequestOptions options;
26 | private Integer hash;
27 |
28 | CacheKey(GraphqlRequest request, RequestOptions options) {
29 | this.request = request;
30 | this.options = options;
31 | }
32 |
33 | @Override
34 | public int hashCode() {
35 | if (hash == null) {
36 | hash = Objects.hash(request, options);
37 | }
38 | return hash.intValue();
39 | }
40 |
41 | @Override
42 | public boolean equals(Object o) {
43 | if (this == o) {
44 | return true;
45 | }
46 | if (o == null || getClass() != o.getClass()) {
47 | return false;
48 | }
49 | CacheKey that = (CacheKey) o;
50 | return Objects.equals(request, that.request) && Objects.equals(options, that.options);
51 | }
52 |
53 | public GraphqlRequest getGraphqlRequest() {
54 | return request;
55 | }
56 |
57 | public RequestOptions getRequestOptions() {
58 | return options;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/com/adobe/cq/commerce/graphql/client/impl/GraphqlClientAdapterFactory.java:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | *
3 | * Copyright 2019 Adobe. All rights reserved.
4 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License. You may obtain a copy
6 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
7 | *
8 | * Unless required by applicable law or agreed to in writing, software distributed under
9 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
10 | * OF ANY KIND, either express or implied. See the License for the specific language
11 | * governing permissions and limitations under the License.
12 | *
13 | ******************************************************************************/
14 |
15 | package com.adobe.cq.commerce.graphql.client.impl;
16 |
17 | import java.util.Collections;
18 | import java.util.HashMap;
19 | import java.util.Map;
20 | import java.util.NavigableSet;
21 | import java.util.concurrent.ConcurrentSkipListSet;
22 |
23 | import org.apache.commons.lang3.StringUtils;
24 | import org.apache.sling.api.adapter.AdapterFactory;
25 | import org.apache.sling.api.resource.Resource;
26 | import org.apache.sling.api.resource.ValueMap;
27 | import org.apache.sling.commons.osgi.Order;
28 | import org.apache.sling.commons.osgi.ServiceUtil;
29 | import org.osgi.service.component.annotations.Component;
30 | import org.osgi.service.component.annotations.Reference;
31 | import org.osgi.service.component.annotations.ReferenceCardinality;
32 | import org.osgi.service.component.annotations.ReferencePolicy;
33 | import org.slf4j.Logger;
34 | import org.slf4j.LoggerFactory;
35 |
36 | import com.adobe.cq.commerce.graphql.client.GraphqlClient;
37 | import com.adobe.cq.commerce.graphql.client.GraphqlClientConfiguration;
38 | import com.day.cq.commons.inherit.ComponentInheritanceValueMap;
39 | import com.day.cq.commons.inherit.HierarchyNodeInheritanceValueMap;
40 | import com.day.cq.commons.inherit.InheritanceValueMap;
41 | import com.day.cq.wcm.api.Page;
42 | import com.day.cq.wcm.api.PageManager;
43 |
44 | @Component(
45 | service = { AdapterFactory.class },
46 | property = {
47 | AdapterFactory.ADAPTABLE_CLASSES + "=" + GraphqlClientAdapterFactory.RESOURCE_CLASS_NAME,
48 | AdapterFactory.ADAPTER_CLASSES + "=" + GraphqlClientAdapterFactory.GRAPHQLCLIENT_CLASS_NAME })
49 | public class GraphqlClientAdapterFactory implements AdapterFactory {
50 |
51 | protected static final String RESOURCE_CLASS_NAME = "org.apache.sling.api.resource.Resource";
52 | protected static final String GRAPHQLCLIENT_CLASS_NAME = "com.adobe.cq.commerce.graphql.client.GraphqlClient";
53 | protected static final String CONFIG_NAME = "cloudconfigs/commerce";
54 |
55 | private static final Logger LOGGER = LoggerFactory.getLogger(GraphqlClientAdapterFactory.class);
56 |
57 | protected NavigableSet clients = new ConcurrentSkipListSet<>();
58 | private transient Map clientsByIdentifier = Collections.emptyMap();
59 |
60 | @Reference(
61 | service = GraphqlClient.class,
62 | bind = "bindGraphqlClient",
63 | unbind = "unbindGraphqlClient",
64 | cardinality = ReferenceCardinality.AT_LEAST_ONE,
65 | policy = ReferencePolicy.DYNAMIC)
66 | protected void bindGraphqlClient(GraphqlClient graphqlClient, Map properties) {
67 | String identifier = graphqlClient.getIdentifier();
68 | LOGGER.info("Registering GraphqlClient '{}'", identifier);
69 | clients.add(new Holder(graphqlClient, properties));
70 | rebuildClientsByIdentifier();
71 | }
72 |
73 | protected void unbindGraphqlClient(GraphqlClient graphqlClient) {
74 | String identifier = graphqlClient.getIdentifier();
75 | LOGGER.info("De-registering GraphqlClient '{}'", identifier);
76 | clients.removeIf(holder -> holder.graphqlClient.equals(graphqlClient));
77 | rebuildClientsByIdentifier();
78 | }
79 |
80 | private void rebuildClientsByIdentifier() {
81 | Map newClientsByIdentifier = new HashMap<>(clients.size());
82 |
83 | for (Holder holder : clients) {
84 | newClientsByIdentifier.putIfAbsent(holder.graphqlClient.getIdentifier(), holder.graphqlClient);
85 | }
86 |
87 | clientsByIdentifier = Collections.unmodifiableMap(newClientsByIdentifier);
88 | }
89 |
90 | @SuppressWarnings("unchecked")
91 | @Override
92 | public AdapterType getAdapter(Object adaptable, Class type) {
93 | if (!(adaptable instanceof Resource) || type != GraphqlClient.class) {
94 | return null;
95 | }
96 |
97 | Resource res = (Resource) adaptable;
98 | ValueMap properties = res.getValueMap();
99 |
100 | String identifier = properties.get(GraphqlClientConfiguration.CQ_GRAPHQL_CLIENT, String.class);
101 | if (identifier == null) {
102 | identifier = readFallbackConfiguration(res);
103 | }
104 |
105 | if (StringUtils.isEmpty(identifier)) {
106 | LOGGER.error("Could not find {} property for given resource at {}", GraphqlClientConfiguration.CQ_GRAPHQL_CLIENT, res
107 | .getPath());
108 | return null;
109 | }
110 |
111 | GraphqlClient client = clientsByIdentifier.get(identifier);
112 |
113 | if (client == null) {
114 | LOGGER.error("No GraphqlClient instance available for catalog identifier '{}'", identifier);
115 | return null;
116 | }
117 |
118 | return (AdapterType) client;
119 | }
120 |
121 | private String readFallbackConfiguration(Resource resource) {
122 | InheritanceValueMap properties;
123 | Page page = resource.getResourceResolver()
124 | .adaptTo(PageManager.class)
125 | .getContainingPage(resource);
126 | if (page != null) {
127 | properties = new HierarchyNodeInheritanceValueMap(page.getContentResource());
128 | } else {
129 | properties = new ComponentInheritanceValueMap(resource);
130 | }
131 | return properties.getInherited(GraphqlClientConfiguration.CQ_GRAPHQL_CLIENT, String.class);
132 | }
133 |
134 | private static class Holder implements Comparable {
135 |
136 | private final GraphqlClient graphqlClient;
137 | private final Comparable