├── .github ├── dependabot.yml └── workflows │ ├── build_and_test.yml │ └── release_version.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── build.gradle.kts ├── examples └── query-for-document │ ├── .gitignore │ ├── README.md │ ├── build.gradle.kts │ ├── docker-compose.yaml │ ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── settings.gradle.kts │ └── src │ ├── main │ └── java │ │ └── com │ │ └── bisnode │ │ └── opa │ │ └── XmasHappening.java │ └── opa │ └── policies │ └── rules │ ├── age_rule.rego │ ├── name_rule.rego │ └── type_rule.rego ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main └── java │ └── com │ └── bisnode │ └── opa │ └── client │ ├── OpaClient.java │ ├── OpaClientException.java │ ├── OpaConfiguration.java │ ├── data │ ├── OpaDataApi.java │ ├── OpaDataClient.java │ └── OpaDocument.java │ ├── policy │ ├── OpaPolicy.java │ ├── OpaPolicyApi.java │ └── OpaPolicyClient.java │ ├── query │ ├── OpaQueryApi.java │ ├── OpaQueryClient.java │ ├── OpaQueryForDocumentRequest.java │ ├── OpaQueryForDocumentResponse.java │ └── QueryForDocumentRequest.java │ └── rest │ ├── ContentType.java │ ├── JsonBodyHandler.java │ ├── JsonBodyPublisher.java │ ├── ObjectMapperFactory.java │ ├── OpaRestClient.java │ ├── OpaServerConnectionException.java │ └── url │ ├── InvalidEndpointException.java │ └── OpaUrl.java └── test └── groovy └── com └── bisnode └── opa └── client ├── ManagingDocumentSpec.groovy ├── ManagingPolicySpec.groovy ├── OpaClientBuilderSpec.groovy ├── QueryingForDocumentSpec.groovy └── rest ├── ObjectMapperFactorySpec.groovy ├── OpaRestClientSpec.groovy └── url └── OpaUrlSpec.groovy /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "gradle" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/build_and_test.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | - uses: actions/setup-java@v1 11 | with: 12 | java-version: 11 13 | - uses: eskatos/gradle-command-action@v1 14 | with: 15 | arguments: build 16 | -------------------------------------------------------------------------------- /.github/workflows/release_version.yml: -------------------------------------------------------------------------------- 1 | name: releaseVersion 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v[0-9]+.[0-9]+.[0-9]+' 7 | 8 | jobs: 9 | buildAndRelease: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - uses: actions/setup-java@v1 14 | with: 15 | java-version: 11 16 | - uses: eskatos/gradle-command-action@v1 17 | env: 18 | ORG_GRADLE_PROJECT_signingKey: ${{ secrets.signingKey }} 19 | ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.signingPassword }} 20 | with: 21 | arguments: publishAllPublicationsToOSSRHRepository -PossrhUsername=${{ secrets.ossrhUsername }} -PossrhPassword=${{ secrets.ossrhPassword }} -Dorg.gradle.internal.publish.checksums.insecure=true 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | out/ 3 | build 4 | .gradle 5 | /gradle/wrapper/gradle-wrapper.jar 6 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | [this email](mailto:nights-watch@bisnode.com). 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html), 118 | version 2.0. 119 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | ### Welcome 4 | 5 | First off, thank you for considering contributing to Opa Java Client. It's people like you that make this client such a great library. 6 | 7 | Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue, assessing changes, and helping you finalize your pull requests. 8 | 9 | ### What we are looking for 10 | 11 | Opa Java Client is an open source project, and we love to receive contributions from our community — you! There are many ways to contribute, from writing tutorials or blog posts, improving the documentation, submitting bug reports and feature requests or writing code which can be incorporated into Opa Java Client itself. 12 | 13 | # Ground Rules 14 | 15 | Responsibilities 16 | * Ensure cross-platform compatibility for every change that's accepted. Windows, Mac, Debian & Ubuntu Linux. 17 | * Create issues for any major changes and enhancements that you wish to make. Discuss things transparently and get community feedback. 18 | * Keep feature versions as small as possible, preferably one new feature per version. 19 | * Be welcoming to newcomers and encourage diverse new contributors from all backgrounds. See the [Code of Conduct](https://github.com/Bisnode/opa-java-client/blob/master/CODE_OF_CONDUCT.md). 20 | 21 | # Getting started 22 | 23 | As a rule of thumb, changes are obvious fixes if they do not introduce any new functionality or creative thinking. As long as the change does not affect functionality, some likely examples include the following: 24 | * Spelling / grammar fixes 25 | * Typo correction, white space and formatting changes 26 | * Comment clean up 27 | * Bug fixes that change default return values or error codes stored in constants 28 | * Adding logging messages or debugging output 29 | * Changes to ‘metadata’ files like .gitignore, build scripts, etc. 30 | * Moving source files from one directory or package to another 31 | 32 | For something that is bigger than a few line fix: 33 | 34 | 1. Create your own fork of the code 35 | 2. Do the changes in your fork 36 | 3. If you like the change and think the project could use it 37 | * Be sure you have followed the code style for the project. 38 | * Note the Code of Conduct. 39 | * Send a pull request. 40 | 41 | 42 | # How to report a bug 43 | 44 | If you find a security vulnerability, do NOT open an issue. Email [maintainers](mailto:nights-watch@bisnode.com) instead. 45 | 46 | 47 | Any security issues should be submitted directly to [maintainers](mailto:nights-watch@bisnode.com) 48 | In order to determine whether you are dealing with a security issue, ask yourself these two questions: 49 | * Can I access something that's not mine, or something I shouldn't have access to? 50 | * Can I disable something for other people? 51 | 52 | If the answer to either of those two questions are "yes", then you're probably dealing with a security issue. Note that even if you answer "no" to both questions, you may still be dealing with a security issue, so if you're unsure, just [email us](mailto:nights-watch@bisnode.com). 53 | 54 | When filing an issue, make sure to answer these five questions: 55 | 56 | 1. What version of OPA/Java are you using? 57 | 2. What operating system and processor architecture are you using? 58 | 3. What did you do? 59 | 4. What did you expect to see? 60 | 5. What did you see instead? 61 | 62 | # How to report a Feature Request 63 | If you find yourself wishing for a feature that doesn't exist in Opa Java Client, you are probably not alone. There are bound to be others out there with similar needs. Many of the features that Opa Java Client has today have been added because our users saw the need. Open an issue on our issues list on GitHub which describes the feature you would like to see, why you need it, and how it should work. 64 | 65 | # Code review process 66 | 67 | The core team looks at Pull Requests as fast as possible. If there is a need, we can arrange a meeting and elaborate on implementation details. 68 | After feedback has been given we expect responses within two weeks. After two weeks we may close the pull request if it isn't showing any activity. 69 | 70 | ## Code, commit message and labeling conventions 71 | 72 | ### Commit message convention 73 | 74 | Please do not provide nondeterministic messages to commits like: "fix vol2", "another fix". 75 | From maintainers point of view, there should be one commit for one Pull Request. 76 | Perhaps the best idea is to squash commits before merge. 77 | 78 | ### Labeling convention 79 | 80 | [1] [StandardIssueLabels](https://github.com/wagenet/StandardIssueLabels#standardissuelabels) 81 | -------------------------------------------------------------------------------- /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 2020-2021 Bisnode 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 | # opa-java-client 2 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.bisnode.opa/opa-java-client/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.bisnode.opa/opa-java-client) ![build](https://github.com/Bisnode/opa-java-client/workflows/build/badge.svg) 3 | 4 | OPA java client is a wrapper for [OPA REST API](https://www.openpolicyagent.org/docs/latest/rest-api/). The goal was to create client that is lightweight and framework independent. It's built for current Bisnode needs, including: 5 | - creating documents 6 | - creating policies 7 | - querying for documents 8 | ## Installation 9 | **Prerequisites:** Java 11 or higher 10 | 11 | Add library using maven: 12 | ```xml 13 | 14 | com.bisnode.opa 15 | opa-java-client 16 | {version} 17 | 18 | ``` 19 | or Gradle 20 | ```groovy 21 | implementation 'com.bisnode.opa:opa-java-client:{version}' 22 | ``` 23 | 24 | ## Usage 25 | Our library is using Jackson for (de)serialization so, objects that you are passing/retrieving using this client should have either proper Jackson-friendly configuration or - the solution working in most cases - getters and setters for fields you want to pass/retrieve to/from OPA. 26 | [More information about Jackson](https://github.com/FasterXML/jackson-docs). 27 | 28 | ### Query for document 29 | ```java 30 | OpaQueryApi client = OpaClient.builder() 31 | .opaConfiguration("http://localhost:8181") 32 | .build(); 33 | 34 | DesiredResponse response = client.queryForDocument(new QueryForDocumentRequest(yourDTO, "path/to/document"), DesiredResponse.class); 35 | 36 | // Do whatever you like with the response 37 | ``` 38 | 39 | ### Query for a list of documents 40 | 41 | This requires [commons-lang3](https://mvnrepository.com/artifact/org.apache.commons/commons-lang3) to be present on your classpath. 42 | 43 | ```java 44 | OpaQueryApi client = OpaClient.builder() 45 | .opaConfiguration("http://localhost:8181") 46 | .build(); 47 | 48 | ParameterizedType type = TypeUtils.parameterize(List.class, DesiredResponse.class); 49 | 50 | List response = client.queryForDocument(new QueryForDocumentRequest(yourDTO, "path/to/document"), type); 51 | 52 | // Do whatever you like with the response 53 | ``` 54 | 55 | ####Example 56 | Example project is in `examples/query-for-document` directory. 57 | ### Create policy 58 | ```java 59 | OpaPolicyApi client = OpaClient.builder() 60 | .opaConfiguration("http://localhost:8181") 61 | .build(); 62 | 63 | void createOrUpdatePolicy(new OpaPolicy("your_policy_id", "content of the policy")); 64 | ``` 65 | ### Create document 66 | ```java 67 | OpaDataApi client = OpaClient.builder() 68 | .opaConfiguration("http://localhost:8181") 69 | .build(); 70 | 71 | void createOrOverwriteDocument(new OpaDocument("path/to/document", "content of document (json)")); 72 | ``` 73 | 74 | ### Error handling 75 | Error handling is done via exceptions. This means that if any error occurs, runtime exception which is subclass of `OpaClientException` is thrown. For now, there is simple error message returned. 76 | 77 | `OpaServerConnectionException` is thrown when connection problems with OPA server occur. 78 | 79 | ### Interface segregation 80 | Every OPA (Data, Policy, Query) API has it's own interface. So, for example, if you want to use client only for querying, you can use `OpaQueryApi` as projection. Thanks to that, in your code there will be exposed only methods that are needed by you, while not allowing to mess with policies and data. 81 | 82 | Available interface projections: 83 | - `OpaQueryApi` 84 | - `OpaPolicyApi` 85 | - `OpaDataApi` 86 | 87 | ## Developing and building 88 | Build process and dependency management is done using Gradle. 89 | Tests are written in spock. 90 | 91 | ## Contribution 92 | 93 | Interested in contributing? Please, start by reading [this document](https://github.com/Bisnode/opa-java-client/blob/master/CONTRIBUTING.md). 94 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.gradle.api.JavaVersion.VERSION_11 2 | import java.util.* 3 | 4 | version = "0.4.5" 5 | group = "com.bisnode.opa" 6 | 7 | plugins { 8 | groovy 9 | java 10 | `java-library` 11 | `maven-publish` 12 | signing 13 | } 14 | 15 | java { 16 | sourceCompatibility = VERSION_11 17 | targetCompatibility = VERSION_11 18 | withJavadocJar() 19 | withSourcesJar() 20 | } 21 | dependencies { 22 | implementation("com.fasterxml.jackson.core:jackson-databind:2.16.1") 23 | implementation("org.slf4j:slf4j-api:2.0.13") 24 | 25 | 26 | testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.2") 27 | testImplementation("org.junit.vintage:junit-vintage-engine:5.10.2") 28 | testImplementation("org.apache.groovy:groovy:4.0.21") 29 | testImplementation("org.spockframework:spock-core:2.3-groovy-4.0") 30 | testImplementation("com.github.tomakehurst:wiremock-jre8:3.0.1") 31 | testImplementation("net.bytebuddy:byte-buddy:1.14.14") 32 | } 33 | 34 | repositories { 35 | mavenCentral() 36 | } 37 | 38 | tasks.test { 39 | useJUnitPlatform() 40 | } 41 | 42 | tasks.javadoc { 43 | source = sourceSets["main"].allJava 44 | } 45 | 46 | publishing { 47 | publications { 48 | create("mavenJava") { 49 | artifactId = "opa-java-client" 50 | from(components["java"]) 51 | pom { 52 | name.set("OPA Java Client") 53 | description.set("Lightweight Java library for Open Policy Agent") 54 | url.set("https://github.com/Bisnode/opa-java-client") 55 | licenses { 56 | license { 57 | name.set("The Apache License, Version 2.0") 58 | url.set("http://www.apache.org/licenses/LICENSE-2.0.txt") 59 | distribution.set("repo") 60 | } 61 | } 62 | scm { 63 | connection.set("scm:git:git://github.com/Bisnode/opa-java-client.git") 64 | developerConnection.set("scm:git:ssh://github.com:Bisnode/opa-java-client.git") 65 | url.set("https://github.com/Bisnode/opa-java-client.git") 66 | } 67 | developers { 68 | developer { 69 | name.set("Igor Rodzik") 70 | email.set("igor.rodzik@bisnode.com") 71 | organization.set("Bisnode") 72 | organizationUrl.set("https://www.bisnode.com") 73 | } 74 | } 75 | } 76 | } 77 | } 78 | repositories { 79 | maven { 80 | val ossrhUsername: String? by project 81 | val ossrhPassword: String? by project 82 | name = "OSSRH" 83 | credentials { 84 | username = ossrhUsername 85 | password = ossrhPassword 86 | } 87 | val releasesRepoUrl = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/") 88 | val snapshotsRepoUrl = uri("https://oss.sonatype.org/content/repositories/snapshots") 89 | url = if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl 90 | } 91 | } 92 | } 93 | 94 | signing { 95 | val signingKey: String? by project 96 | val signingPassword: String? by project 97 | val decodedKey = signingKey 98 | ?.let { Base64.getDecoder().decode(signingKey) } 99 | ?.let { String(it) } 100 | useInMemoryPgpKeys(decodedKey, signingPassword) 101 | sign(publishing.publications["mavenJava"]) 102 | } 103 | -------------------------------------------------------------------------------- /examples/query-for-document/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore Gradle project-specific cache directory 2 | .gradle 3 | .idea 4 | # Ignore Gradle build output directory 5 | build 6 | -------------------------------------------------------------------------------- /examples/query-for-document/README.md: -------------------------------------------------------------------------------- 1 | # Query For Document example 2 | 3 | ## Introduction 4 | This is a repository which contains example usage of `queryForDocument` method from `opa-java-client` repository. 5 | Policies are stored in `examples/query-for-document/src/opa/policies/rules`. 6 | 7 | ### Usage 8 | Enter terminal in `examples/query-for-document` directory. 9 | Please run firstly OPA server with
10 | `docker-compose up`.
11 | Subsequently, run main application with
12 | `./gradlew run`
or `gradlew.bat run`(Windows) 13 | 14 | 15 | ### More examples 16 | If you need more examples, please create issue in `opa-java-client` repository. 17 | -------------------------------------------------------------------------------- /examples/query-for-document/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | groovy 3 | application 4 | } 5 | 6 | repositories { 7 | jcenter() 8 | } 9 | 10 | dependencies { 11 | implementation("com.bisnode.opa:opa-java-client:0.3.0") 12 | implementation("org.slf4j:slf4j-simple:1.7.30") 13 | 14 | testImplementation("org.codehaus.groovy:groovy-all:2.5.13") 15 | testImplementation("junit:junit:4.13") 16 | } 17 | 18 | application { 19 | mainClass.set("com.bisnode.opa.XmasHappening") 20 | } 21 | -------------------------------------------------------------------------------- /examples/query-for-document/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '2' 2 | 3 | services: 4 | opa: 5 | image: openpolicyagent/opa:latest 6 | ports: 7 | - 8181:8181 8 | volumes: 9 | - ./src/opa/policies:/src/opa/policies 10 | command: 11 | - "run" 12 | - "--watch" 13 | - "--server" 14 | - "--log-level=debug" 15 | - "--log-format=text" 16 | - "src/opa/policies" 17 | -------------------------------------------------------------------------------- /examples/query-for-document/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bisnode/opa-java-client/d8ef373d4a7127ad8162f88df04b111eb14dad22/examples/query-for-document/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /examples/query-for-document/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /examples/query-for-document/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /examples/query-for-document/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /examples/query-for-document/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "query-for-document" 2 | -------------------------------------------------------------------------------- /examples/query-for-document/src/main/java/com/bisnode/opa/XmasHappening.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa; 2 | 3 | import com.bisnode.opa.client.OpaClient; 4 | import com.bisnode.opa.client.query.OpaQueryApi; 5 | import com.bisnode.opa.client.query.QueryForDocumentRequest; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import java.util.List; 10 | 11 | public class XmasHappening { 12 | private static final Logger log = LoggerFactory.getLogger(XmasHappening.class); 13 | 14 | public static final String TYPE_RULE_PRESENTS_PACKAGING_PATH = "type_rule/presents_packaging"; 15 | public static final String AGE_QUERY_PATH = "age_rule/access_to_xmas_wine"; 16 | public static final String NAME_QUERY_PATH = "name_rule/access_to_chimney"; 17 | public static final String OPA_URL = "http://localhost:8181/"; 18 | 19 | 20 | public static void main(String[] args) { 21 | 22 | 23 | List sleighCrew = List.of( 24 | new OpaInput("SantaClaus", 99, SantaPartyMember.SANTA.name()), 25 | new OpaInput("Buddy", 17, SantaPartyMember.ELF.name()), 26 | new OpaInput("Grinch",22, SantaPartyMember.GRINCH.name()), 27 | new OpaInput("Rudolf", 33, SantaPartyMember.REINDEER.name()), 28 | new OpaInput("Niko", 25, SantaPartyMember.REINDEER.name())); 29 | 30 | sleighCrew.forEach(XmasHappening::callOpa); 31 | 32 | } 33 | 34 | static void callOpa(OpaInput testInput){ 35 | log.info("Creating query for input {}", testInput); 36 | OpaQueryApi queryApi = OpaClient.builder().opaConfiguration(OPA_URL).build(); 37 | 38 | QueryForDocumentRequest ageRequest = new QueryForDocumentRequest(testInput, AGE_QUERY_PATH); 39 | OpaOutput ageResponse = queryApi.queryForDocument(ageRequest, OpaOutput.class); 40 | log.info(ageResponse.toString()); 41 | 42 | QueryForDocumentRequest typeRequest = new QueryForDocumentRequest(testInput, TYPE_RULE_PRESENTS_PACKAGING_PATH); 43 | OpaOutput typeResponse = queryApi.queryForDocument(typeRequest, OpaOutput.class); 44 | log.info(typeResponse.toString()); 45 | 46 | QueryForDocumentRequest nameRequest = new QueryForDocumentRequest(testInput, NAME_QUERY_PATH); 47 | OpaOutput nameResponse = queryApi.queryForDocument(nameRequest, OpaOutput.class); 48 | log.info(nameResponse.toString()); 49 | } 50 | } 51 | 52 | class OpaOutput { 53 | private Boolean allow; 54 | private String reason; 55 | 56 | public Boolean getAllow() { 57 | return allow; 58 | } 59 | 60 | public void setAllow(Boolean allow) { 61 | this.allow = allow; 62 | } 63 | 64 | public String getReason() { 65 | return reason; 66 | } 67 | 68 | public void setReason(String reason) { 69 | 70 | this.reason = reason; 71 | } 72 | 73 | @Override 74 | public String toString() { 75 | return "OpaOutput{" + 76 | "allow=" + allow + 77 | ", reason='" + reason + '\'' + 78 | '}'; 79 | } 80 | } 81 | 82 | class OpaInput { 83 | private final String name; 84 | private final int age; 85 | private final String santaPartyMember; 86 | 87 | OpaInput(String name, int age, String santaPartyMember) { 88 | this.name = name; 89 | this.age = age; 90 | this.santaPartyMember = santaPartyMember; 91 | } 92 | 93 | public String getName() { 94 | return name; 95 | } 96 | 97 | public int getAge() { 98 | return age; 99 | } 100 | 101 | public String getSantaPartyMember() { 102 | return santaPartyMember; 103 | } 104 | 105 | @Override 106 | public String toString() { 107 | return "OpaInput{" + 108 | "name='" + name + '\'' + 109 | ", age=" + age + 110 | ", santaPartyMember=" + santaPartyMember + 111 | '}'; 112 | } 113 | } 114 | 115 | enum SantaPartyMember { 116 | SANTA, 117 | ELF, 118 | REINDEER, 119 | GRINCH 120 | } 121 | -------------------------------------------------------------------------------- /examples/query-for-document/src/opa/policies/rules/age_rule.rego: -------------------------------------------------------------------------------- 1 | package age_rule 2 | 3 | 4 | access_to_xmas_wine = { 5 | "allow": false, 6 | "reason": "You are not adult yet" 7 | } { 8 | input.age < 18 9 | } else = { 10 | "allow": true, 11 | "reason": "Xmas wine for you!" 12 | } 13 | -------------------------------------------------------------------------------- /examples/query-for-document/src/opa/policies/rules/name_rule.rego: -------------------------------------------------------------------------------- 1 | package name_rule 2 | 3 | 4 | access_to_chimney = { 5 | "allow": true, 6 | "reason": "Welcome Santa" 7 | } { 8 | input.name == "SantaClaus" 9 | } else = { 10 | "allow": false, 11 | "reason": "Can't jump into chimney" 12 | } 13 | -------------------------------------------------------------------------------- /examples/query-for-document/src/opa/policies/rules/type_rule.rego: -------------------------------------------------------------------------------- 1 | package type_rule 2 | 3 | allowed_party_members = {"SANTA", "ELF"} 4 | presents_packaging = { 5 | "allow": true, 6 | "reason": sprintf("%v may pack presents for children", [input.name]) 7 | } { 8 | input.santaPartyMember == allowed_party_members[_] 9 | } else = { 10 | "allow" : false, 11 | "reason": "Only trusted members of Santa team may pack presents" 12 | } 13 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Bisnode/opa-java-client/d8ef373d4a7127ad8162f88df04b111eb14dad22/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "opa-java-client" 2 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/OpaClient.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client; 2 | 3 | 4 | import com.bisnode.opa.client.data.OpaDataApi; 5 | import com.bisnode.opa.client.data.OpaDataClient; 6 | import com.bisnode.opa.client.data.OpaDocument; 7 | import com.bisnode.opa.client.policy.OpaPolicy; 8 | import com.bisnode.opa.client.policy.OpaPolicyApi; 9 | import com.bisnode.opa.client.policy.OpaPolicyClient; 10 | import com.bisnode.opa.client.query.OpaQueryApi; 11 | import com.bisnode.opa.client.query.OpaQueryClient; 12 | import com.bisnode.opa.client.query.QueryForDocumentRequest; 13 | import com.bisnode.opa.client.rest.ObjectMapperFactory; 14 | import com.bisnode.opa.client.rest.OpaRestClient; 15 | import com.fasterxml.jackson.databind.ObjectMapper; 16 | 17 | import java.lang.reflect.ParameterizedType; 18 | import java.net.http.HttpClient; 19 | import java.util.Objects; 20 | import java.util.Optional; 21 | 22 | /** 23 | * Opa client featuring {@link OpaDataApi}, {@link OpaQueryApi} and {@link OpaPolicyApi} 24 | */ 25 | public class OpaClient implements OpaQueryApi, OpaDataApi, OpaPolicyApi { 26 | 27 | private final OpaQueryApi opaQueryApi; 28 | private final OpaDataApi opaDataApi; 29 | private final OpaPolicyApi opaPolicyApi; 30 | 31 | private OpaClient(OpaQueryApi opaQueryApi, OpaDataApi opaDataApi, OpaPolicyApi opaPolicyApi) { 32 | this.opaQueryApi = opaQueryApi; 33 | this.opaDataApi = opaDataApi; 34 | this.opaPolicyApi = opaPolicyApi; 35 | } 36 | 37 | /** 38 | * @return builder for {@link OpaClient} 39 | */ 40 | public static Builder builder() { 41 | return new Builder(); 42 | } 43 | 44 | /** 45 | * @see com.bisnode.opa.client.query.OpaQueryApi 46 | */ 47 | public R queryForDocument(QueryForDocumentRequest queryForDocumentRequest, ParameterizedType responseType) { 48 | return this.opaQueryApi.queryForDocument(queryForDocumentRequest, responseType); 49 | } 50 | 51 | /** 52 | * @see com.bisnode.opa.client.query.OpaQueryApi 53 | */ 54 | public R queryForDocument(QueryForDocumentRequest queryForDocumentRequest, Class responseType) { 55 | return this.opaQueryApi.queryForDocument(queryForDocumentRequest, responseType); 56 | } 57 | 58 | /** 59 | * @see com.bisnode.opa.client.data.OpaDataApi 60 | */ 61 | public void createOrOverwriteDocument(OpaDocument document) { 62 | this.opaDataApi.createOrOverwriteDocument(document); 63 | } 64 | 65 | /** 66 | * @see com.bisnode.opa.client.policy.OpaPolicyApi 67 | */ 68 | public void createOrUpdatePolicy(OpaPolicy policy) { 69 | this.opaPolicyApi.createOrUpdatePolicy(policy); 70 | } 71 | 72 | /** 73 | * Builder for {@link OpaClient} 74 | */ 75 | public static class Builder { 76 | private OpaConfiguration opaConfiguration; 77 | private ObjectMapper objectMapper; 78 | 79 | /** 80 | * @param url URL including protocol and port 81 | */ 82 | public Builder opaConfiguration(String url) { 83 | this.opaConfiguration = new OpaConfiguration(url); 84 | return this; 85 | } 86 | 87 | public Builder objectMapper(ObjectMapper objectMapper) { 88 | this.objectMapper = objectMapper; 89 | return this; 90 | } 91 | 92 | public OpaClient build() { 93 | Objects.requireNonNull(opaConfiguration, "build() called without opaConfiguration provided"); 94 | HttpClient httpClient = HttpClient.newBuilder() 95 | .version(opaConfiguration.getHttpVersion()) 96 | .build(); 97 | ObjectMapper objectMapper = Optional.ofNullable(this.objectMapper) 98 | .orElseGet(ObjectMapperFactory.getInstance()::create); 99 | OpaRestClient opaRestClient = new OpaRestClient(opaConfiguration, httpClient, objectMapper); 100 | return new OpaClient(new OpaQueryClient(opaRestClient), new OpaDataClient(opaRestClient), new OpaPolicyClient(opaRestClient)); 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/OpaClientException.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client; 2 | 3 | /** 4 | * Exception returned by {@link OpaClient} 5 | * All exceptions that will be thrown inside {@link OpaClient} will be mapped to this one 6 | */ 7 | public class OpaClientException extends RuntimeException { 8 | public OpaClientException() { 9 | super(); 10 | } 11 | 12 | public OpaClientException(String message) { 13 | super(message); 14 | } 15 | 16 | public OpaClientException(String message, Throwable cause) { 17 | super(message, cause); 18 | } 19 | 20 | public OpaClientException(Throwable cause) { 21 | super(cause); 22 | } 23 | 24 | protected OpaClientException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 25 | super(message, cause, enableSuppression, writableStackTrace); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/OpaConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client; 2 | 3 | import java.beans.ConstructorProperties; 4 | import java.net.URI; 5 | import java.net.http.HttpClient; 6 | import java.util.Objects; 7 | 8 | /** 9 | * Contains all configuration needed to set up {@link OpaClient} 10 | */ 11 | public final class OpaConfiguration { 12 | private final String url; 13 | private final HttpClient.Version httpVersion; 14 | 15 | /** 16 | * @param url base URL to OPA server, containing protocol, and port (eg. http://localhost:8181) 17 | */ 18 | @ConstructorProperties({"url"}) 19 | public OpaConfiguration(String url) { 20 | this.url = url; 21 | this.httpVersion = "https".equals(URI.create(url).getScheme()) ? 22 | HttpClient.Version.HTTP_2 : 23 | HttpClient.Version.HTTP_1_1; 24 | } 25 | 26 | /** 27 | * @param url base URL to OPA server, containing protocol, and port (eg. http://localhost:8181) 28 | * @param httpVersion preferred HTTP version to use for the client 29 | */ 30 | @ConstructorProperties({"url", "httpVersion"}) 31 | public OpaConfiguration(String url, HttpClient.Version httpVersion) { 32 | this.url = url; 33 | this.httpVersion = httpVersion; 34 | } 35 | 36 | /** 37 | * @return url base URL to OPA server, containing protocol, and port 38 | */ 39 | public String getUrl() { 40 | return this.url; 41 | } 42 | 43 | /** 44 | * Get HTTP version configured for the client. If not configured will use HTTP2 for "https" scheme 45 | * and HTTP1.1 for "http" scheme. 46 | * 47 | * @return httpVersion configured for use by the client 48 | */ 49 | public HttpClient.Version getHttpVersion() { 50 | return this.httpVersion; 51 | } 52 | 53 | @Override 54 | public boolean equals(Object o) { 55 | if (this == o) return true; 56 | if (o == null || getClass() != o.getClass()) return false; 57 | OpaConfiguration that = (OpaConfiguration) o; 58 | return Objects.equals(url, that.url); 59 | } 60 | 61 | @Override 62 | public int hashCode() { 63 | return Objects.hash(url); 64 | } 65 | 66 | @Override 67 | public String toString() { 68 | return "OpaConfiguration{" + 69 | "url='" + url + '\'' + 70 | '}'; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/data/OpaDataApi.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.data; 2 | 3 | /** 4 | * This is the interface responsible for OPA Data Api, please see OPA Data API docs 5 | */ 6 | public interface OpaDataApi { 7 | /** 8 | *

Updates or creates new OPA document 9 | *

10 | * 11 | * @param document document to be created/updated 12 | * @since 0.0.1 13 | */ 14 | void createOrOverwriteDocument(OpaDocument document); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/data/OpaDataClient.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.data; 2 | 3 | import com.bisnode.opa.client.OpaClientException; 4 | import com.bisnode.opa.client.rest.ContentType; 5 | import com.bisnode.opa.client.rest.OpaRestClient; 6 | 7 | import java.net.http.HttpRequest; 8 | import java.net.http.HttpResponse; 9 | 10 | /** 11 | * @see com.bisnode.opa.client.data.OpaDataApi 12 | */ 13 | public class OpaDataClient implements OpaDataApi { 14 | private static final String DATA_ENDPOINT = "/v1/data/"; 15 | 16 | private final OpaRestClient opaRestClient; 17 | 18 | public OpaDataClient(OpaRestClient opaRestClient) { 19 | this.opaRestClient = opaRestClient; 20 | } 21 | 22 | @Override 23 | public void createOrOverwriteDocument(OpaDocument document) { 24 | try { 25 | HttpRequest request = opaRestClient.getBasicRequestBuilder(DATA_ENDPOINT + document.getPath()) 26 | .PUT(HttpRequest.BodyPublishers.ofString(document.getContent())) 27 | .header(ContentType.HEADER_NAME, ContentType.Values.APPLICATION_JSON) 28 | .build(); 29 | 30 | opaRestClient.sendRequest(request, HttpResponse.BodyHandlers.discarding()); 31 | } catch (OpaClientException exception) { 32 | throw exception; 33 | } catch (Exception e) { 34 | throw new OpaClientException(e); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/data/OpaDocument.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.data; 2 | 3 | import java.beans.ConstructorProperties; 4 | import java.util.Objects; 5 | 6 | /** 7 | * Class wrapping OPA document content and path to it 8 | */ 9 | public final class OpaDocument { 10 | private final String path; 11 | private final String content; 12 | 13 | /** 14 | * @param path Path to the document (eg. "this/is/path/to/document") 15 | * @param content Content of the document (JSON format) 16 | */ 17 | @ConstructorProperties({"path", "content"}) 18 | public OpaDocument(String path, String content) { 19 | this.path = path; 20 | this.content = content; 21 | } 22 | 23 | /** 24 | * Path to the document (eg. "this/is/path/to/document") 25 | */ 26 | public String getPath() { 27 | return this.path; 28 | } 29 | 30 | /** 31 | * Content of the document (JSON format) 32 | */ 33 | public String getContent() { 34 | return this.content; 35 | } 36 | 37 | @Override 38 | public boolean equals(Object o) { 39 | if (this == o) return true; 40 | if (o == null || getClass() != o.getClass()) return false; 41 | OpaDocument that = (OpaDocument) o; 42 | return Objects.equals(path, that.path) && 43 | Objects.equals(content, that.content); 44 | } 45 | 46 | @Override 47 | public int hashCode() { 48 | return Objects.hash(path, content); 49 | } 50 | 51 | @Override 52 | public String toString() { 53 | return "OpaDocument{" + 54 | "path='" + path + '\'' + 55 | ", content='" + content + '\'' + 56 | '}'; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/policy/OpaPolicy.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.policy; 2 | 3 | import java.beans.ConstructorProperties; 4 | import java.util.Objects; 5 | 6 | /** 7 | * Class wrapping OPA document content and path to it 8 | */ 9 | public final class OpaPolicy { 10 | private final String id; 11 | private final String content; 12 | 13 | /** 14 | * @param id Id of the policy to update, or id of newly created policy 15 | * @param content Content of the policy (written in Rego) 16 | */ 17 | @ConstructorProperties({"id", "content"}) 18 | public OpaPolicy(String id, String content) { 19 | this.id = id; 20 | this.content = content; 21 | } 22 | 23 | public String getId() { 24 | return this.id; 25 | } 26 | 27 | public String getContent() { 28 | return this.content; 29 | } 30 | 31 | @Override 32 | public boolean equals(Object o) { 33 | if (this == o) return true; 34 | if (o == null || getClass() != o.getClass()) return false; 35 | OpaPolicy opaPolicy = (OpaPolicy) o; 36 | return Objects.equals(id, opaPolicy.id) && 37 | Objects.equals(content, opaPolicy.content); 38 | } 39 | 40 | @Override 41 | public int hashCode() { 42 | return Objects.hash(id, content); 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | return "OpaPolicy{" + 48 | "id='" + id + '\'' + 49 | ", content='" + content + '\'' + 50 | '}'; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/policy/OpaPolicyApi.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.policy; 2 | 3 | /** 4 | * This is the interface responsible for OPA Policy Api @see OPA Policy API docs 5 | */ 6 | public interface OpaPolicyApi { 7 | /** 8 | *

Updates or creates new OPA policy 9 | *

10 | * 11 | * @param policy document to be created/updated 12 | * @since 0.0.1 13 | */ 14 | void createOrUpdatePolicy(OpaPolicy policy); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/policy/OpaPolicyClient.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.policy; 2 | 3 | import com.bisnode.opa.client.OpaClientException; 4 | import com.bisnode.opa.client.rest.ContentType; 5 | import com.bisnode.opa.client.rest.OpaRestClient; 6 | 7 | import java.net.http.HttpRequest; 8 | import java.net.http.HttpResponse; 9 | 10 | /** 11 | * @see com.bisnode.opa.client.policy.OpaPolicyApi 12 | */ 13 | public class OpaPolicyClient implements OpaPolicyApi { 14 | public static final String POLICY_ENDPOINT = "/v1/policies/"; 15 | 16 | private final OpaRestClient opaRestClient; 17 | 18 | public OpaPolicyClient(OpaRestClient opaRestClient) { 19 | this.opaRestClient = opaRestClient; 20 | } 21 | 22 | @Override 23 | public void createOrUpdatePolicy(OpaPolicy policy) { 24 | try { 25 | HttpRequest request = opaRestClient.getBasicRequestBuilder(POLICY_ENDPOINT + policy.getId()) 26 | .header(ContentType.HEADER_NAME, ContentType.Values.TEXT_PLAIN) 27 | .PUT(HttpRequest.BodyPublishers.ofString(policy.getContent())) 28 | .build(); 29 | 30 | opaRestClient.sendRequest(request, HttpResponse.BodyHandlers.discarding()); 31 | 32 | } catch (OpaClientException exception) { 33 | throw exception; 34 | } catch (Exception e) { 35 | throw new OpaClientException(e); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/query/OpaQueryApi.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.query; 2 | 3 | 4 | import java.lang.reflect.ParameterizedType; 5 | 6 | /** 7 | * This is the interface responsible for OPA Query API @see OPA Query API docs 8 | */ 9 | public interface OpaQueryApi { 10 | /** 11 | *

Executes simple query for document 12 | *

13 | * 14 | * @param queryForDocumentRequest request containing information needed for querying 15 | * @param responseType class of response to be returned 16 | * @return response from OPA mapped to specified class 17 | * @since 0.3.0 18 | */ 19 | R queryForDocument(QueryForDocumentRequest queryForDocumentRequest, ParameterizedType responseType); 20 | 21 | /** 22 | *

Executes simple query for document 23 | *

24 | * 25 | * @param queryForDocumentRequest request containing information needed for querying 26 | * @param responseType class of response to be returned 27 | * @return response from OPA mapped to specified class 28 | * @since 0.0.1 29 | */ 30 | R queryForDocument(QueryForDocumentRequest queryForDocumentRequest, Class responseType); 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/query/OpaQueryClient.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.query; 2 | 3 | import com.bisnode.opa.client.OpaClientException; 4 | import com.bisnode.opa.client.rest.ContentType; 5 | import com.bisnode.opa.client.rest.OpaRestClient; 6 | import com.fasterxml.jackson.databind.JavaType; 7 | import com.fasterxml.jackson.databind.type.TypeFactory; 8 | 9 | import java.lang.reflect.ParameterizedType; 10 | import java.lang.reflect.Type; 11 | import java.net.http.HttpRequest; 12 | import java.util.Arrays; 13 | import java.util.Objects; 14 | 15 | /** 16 | * @see com.bisnode.opa.client.query.OpaQueryApi 17 | */ 18 | public class OpaQueryClient implements OpaQueryApi { 19 | private static final String EVALUATE_POLICY_ENDPOINT = "/v1/data/"; 20 | private static final String EMPTY_RESULT_ERROR_MESSAGE = "Result is empty, it may indicate that document under path [%s] does not exist"; 21 | 22 | private final OpaRestClient opaRestClient; 23 | 24 | public OpaQueryClient(OpaRestClient opaRestClient) { 25 | this.opaRestClient = opaRestClient; 26 | } 27 | 28 | /** 29 | *

Executes simple query for document 30 | *

31 | * 32 | * @param queryForDocumentRequest request containing information needed for querying 33 | * @param responseType class of response to be returned 34 | * @return response from OPA mapped to specified class 35 | * @since 0.0.1 36 | */ 37 | public R queryForDocument(QueryForDocumentRequest queryForDocumentRequest, Class responseType) { 38 | return internalQueryForDocument(queryForDocumentRequest, responseType); 39 | } 40 | 41 | @Override 42 | public R queryForDocument(QueryForDocumentRequest queryForDocumentRequest, ParameterizedType responseType) { 43 | return internalQueryForDocument(queryForDocumentRequest, responseType); 44 | } 45 | 46 | private R internalQueryForDocument(QueryForDocumentRequest queryForDocumentRequest, Type responseType) { 47 | try { 48 | OpaQueryForDocumentRequest opaQueryForDocumentRequest = new OpaQueryForDocumentRequest(queryForDocumentRequest.getInput()); 49 | 50 | HttpRequest request = opaRestClient.getBasicRequestBuilder(EVALUATE_POLICY_ENDPOINT + queryForDocumentRequest.getPath()) 51 | .header(ContentType.HEADER_NAME, ContentType.Values.APPLICATION_JSON) 52 | .POST(opaRestClient.getJsonBodyPublisher(opaQueryForDocumentRequest)) 53 | .build(); 54 | 55 | JavaType opaResponseType = getResponseJavaType(responseType); 56 | 57 | R result = opaRestClient.sendRequest(request, opaRestClient.>getJsonBodyHandler(opaResponseType)) 58 | .body() 59 | .get() 60 | .getResult(); 61 | if (Objects.isNull(result)) { 62 | throw new OpaClientException(String.format(EMPTY_RESULT_ERROR_MESSAGE, queryForDocumentRequest.getPath())); 63 | } 64 | return result; 65 | } catch (OpaClientException exception) { 66 | throw exception; 67 | } catch (Exception e) { 68 | throw new OpaClientException(e); 69 | } 70 | } 71 | 72 | private JavaType getResponseJavaType(Type responseType) 73 | throws ClassNotFoundException { 74 | JavaType opaResponseType; 75 | if (responseType instanceof ParameterizedType) { 76 | ParameterizedType parameterizedType = (ParameterizedType) responseType; 77 | Class[] classes = Arrays.stream(parameterizedType.getActualTypeArguments()).map(type -> { 78 | try { 79 | return Class.forName(type.getTypeName()); 80 | } catch (ClassNotFoundException e) { 81 | throw new IllegalArgumentException("Cannot find class configured in the responseType ".concat(type.getTypeName()), e); 82 | } 83 | }).toArray(Class[]::new); 84 | 85 | JavaType opaType = TypeFactory.defaultInstance().constructParametricType(Class.forName(parameterizedType.getRawType().getTypeName()), classes); 86 | opaResponseType = TypeFactory.defaultInstance().constructParametricType(OpaQueryForDocumentResponse.class, opaType); 87 | } else { 88 | opaResponseType = TypeFactory.defaultInstance().constructParametricType(OpaQueryForDocumentResponse.class, Class.forName(responseType.getTypeName())); 89 | } 90 | return opaResponseType; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/query/OpaQueryForDocumentRequest.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.query; 2 | 3 | import java.beans.ConstructorProperties; 4 | import java.util.Objects; 5 | 6 | final class OpaQueryForDocumentRequest { 7 | private final Object input; 8 | 9 | @ConstructorProperties({"input"}) 10 | public OpaQueryForDocumentRequest(Object input) { 11 | this.input = input; 12 | } 13 | 14 | public Object getInput() { 15 | return this.input; 16 | } 17 | 18 | @Override 19 | public boolean equals(Object o) { 20 | if (this == o) return true; 21 | if (o == null || getClass() != o.getClass()) return false; 22 | OpaQueryForDocumentRequest that = (OpaQueryForDocumentRequest) o; 23 | return Objects.equals(input, that.input); 24 | } 25 | 26 | @Override 27 | public int hashCode() { 28 | return Objects.hash(input); 29 | } 30 | 31 | @Override 32 | public String toString() { 33 | return "OpaQueryForDocumentRequest{" + 34 | "input=" + input + 35 | '}'; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/query/OpaQueryForDocumentResponse.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.query; 2 | 3 | import java.beans.ConstructorProperties; 4 | import java.util.Objects; 5 | 6 | final class OpaQueryForDocumentResponse { 7 | private final T result; 8 | 9 | @ConstructorProperties({"result"}) 10 | public OpaQueryForDocumentResponse(T result) { 11 | this.result = result; 12 | } 13 | 14 | public T getResult() { 15 | return this.result; 16 | } 17 | 18 | @Override 19 | public boolean equals(Object o) { 20 | if (this == o) return true; 21 | if (o == null || getClass() != o.getClass()) return false; 22 | OpaQueryForDocumentResponse that = (OpaQueryForDocumentResponse) o; 23 | return Objects.equals(result, that.result); 24 | } 25 | 26 | @Override 27 | public int hashCode() { 28 | return Objects.hash(result); 29 | } 30 | 31 | @Override 32 | public String toString() { 33 | return "OpaQueryForDocumentResponse{" + 34 | "result=" + result + 35 | '}'; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/query/QueryForDocumentRequest.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.query; 2 | 3 | import java.beans.ConstructorProperties; 4 | import java.util.Objects; 5 | 6 | /** 7 | * Class wrapping OPA query response 8 | */ 9 | public final class QueryForDocumentRequest { 10 | private final Object input; 11 | private final String path; 12 | 13 | /** 14 | * @param input Query input 15 | * @param path Path to the document (eg. "this/is/path/to/document") 16 | */ 17 | @ConstructorProperties({"input", "path"}) 18 | public QueryForDocumentRequest(Object input, String path) { 19 | this.input = input; 20 | this.path = path; 21 | } 22 | 23 | public Object getInput() { 24 | return this.input; 25 | } 26 | 27 | public String getPath() { 28 | return this.path; 29 | } 30 | 31 | @Override 32 | public boolean equals(Object o) { 33 | if (this == o) return true; 34 | if (o == null || getClass() != o.getClass()) return false; 35 | QueryForDocumentRequest that = (QueryForDocumentRequest) o; 36 | return Objects.equals(input, that.input) && 37 | Objects.equals(path, that.path); 38 | } 39 | 40 | @Override 41 | public int hashCode() { 42 | return Objects.hash(input, path); 43 | } 44 | 45 | @Override 46 | public String toString() { 47 | return "QueryForDocumentRequest{" + 48 | "input=" + input + 49 | ", path='" + path + '\'' + 50 | '}'; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/rest/ContentType.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest; 2 | 3 | /** 4 | * Content-Type header related information 5 | */ 6 | public interface ContentType { 7 | interface Values { 8 | String APPLICATION_JSON = "application/json"; 9 | String TEXT_PLAIN = "text/plain"; 10 | } 11 | 12 | String HEADER_NAME = "Content-Type"; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/rest/JsonBodyHandler.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest; 2 | 3 | import com.fasterxml.jackson.databind.JavaType; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.io.UncheckedIOException; 9 | import java.net.http.HttpResponse; 10 | import java.util.function.Function; 11 | import java.util.function.Supplier; 12 | 13 | class JsonBodyHandler implements HttpResponse.BodyHandler> { 14 | 15 | private final JavaType responseType; 16 | private final ObjectMapper objectMapper; 17 | 18 | public JsonBodyHandler(JavaType responseType, ObjectMapper objectMapper) { 19 | this.responseType = responseType; 20 | this.objectMapper = objectMapper; 21 | } 22 | 23 | public static HttpResponse.BodySubscriber> asJSON(JavaType responseType, ObjectMapper objectMapper) { 24 | HttpResponse.BodySubscriber upstream = HttpResponse.BodySubscribers.ofInputStream(); 25 | 26 | return HttpResponse.BodySubscribers.mapping(upstream, createMapper(responseType, objectMapper)); 27 | } 28 | 29 | private static Function> createMapper(JavaType responseType, ObjectMapper objectMapper) { 30 | return is -> () -> mapToJson(responseType, is, objectMapper); 31 | } 32 | 33 | private static W mapToJson(JavaType responseType, InputStream is, ObjectMapper objectMapper) { 34 | try (InputStream inputStream = is) { 35 | return objectMapper.readValue(inputStream, responseType); 36 | } catch (IOException e) { 37 | throw new UncheckedIOException(e); 38 | } 39 | } 40 | 41 | @Override 42 | public HttpResponse.BodySubscriber> apply(HttpResponse.ResponseInfo responseInfo) { 43 | return asJSON(responseType, objectMapper); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/rest/JsonBodyPublisher.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest; 2 | 3 | 4 | import com.fasterxml.jackson.core.JsonProcessingException; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | 7 | import java.net.http.HttpRequest; 8 | import java.nio.ByteBuffer; 9 | import java.util.concurrent.Flow; 10 | 11 | class JsonBodyPublisher implements HttpRequest.BodyPublisher { 12 | 13 | private final HttpRequest.BodyPublisher stringBodyPublisher; 14 | 15 | public static HttpRequest.BodyPublisher of(Object body, ObjectMapper objectMapper) throws JsonProcessingException { 16 | return new JsonBodyPublisher(body, objectMapper); 17 | } 18 | 19 | public JsonBodyPublisher(Object body, ObjectMapper objectMapper) throws JsonProcessingException { 20 | this.stringBodyPublisher = HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(body)); 21 | } 22 | 23 | @Override 24 | public long contentLength() { 25 | return stringBodyPublisher.contentLength(); 26 | } 27 | 28 | @Override 29 | public void subscribe(Flow.Subscriber subscriber) { 30 | stringBodyPublisher.subscribe(subscriber); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/rest/ObjectMapperFactory.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest; 2 | 3 | import com.fasterxml.jackson.databind.DeserializationFeature; 4 | import com.fasterxml.jackson.databind.ObjectMapper; 5 | 6 | /** 7 | * Creates and configures {@link ObjectMapper} 8 | */ 9 | public class ObjectMapperFactory { 10 | 11 | private static final ObjectMapperFactory instance = new ObjectMapperFactory(); 12 | 13 | private ObjectMapper objectMapper = createConfiguredObjectMapper(); 14 | 15 | public ObjectMapper create() { 16 | return objectMapper; 17 | } 18 | 19 | private static ObjectMapper createConfiguredObjectMapper() { 20 | return new ObjectMapper() 21 | .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 22 | } 23 | 24 | public static ObjectMapperFactory getInstance() { 25 | return instance; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/rest/OpaRestClient.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest; 2 | 3 | import com.bisnode.opa.client.OpaClientException; 4 | import com.bisnode.opa.client.OpaConfiguration; 5 | import com.bisnode.opa.client.rest.url.OpaUrl; 6 | import com.fasterxml.jackson.core.JsonProcessingException; 7 | import com.fasterxml.jackson.databind.JavaType; 8 | import com.fasterxml.jackson.databind.ObjectMapper; 9 | 10 | import java.io.IOException; 11 | import java.net.SocketException; 12 | import java.net.http.HttpClient; 13 | import java.net.http.HttpRequest; 14 | import java.net.http.HttpResponse; 15 | 16 | /** 17 | * Class wrapping Java's HttpClient in OPA and JSON requests 18 | */ 19 | public class OpaRestClient { 20 | 21 | private final OpaConfiguration opaConfiguration; 22 | private final HttpClient httpClient; 23 | private final ObjectMapper objectMapper; 24 | 25 | public OpaRestClient(OpaConfiguration opaConfiguration, HttpClient httpClient, ObjectMapper objectMapper) { 26 | this.opaConfiguration = opaConfiguration; 27 | this.httpClient = httpClient; 28 | this.objectMapper = objectMapper; 29 | } 30 | 31 | /** 32 | * Create {@link java.net.http.HttpRequest.Builder} with configured url using provided endpoint 33 | * 34 | * @param endpoint desired opa endpoint 35 | * @throws OpaClientException if URL or endpoint is invalid 36 | */ 37 | public HttpRequest.Builder getBasicRequestBuilder(String endpoint) { 38 | OpaUrl url = OpaUrl.of(opaConfiguration.getUrl(), endpoint).normalized(); 39 | return HttpRequest.newBuilder(url.toUri()); 40 | } 41 | 42 | /** 43 | * Gets {@link java.net.http.HttpRequest.BodyPublisher} that is capable of serializing to JSON 44 | * 45 | * @param body object to be serialized 46 | */ 47 | public HttpRequest.BodyPublisher getJsonBodyPublisher(Object body) throws JsonProcessingException { 48 | return JsonBodyPublisher.of(body, objectMapper); 49 | } 50 | 51 | /** 52 | * Gets {@link JsonBodyHandler} that will deserialize JSON to desired class type 53 | * 54 | * @param responseType desired response type 55 | * @param desired response type 56 | */ 57 | public JsonBodyHandler getJsonBodyHandler(JavaType responseType) { 58 | return new JsonBodyHandler<>(responseType, objectMapper); 59 | } 60 | 61 | /** 62 | * Sends provided request and returns response mapped using {@link java.net.http.HttpResponse.BodyHandler} 63 | * 64 | * @param request request to be sent 65 | * @param bodyHandler handler that indicates how to transform incoming body 66 | * @param Type of returned body 67 | * @return response from HttpRequest 68 | * @throws IOException is propagated from {@link HttpClient} 69 | * @throws InterruptedException is propagated from {@link HttpClient} 70 | */ 71 | public HttpResponse sendRequest(HttpRequest request, HttpResponse.BodyHandler bodyHandler) throws IOException, InterruptedException { 72 | try { 73 | HttpResponse response = httpClient.send(request, bodyHandler); 74 | if (response.statusCode() >= 300) { 75 | throw new OpaClientException("Error in communication with OPA server, status code: " + response.statusCode()); 76 | } 77 | return response; 78 | } catch (SocketException exception) { 79 | throw new OpaServerConnectionException("Could not reach OPA server", exception); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/rest/OpaServerConnectionException.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest; 2 | 3 | import com.bisnode.opa.client.OpaClient; 4 | import com.bisnode.opa.client.OpaClientException; 5 | 6 | /** 7 | * Exception returned by {@link OpaClient} 8 | * Exception which is thrown when {@link OpaClient} cannot reach Open Policy Agent server. 9 | */ 10 | public class OpaServerConnectionException extends OpaClientException { 11 | public OpaServerConnectionException() { 12 | } 13 | 14 | public OpaServerConnectionException(String message) { 15 | super(message); 16 | } 17 | 18 | public OpaServerConnectionException(String message, Throwable cause) { 19 | super(message, cause); 20 | } 21 | 22 | public OpaServerConnectionException(Throwable cause) { 23 | super(cause); 24 | } 25 | 26 | public OpaServerConnectionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 27 | super(message, cause, enableSuppression, writableStackTrace); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/rest/url/InvalidEndpointException.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest.url; 2 | 3 | import com.bisnode.opa.client.OpaClientException; 4 | 5 | public class InvalidEndpointException extends OpaClientException { 6 | public InvalidEndpointException() { 7 | super(); 8 | } 9 | 10 | public InvalidEndpointException(String message) { 11 | super(message); 12 | } 13 | 14 | public InvalidEndpointException(String message, Throwable cause) { 15 | super(message, cause); 16 | } 17 | 18 | public InvalidEndpointException(Throwable cause) { 19 | super(cause); 20 | } 21 | 22 | protected InvalidEndpointException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 23 | super(message, cause, enableSuppression, writableStackTrace); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/bisnode/opa/client/rest/url/OpaUrl.java: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest.url; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import java.net.URI; 7 | import java.util.Optional; 8 | import java.util.function.Function; 9 | 10 | /** 11 | * Contains request URL which is then used to call OPA server 12 | * Provides methods useful in URL validation/manipulation 13 | */ 14 | public class OpaUrl { 15 | private static final Logger log = LoggerFactory.getLogger(OpaUrl.class); 16 | private final String value; 17 | 18 | /** 19 | * Creates OpaUrl 20 | * 21 | * @param serverUrl URL of OPA Server 22 | * @param endpoint endpoint path 23 | * @return created OpaUrl 24 | */ 25 | public static OpaUrl of(String serverUrl, String endpoint) { 26 | return new OpaUrl(urlOf(serverUrl, endpoint)); 27 | } 28 | 29 | private static String urlOf(String url, String endpoint) { 30 | return url + "/" + Optional.ofNullable(endpoint).orElseThrow(() -> new InvalidEndpointException("Invalid endpoint: " + endpoint)); 31 | } 32 | 33 | /** 34 | * @return String value of OPA URL 35 | */ 36 | public String getValue() { 37 | return value; 38 | } 39 | 40 | /** 41 | * @return Normalized version of URL, removing multiple and trailing slashes 42 | */ 43 | public OpaUrl normalized() { 44 | String normalizedValue = normalize(value); 45 | return new OpaUrl(normalizedValue); 46 | } 47 | 48 | /** 49 | * @return OpaUrl transformed to URI 50 | */ 51 | public URI toUri() { 52 | return URI.create(value); 53 | } 54 | 55 | private String normalize(String inputUrl) { 56 | String normalized = removeExtraSlashes() 57 | .andThen(removeTrailingSlash()) 58 | .apply(inputUrl.trim()); 59 | if (!inputUrl.equals(normalized)) { 60 | log.debug("Supplied URL [{}] is malformed, has to be normalized", inputUrl); 61 | } 62 | return normalized; 63 | } 64 | 65 | private Function removeTrailingSlash() { 66 | return (input) -> input.endsWith("/") ? input.substring(0, input.length() - 1) : input; 67 | } 68 | 69 | private Function removeExtraSlashes() { 70 | return (input) -> input.replaceAll("([^:])//+", "$1/"); 71 | } 72 | 73 | private OpaUrl(String value) { 74 | this.value = value; 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/test/groovy/com/bisnode/opa/client/ManagingDocumentSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client 2 | 3 | import com.bisnode.opa.client.data.OpaDataApi 4 | import com.bisnode.opa.client.data.OpaDocument 5 | import com.bisnode.opa.client.query.OpaQueryApi 6 | import com.bisnode.opa.client.rest.ContentType 7 | import com.bisnode.opa.client.rest.OpaServerConnectionException 8 | import com.github.tomakehurst.wiremock.WireMockServer 9 | import spock.lang.Shared 10 | import spock.lang.Specification 11 | import spock.lang.Subject 12 | import spock.lang.Unroll 13 | 14 | import static com.bisnode.opa.client.rest.ContentType.Values.APPLICATION_JSON 15 | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse 16 | import static com.github.tomakehurst.wiremock.client.WireMock.equalTo 17 | import static com.github.tomakehurst.wiremock.client.WireMock.put 18 | import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor 19 | import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo 20 | 21 | class ManagingDocumentSpec extends Specification { 22 | 23 | private static int PORT = 8181 24 | 25 | private String url = "http://localhost:$PORT" 26 | @Shared 27 | private WireMockServer wireMockServer = new WireMockServer(PORT) 28 | @Subject 29 | private OpaDataApi client = OpaClient.builder().opaConfiguration(url).build() 30 | 31 | def DOCUMENT = '{"example": {"flag": true}}' 32 | 33 | def setupSpec() { 34 | wireMockServer.start() 35 | } 36 | 37 | def cleanupSpec() { 38 | wireMockServer.stop() 39 | } 40 | 41 | def 'should perform successful policy create or update'() { 42 | given: 43 | def documentPath = 'somePath' 44 | def endpoint = "/v1/data/$documentPath" 45 | wireMockServer 46 | .stubFor(put(urlEqualTo(endpoint)) 47 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 48 | .willReturn(aResponse() 49 | .withStatus(200) 50 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 51 | .withBody('{}'))) 52 | when: 53 | client.createOrOverwriteDocument(new OpaDocument(documentPath, DOCUMENT)) 54 | then: 55 | noExceptionThrown() 56 | wireMockServer.verify(putRequestedFor(urlEqualTo(endpoint)) 57 | .withRequestBody(equalTo(DOCUMENT)) 58 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON))) 59 | } 60 | 61 | @Unroll 62 | def 'should throw OpaClientException on status code = #status'() { 63 | given: 64 | def documentPath = 'somePath' 65 | def endpoint = "/v1/data/$documentPath" 66 | wireMockServer 67 | .stubFor(put(urlEqualTo(endpoint)) 68 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 69 | .willReturn(aResponse() 70 | .withStatus(status) 71 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 72 | .withBody('{}'))) 73 | when: 74 | client.createOrOverwriteDocument(new OpaDocument(documentPath, DOCUMENT)) 75 | then: 76 | thrown(OpaClientException) 77 | wireMockServer.verify(putRequestedFor(urlEqualTo(endpoint)) 78 | .withRequestBody(equalTo(DOCUMENT)) 79 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON))) 80 | where: 81 | status << [400, 404, 500] 82 | } 83 | 84 | 85 | def 'should throw OpaServerConnectionException when server is down'() { 86 | given: 87 | def documentPath = 'somePath' 88 | def fakeUrl = 'http://localhost:8182' 89 | OpaQueryApi newClient = OpaClient.builder().opaConfiguration(fakeUrl).build() 90 | when: 91 | newClient.createOrOverwriteDocument(new OpaDocument(documentPath, DOCUMENT)) 92 | then: 93 | thrown(OpaServerConnectionException) 94 | 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/test/groovy/com/bisnode/opa/client/ManagingPolicySpec.groovy: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client 2 | 3 | import com.bisnode.opa.client.policy.OpaPolicy 4 | import com.bisnode.opa.client.policy.OpaPolicyApi 5 | import com.bisnode.opa.client.query.OpaQueryApi 6 | import com.bisnode.opa.client.rest.ContentType 7 | import com.bisnode.opa.client.rest.OpaServerConnectionException 8 | import com.github.tomakehurst.wiremock.WireMockServer 9 | import spock.lang.Shared 10 | import spock.lang.Specification 11 | import spock.lang.Subject 12 | import spock.lang.Unroll 13 | 14 | import static com.bisnode.opa.client.rest.ContentType.Values.APPLICATION_JSON 15 | import static com.bisnode.opa.client.rest.ContentType.Values.TEXT_PLAIN 16 | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse 17 | import static com.github.tomakehurst.wiremock.client.WireMock.equalTo 18 | import static com.github.tomakehurst.wiremock.client.WireMock.put 19 | import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor 20 | import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo 21 | 22 | class ManagingPolicySpec extends Specification { 23 | 24 | private static int PORT = 8181 25 | private static String url = "http://localhost:$PORT" 26 | 27 | @Shared 28 | private WireMockServer wireMockServer = new WireMockServer(PORT) 29 | @Subject 30 | private OpaPolicyApi client = OpaClient.builder().opaConfiguration(url).build() 31 | 32 | def POLICY = """package example 33 | default allow = false 34 | 35 | allow = true { 36 | input.body == "Looks good" 37 | }""" 38 | 39 | def setupSpec() { 40 | wireMockServer.start() 41 | } 42 | 43 | def cleanupSpec() { 44 | wireMockServer.stop() 45 | } 46 | 47 | def 'should perform successful policy create or update'() { 48 | given: 49 | def policyId = '12345' 50 | def endpoint = "/v1/policies/$policyId" 51 | wireMockServer 52 | .stubFor(put(urlEqualTo(endpoint)) 53 | .withHeader(ContentType.HEADER_NAME, equalTo(TEXT_PLAIN)) 54 | .willReturn(aResponse() 55 | .withStatus(200) 56 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 57 | .withBody('{}'))) 58 | when: 59 | client.createOrUpdatePolicy(new OpaPolicy(policyId, POLICY)) 60 | then: 61 | noExceptionThrown() 62 | wireMockServer.verify(putRequestedFor(urlEqualTo(endpoint)) 63 | .withRequestBody(equalTo(POLICY)) 64 | .withHeader(ContentType.HEADER_NAME, equalTo(TEXT_PLAIN))) 65 | } 66 | 67 | @Unroll 68 | def 'should throw OpaClientException on status code = #status'() { 69 | given: 70 | def policyId = '12345' 71 | def endpoint = "/v1/policies/$policyId" 72 | wireMockServer 73 | .stubFor(put(urlEqualTo(endpoint)) 74 | .withHeader(ContentType.HEADER_NAME, equalTo(TEXT_PLAIN)) 75 | .willReturn(aResponse() 76 | .withStatus(status) 77 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 78 | .withBody('{}'))) 79 | when: 80 | client.createOrUpdatePolicy(new OpaPolicy(policyId, POLICY)) 81 | then: 82 | thrown(OpaClientException) 83 | wireMockServer.verify(putRequestedFor(urlEqualTo(endpoint)) 84 | .withRequestBody(equalTo(POLICY)) 85 | .withHeader(ContentType.HEADER_NAME, equalTo(TEXT_PLAIN))) 86 | where: 87 | status << [400, 500] 88 | } 89 | 90 | def 'should throw OpaServerConnectionException when server is down'() { 91 | given: 92 | def policyId = '12345' 93 | def fakeUrl = 'http://localhost:8182' 94 | OpaQueryApi newClient = OpaClient.builder().opaConfiguration(fakeUrl).build() 95 | when: 96 | newClient.createOrUpdatePolicy(new OpaPolicy(policyId, POLICY)) 97 | then: 98 | thrown(OpaServerConnectionException) 99 | 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/test/groovy/com/bisnode/opa/client/OpaClientBuilderSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client 2 | 3 | 4 | import com.bisnode.opa.client.query.QueryForDocumentRequest 5 | import com.bisnode.opa.client.rest.ContentType 6 | import com.fasterxml.jackson.databind.ObjectMapper 7 | import com.github.tomakehurst.wiremock.WireMockServer 8 | import spock.lang.Shared 9 | import spock.lang.Specification 10 | 11 | import static com.bisnode.opa.client.rest.ContentType.Values.APPLICATION_JSON 12 | import static com.github.tomakehurst.wiremock.client.WireMock.* 13 | 14 | class OpaClientBuilderSpec extends Specification { 15 | 16 | private static int PORT = 8181 17 | private static String url = "http://localhost:$PORT" 18 | 19 | @Shared 20 | private WireMockServer wireMockServer = new WireMockServer(PORT) 21 | 22 | def setupSpec() { 23 | wireMockServer.start() 24 | } 25 | 26 | def cleanupSpec() { 27 | wireMockServer.stop() 28 | } 29 | 30 | def 'should configure OpaClient with custom ObjectMapper'() { 31 | 32 | given: 33 | def objectMapper = Spy(ObjectMapper) 34 | def path = 'someDocument' 35 | def endpoint = "/v1/data/$path" 36 | wireMockServer 37 | .stubFor(post(urlEqualTo(endpoint)) 38 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 39 | .willReturn(aResponse() 40 | .withStatus(200) 41 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 42 | .withBody('{"result": {"authorized": true}}'))) 43 | def opaClient = OpaClient.builder() 44 | .opaConfiguration(url) 45 | .objectMapper(objectMapper) 46 | .build(); 47 | 48 | when: 49 | opaClient.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), Object.class) 50 | 51 | then: 52 | 1 * objectMapper.writeValueAsString(_) 53 | } 54 | 55 | def 'should revert to default ObjectMapper if null ObjectMapper supplied'() { 56 | given: 57 | def path = 'someDocument' 58 | def endpoint = "/v1/data/$path" 59 | wireMockServer 60 | .stubFor(post(urlEqualTo(endpoint)) 61 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 62 | .willReturn(aResponse() 63 | .withStatus(200) 64 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 65 | .withBody('{"result": {"authorized": true}}'))) 66 | def opaClient = OpaClient.builder() 67 | .opaConfiguration(url) 68 | .objectMapper(null) 69 | .build(); 70 | 71 | when: 72 | def result = opaClient.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), Map.class) 73 | 74 | then: 75 | result != null 76 | result.get("authorized") == true 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/test/groovy/com/bisnode/opa/client/QueryingForDocumentSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client 2 | 3 | import com.bisnode.opa.client.query.OpaQueryApi 4 | import com.bisnode.opa.client.query.QueryForDocumentRequest 5 | import com.bisnode.opa.client.rest.ContentType 6 | import com.bisnode.opa.client.rest.OpaServerConnectionException 7 | import com.github.tomakehurst.wiremock.WireMockServer 8 | import org.apache.commons.lang3.reflect.TypeUtils 9 | import spock.lang.Shared 10 | import spock.lang.Specification 11 | import spock.lang.Subject 12 | import spock.lang.Unroll 13 | 14 | import static com.bisnode.opa.client.rest.ContentType.Values.APPLICATION_JSON 15 | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse 16 | import static com.github.tomakehurst.wiremock.client.WireMock.equalTo 17 | import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson 18 | import static com.github.tomakehurst.wiremock.client.WireMock.post 19 | import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor 20 | import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo 21 | 22 | class QueryingForDocumentSpec extends Specification { 23 | 24 | private static int PORT = 8181 25 | private static String url = "http://localhost:$PORT" 26 | 27 | @Shared 28 | private WireMockServer wireMockServer = new WireMockServer(PORT) 29 | 30 | @Subject 31 | private OpaQueryApi client = OpaClient.builder().opaConfiguration(url).build() 32 | 33 | def setupSpec() { 34 | wireMockServer.start() 35 | } 36 | 37 | def cleanupSpec() { 38 | wireMockServer.stop() 39 | } 40 | 41 | def 'should perform successful document evaluation'() { 42 | given: 43 | def path = 'someDocument' 44 | def endpoint = "/v1/data/$path" 45 | wireMockServer 46 | .stubFor(post(urlEqualTo(endpoint)) 47 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 48 | .willReturn(aResponse() 49 | .withStatus(200) 50 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 51 | .withBody('{"result": {"allow":"true"}}'))) 52 | when: 53 | def result = client.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), ValidationResult.class) 54 | then: 55 | noExceptionThrown() 56 | wireMockServer.verify(postRequestedFor(urlEqualTo(endpoint)) 57 | .withRequestBody(equalToJson('{"input":{"shouldPass": true}}')) 58 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON))) 59 | result.allow 60 | } 61 | 62 | def 'should return empty object when empty json returned from opa'() { 63 | given: 64 | def path = 'someDocument' 65 | def endpoint = "/v1/data/$path" 66 | wireMockServer 67 | .stubFor(post(urlEqualTo(endpoint)) 68 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 69 | .willReturn(aResponse() 70 | .withStatus(200) 71 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 72 | .withBody('{"result": {}}'))) 73 | when: 74 | def result = client.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), ValidationResult.class) 75 | then: 76 | noExceptionThrown() 77 | wireMockServer.verify(postRequestedFor(urlEqualTo(endpoint)) 78 | .withRequestBody(equalToJson('{"input":{"shouldPass": true}}')) 79 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON))) 80 | result.allow == null 81 | } 82 | 83 | def 'should not fail when returned more properties than mapping requires'() { 84 | given: 85 | def path = 'someDocument' 86 | def endpoint = "/v1/data/$path" 87 | wireMockServer 88 | .stubFor(post(urlEqualTo(endpoint)) 89 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 90 | .willReturn(aResponse() 91 | .withStatus(200) 92 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 93 | .withBody('{"result": {"authorized": "true", "allow": true}}, "otherStuff": true'))) 94 | when: 95 | def result = client.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), ValidationResult.class) 96 | then: 97 | noExceptionThrown() 98 | wireMockServer.verify(postRequestedFor(urlEqualTo(endpoint)) 99 | .withRequestBody(equalToJson('{"input":{"shouldPass": true}}')) 100 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON))) 101 | result.allow 102 | } 103 | 104 | @Unroll 105 | def 'should throw OpaClientException on status code = #status'() { 106 | given: 107 | def path = 'someDocument' 108 | def endpoint = "/v1/data/$path" 109 | wireMockServer 110 | .stubFor(post(urlEqualTo(endpoint)) 111 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 112 | .willReturn(aResponse() 113 | .withStatus(status) 114 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON))) 115 | when: 116 | client.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), ValidationResult.class) 117 | then: 118 | thrown(OpaClientException) 119 | wireMockServer.verify(postRequestedFor(urlEqualTo(endpoint)) 120 | .withRequestBody(equalToJson('{"input":{"shouldPass": true}}')) 121 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON))) 122 | where: 123 | status << [400, 404, 500] 124 | } 125 | 126 | 127 | 128 | def 'should handle collection with generics in response'() { 129 | given: 130 | def path = 'someDocument' 131 | def endpoint = "/v1/data/$path" 132 | 133 | 134 | wireMockServer 135 | .stubFor(post(urlEqualTo(endpoint)) 136 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 137 | .willReturn(aResponse() 138 | .withStatus(200) 139 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 140 | .withBody('{"result": [{"allow": true},{"allow": false}]}'))) 141 | when: 142 | 143 | def type = TypeUtils.parameterize(List.class,ValidationResult.class); 144 | List result = client.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), type) 145 | then: 146 | ValidationResult element = result[0] 147 | element.allow 148 | } 149 | 150 | def 'should handle nested classes in response'() { 151 | given: 152 | def path = 'someDocument' 153 | def endpoint = "/v1/data/$path" 154 | wireMockServer 155 | .stubFor(post(urlEqualTo(endpoint)) 156 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 157 | .willReturn(aResponse() 158 | .withStatus(200) 159 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 160 | .withBody('{"result": {"validationResult": {"allow": true}}}'))) 161 | when: 162 | def result = client.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), ComplexValidationResult.class) 163 | then: 164 | result.getClass() == ComplexValidationResult.class 165 | result.validationResult.allow 166 | } 167 | 168 | def 'should map missing properties to null'() { 169 | given: 170 | def path = 'someDocument' 171 | def endpoint = "/v1/data/$path" 172 | wireMockServer 173 | .stubFor(post(urlEqualTo(endpoint)) 174 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 175 | .willReturn(aResponse() 176 | .withStatus(200) 177 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 178 | .withBody('{"result": {"validationResult": {"authorized": true}}}'))) 179 | when: 180 | def result = client.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), ComplexValidationResult.class) 181 | then: 182 | result.getClass() == ComplexValidationResult.class 183 | result.validationResult.allow == null 184 | } 185 | 186 | def 'should throw exception when document is empty'() { 187 | given: 188 | def path = 'someDocument' 189 | def endpoint = "/v1/data/$path" 190 | wireMockServer 191 | .stubFor(post(urlEqualTo(endpoint)) 192 | .withHeader(ContentType.HEADER_NAME, equalTo(APPLICATION_JSON)) 193 | .willReturn(aResponse() 194 | .withStatus(200) 195 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 196 | .withBody('{}'))) 197 | when: 198 | client.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), ComplexValidationResult.class) 199 | then: 200 | thrown(OpaClientException) 201 | 202 | } 203 | 204 | def 'should throw OpaServerConnectionException when server is down'() { 205 | given: 206 | def path = 'someDocument' 207 | def fakeUrl = 'http://localhost:8182' 208 | OpaQueryApi newClient = OpaClient.builder().opaConfiguration(fakeUrl).build() 209 | when: 210 | newClient.queryForDocument(new QueryForDocumentRequest([shouldPass: true], path), ComplexValidationResult.class) 211 | then: 212 | thrown(OpaServerConnectionException) 213 | 214 | } 215 | 216 | static final class ValidationResult { 217 | Boolean allow 218 | } 219 | 220 | static final class ComplexValidationResult { 221 | ValidationResult validationResult 222 | } 223 | 224 | } 225 | -------------------------------------------------------------------------------- /src/test/groovy/com/bisnode/opa/client/rest/ObjectMapperFactorySpec.groovy: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest 2 | 3 | import com.fasterxml.jackson.databind.DeserializationFeature 4 | import spock.lang.Specification 5 | 6 | class ObjectMapperFactorySpec extends Specification { 7 | 8 | def 'should create ObjectMapperFactory instance only once'() { 9 | when: 10 | def firstCall = ObjectMapperFactory.getInstance() 11 | def secondCall = ObjectMapperFactory.getInstance() 12 | then: 13 | firstCall == secondCall 14 | } 15 | 16 | def 'should set FAIL_ON_UNKNOWN_PROPERTIES to false in created ObjectMapper'() { 17 | when: 18 | def result = ObjectMapperFactory.getInstance().create() 19 | then: 20 | !result.deserializationConfig.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/test/groovy/com/bisnode/opa/client/rest/OpaRestClientSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest 2 | 3 | import com.bisnode.opa.client.OpaClientException 4 | import com.bisnode.opa.client.OpaConfiguration 5 | import com.fasterxml.jackson.databind.ObjectMapper 6 | import com.github.tomakehurst.wiremock.WireMockServer 7 | import spock.lang.Shared 8 | import spock.lang.Specification 9 | import spock.lang.Subject 10 | 11 | import java.net.http.HttpClient 12 | import java.net.http.HttpResponse 13 | 14 | import static com.bisnode.opa.client.rest.ContentType.Values.APPLICATION_JSON 15 | import static com.github.tomakehurst.wiremock.client.WireMock.aResponse 16 | import static com.github.tomakehurst.wiremock.client.WireMock.any 17 | import static com.github.tomakehurst.wiremock.client.WireMock.anyUrl 18 | import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor 19 | import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo 20 | 21 | class OpaRestClientSpec extends Specification { 22 | 23 | private static int PORT = 8181 24 | 25 | private String url = "http://localhost:$PORT" 26 | @Shared 27 | private WireMockServer wireMockServer = new WireMockServer(PORT) 28 | @Subject 29 | private OpaRestClient client = new OpaRestClient(new OpaConfiguration(url), HttpClient.newHttpClient(), new ObjectMapper()) 30 | 31 | def setupSpec() { 32 | wireMockServer.start() 33 | } 34 | 35 | def cleanupSpec() { 36 | wireMockServer.stop() 37 | } 38 | 39 | def 'should remove trailing slashes from request URL to OPA'() { 40 | given: 41 | def path = '/v1/path/with/trailing/slash/' 42 | wireMockServer 43 | .stubFor(any(anyUrl()) 44 | .willReturn(aResponse() 45 | .withStatus(200) 46 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 47 | .withBody('{}'))) 48 | when: 49 | def request = client.getBasicRequestBuilder(path).GET().build() 50 | client.sendRequest(request, HttpResponse.BodyHandlers.discarding()) 51 | then: 52 | wireMockServer.verify(getRequestedFor(urlEqualTo('/v1/path/with/trailing/slash'))) 53 | } 54 | 55 | def 'should remove extra slashes from request URL to OPA'() { 56 | given: 57 | def path = '/v1/path/with///extra//slash' 58 | wireMockServer 59 | .stubFor(any(anyUrl()) 60 | .willReturn(aResponse() 61 | .withStatus(200) 62 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 63 | .withBody('{}'))) 64 | when: 65 | def request = client.getBasicRequestBuilder(path).GET().build() 66 | client.sendRequest(request, HttpResponse.BodyHandlers.discarding()) 67 | then: 68 | wireMockServer.verify(getRequestedFor(urlEqualTo('/v1/path/with/extra/slash'))) 69 | } 70 | 71 | def 'should throw OpaClientException when url is null'() { 72 | given: 73 | wireMockServer 74 | .stubFor(any(anyUrl()) 75 | .willReturn(aResponse() 76 | .withStatus(200) 77 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 78 | .withBody('{}'))) 79 | when: 80 | def request = client.getBasicRequestBuilder(null).GET().build() 81 | client.sendRequest(request, HttpResponse.BodyHandlers.discarding()) 82 | then: 83 | thrown(OpaClientException) 84 | } 85 | 86 | def 'should prefix endpoint path with slash when missing'() { 87 | given: 88 | wireMockServer 89 | .stubFor(any(anyUrl()) 90 | .willReturn(aResponse() 91 | .withStatus(200) 92 | .withHeader(ContentType.HEADER_NAME, APPLICATION_JSON) 93 | .withBody('{}'))) 94 | when: 95 | def request = client.getBasicRequestBuilder('v1/path/with/missing/slash').GET().build() 96 | client.sendRequest(request, HttpResponse.BodyHandlers.discarding()) 97 | then: 98 | wireMockServer.verify(getRequestedFor(urlEqualTo('/v1/path/with/missing/slash'))) 99 | } 100 | 101 | def 'should remap SocketException and derivatives to OpaServerConnectionException'() { 102 | given: 103 | OpaRestClient restClient = new OpaRestClient(new OpaConfiguration("http://localhost:8182"), HttpClient.newHttpClient(), new ObjectMapper()) 104 | when: 105 | def request = restClient.getBasicRequestBuilder('v1/path/with/missing/slash').GET().build() 106 | restClient.sendRequest(request, HttpResponse.BodyHandlers.discarding()) 107 | then: 108 | thrown(OpaServerConnectionException) 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /src/test/groovy/com/bisnode/opa/client/rest/url/OpaUrlSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.bisnode.opa.client.rest.url 2 | 3 | import spock.lang.Specification 4 | 5 | class OpaUrlSpec extends Specification { 6 | public static final String URL = 'http://localhost:8181/' 7 | 8 | def 'should change multiple extra slashes to single one when normalized'() { 9 | when: 10 | OpaUrl opaUrl = OpaUrl.of(URL, '/v1/path/to///document') 11 | def normalizationResult = opaUrl.normalized().value 12 | then: 13 | normalizationResult == 'http://localhost:8181/v1/path/to/document' 14 | } 15 | 16 | def 'should remove trailing slash when normalized'() { 17 | when: 18 | OpaUrl opaUrl = OpaUrl.of(URL, '/v1/path/to/document/') 19 | def normalizationResult = opaUrl.normalized().value 20 | then: 21 | normalizationResult == 'http://localhost:8181/v1/path/to/document' 22 | } 23 | 24 | def 'should throw InvalidEndpointException when trying to create object with null endpoint'() { 25 | when: 26 | OpaUrl.of(URL, null) 27 | then: 28 | thrown(InvalidEndpointException) 29 | } 30 | } 31 | --------------------------------------------------------------------------------