Skip to content
This repository was archived by the owner on Apr 10, 2023. It is now read-only.

Commit 0f5127d

Browse files
committed
initial commit
0 parents  commit 0f5127d

81 files changed

Lines changed: 4148 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.github/dependabot.yml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
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://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5+
6+
version: 2
7+
updates:
8+
- package-ecosystem: "gradle"
9+
directory: "/"
10+
schedule:
11+
interval: "weekly"
12+
day: "monday"

.github/workflows/build.yml

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
name: PR Validation
2+
3+
on:
4+
pull_request:
5+
branches:
6+
- main
7+
8+
jobs:
9+
build:
10+
runs-on: ubuntu-latest
11+
steps:
12+
- uses: actions/checkout@v2
13+
- name: Set up JDK 11
14+
uses: actions/setup-java@v2
15+
with:
16+
java-version: '11'
17+
distribution: 'adopt'
18+
- name: Validate Gradle wrapper
19+
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b
20+
- name: Cache Gradle packages
21+
uses: actions/cache@v2
22+
with:
23+
path: |
24+
~/.gradle/caches
25+
~/.gradle/wrapper
26+
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
27+
restore-keys: |
28+
${{ runner.os }}-gradle-
29+
- name: Build with Gradle
30+
run: ./gradlew build --info -Dorg.gradle.daemon=false
31+
- name: Cleanup Gradle Cache
32+
# Remove some files from the Gradle cache, so they aren't cached by GitHub Actions.
33+
# Restoring these files from a GitHub Actions cache might cause problems for future builds.
34+
run: |
35+
rm -f ~/.gradle/caches/modules-2/modules-2.lock
36+
rm -f ~/.gradle/caches/modules-2/gc.properties

.github/workflows/publish.yml

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
name: Publish to Github Packages on Release
2+
on:
3+
release:
4+
branches:
5+
- main
6+
types:
7+
- created
8+
jobs:
9+
publish:
10+
runs-on: ubuntu-latest
11+
permissions:
12+
contents: read
13+
packages: write
14+
steps:
15+
- uses: actions/checkout@v2
16+
- uses: actions/setup-java@v2
17+
with:
18+
java-version: '11'
19+
distribution: 'adopt'
20+
- name: Validate Gradle wrapper
21+
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b
22+
- name: Cache Gradle packages
23+
uses: actions/cache@v2
24+
with:
25+
path: |
26+
~/.gradle/caches
27+
~/.gradle/wrapper
28+
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
29+
restore-keys: |
30+
${{ runner.os }}-gradle-
31+
- name: Build with Gradle
32+
run: ./gradlew build --info -Dorg.gradle.daemon=false
33+
- name: Cleanup Gradle Cache
34+
# Remove some files from the Gradle cache, so they aren't cached by GitHub Actions.
35+
# Restoring these files from a GitHub Actions cache might cause problems for future builds.
36+
run: |
37+
rm -f ~/.gradle/caches/modules-2/modules-2.lock
38+
rm -f ~/.gradle/caches/modules-2/gc.properties
39+
- name: Publish package
40+
run: |
41+
NEW_VERSION=$(echo "${GITHUB_REF}" | cut -d "/" -f3)
42+
echo "Publishing new version: ${NEW_VERSION}"
43+
./gradlew -Pversion=${NEW_VERSION} publish
44+
env:
45+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

.gitignore

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
*.class
2+
*.log
3+
# Mobile Tools for Java (J2ME)
4+
.mtj.tmp/
5+
6+
# Package Files #
7+
*.war
8+
*.ear
9+
#*.jar
10+
11+
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
12+
hs_err_pid*
13+
14+
# output
15+
target/
16+
build/
17+
/bin/
18+
out/
19+
20+
# eclipse
21+
.classpath
22+
.project
23+
.settings/
24+
25+
# idea
26+
*.iml
27+
*.ipr
28+
*.iws
29+
.idea
30+
.DS_Store
31+
.gradle/

.whitesource

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
{
2+
"settingsInheritedFrom": "whitesource-config/whitesource-config@main"
3+
}

CODE_OF_CONDUCT.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Contributor Covenant Code of Conduct
2+
3+
# Our Pledge
4+
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
5+
6+
# Our Standards
7+
Examples of behavior that contributes to creating a positive environment include:
8+
Using welcoming and inclusive language
9+
Being respectful of differing viewpoints and experiences
10+
Gracefully accepting constructive criticism
11+
Focusing on what is best for the community
12+
Showing empathy towards other community members
13+
14+
Examples of unacceptable behavior by participants include:
15+
The use of sexualized language or imagery and unwelcome sexual attention or advances
16+
Trolling, insulting/derogatory comments, and personal or political attacks
17+
Public or private harassment
18+
Publishing others' private information, such as a physical or electronic address, without explicit permission
19+
Other conduct which could reasonably be considered inappropriate in a professional setting
20+
21+
# Our Responsibilities
22+
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
23+
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
24+
25+
# Scope
26+
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
27+
28+
# Enforcement
29+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at TTS-OpenSource-Office@target.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
30+
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
31+
32+
# Attribution
33+
This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

CONTRIBUTING.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Contributing to reuse
2+
3+
### Issues
4+
5+
Feel free to submit bugs or feature requests as issues.
6+
7+
### Pull Requests
8+
9+
These rules must be followed for any contributions to be merged into master.
10+
11+
1. Fork this repo
12+
1. Make any desired changes
13+
1. Validate your changes meet your desired use case
14+
1. Ensure documentation has been updated
15+
1. Open a pull request

LICENSE.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
Copyright (c) 2021 Target Brands, Inc.
2+
3+
4+
Permission is hereby granted, free of charge, to any person obtaining a copy
5+
of this software and associated documentation files (the "Software"), to deal
6+
in the Software without restriction, including without limitation the rights
7+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8+
copies of the Software, and to permit persons to whom the Software is
9+
furnished to do so, subject to the following conditions:
10+
11+
The above copyright notice and this permission notice shall be included in all
12+
copies or substantial portions of the Software.
13+
14+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20+
SOFTWARE.

README.md

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
# Token Manager for Salesforce
2+
3+
This project makes Salesforce API calls with Spring a breeze. It exposes either a RestTemplate or WebClient that handles generating, refreshing and attaching an authorization token header for every API call. Just pass in your instance and user credentials via `application.yml`, autowire your desired bean and it takes care of the rest.
4+
5+
## Usage
6+
7+
To use this library, the following repository declaration and one of the dependencies to your project's `build.gradle` file. This will include the core module as well automatically.
8+
9+
```groovy
10+
repositories {
11+
maven {
12+
name = "GitHubPackages"
13+
url = uri("https://maven.pkg.github.com/target/token-manager-for-salesforce")
14+
credentials {
15+
username = project.findProperty("gpr.user") ?: System.getenv("USERNAME")
16+
password = project.findProperty("gpr.token") ?: System.getenv("TOKEN")
17+
}
18+
}
19+
}
20+
dependencies {
21+
// for reactive applications
22+
implementation "com.tgt.crm:token-manager-for-salesforce-webflux:${libraryVersion}"
23+
// for non-reactive applications
24+
implementation "com.tgt.crm:token-manager-for-salesforce-webmvc:${libraryVersion}"
25+
}
26+
```
27+
28+
Find the latest version in the "packages" section of this repo. You will need access to the Github repository and will need to make your user and a personal access token available as a project or system property to authorize with Github and download the package. More details can be found [here](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-gradle-registry).
29+
30+
Add the following to your `application.yml` file to pass in Salesforce properties from TAP secrets/environment variables. You can set explicit values for these properties instead of environment variables if you prefer. Ensure you don't check any secrets into Git.
31+
32+
```yaml
33+
salesforce:
34+
host: ${SALESFORCE_HOST}
35+
username: ${SALESFORCE_USERNAME}
36+
password: ${SALESFORCE_PASSWORD}
37+
client-id: ${SALESFORCE_CLIENT_ID}
38+
client-secret: ${SALESFORCE_CLIENT_SECRET}
39+
auth-uri: /services/oauth2/token # optional
40+
retry-backoff-delay: 1000 # optional, configures retry for auth token requests only
41+
max-auth-token-retries: 3 # optional, configures retry for auth token requests only
42+
retry-backoff-multiplier: 2 # optional, configures retry for auth token requests only, only used by MVC, see SalesforceConfig for more info
43+
httpclient:
44+
max-conn-per-route: 20 # optional
45+
read-timeout: 30000 # optional, in milliseconds
46+
connection-timeout: 60000 # optional, in milliseconds
47+
mvc: # configs in this block only available for webmvc
48+
max-pools: 50 # optional
49+
connection-request-timeout: 30000 # optional, in milliseconds
50+
retries: 3 # optional, MVC only, configures default # of retries for all requests except auth token
51+
retry-interval: 2000 # optional, in milliseconds, configures default retry interval for all requests except auth token
52+
```
53+
54+
You should then be able to autowire the RestTemplate or WebClient bean in any component in your project and use it to make API calls to Salesforce.
55+
56+
```java
57+
@Service
58+
public class SalesforceClient {
59+
60+
private final RestTemplate salesforceRestTemplate;
61+
62+
public SalesforceClient(@Qualifier("sfRestTemplate") final RestTemplate salesForceRestTemplate) {
63+
this.salesForceRestTemplate = salesForceRestTemplate;
64+
}
65+
66+
public String querySalesforce() {
67+
ResponseEntity<String> sfResponse =
68+
salesForceRestTemplate.exchange(
69+
"/services/data/v50.0/query&q={query}",
70+
HttpMethod.GET,
71+
HttpEntity.EMPTY,
72+
String.class,
73+
"SELECT Id FROM Case");
74+
75+
return sfResponse.getBody();
76+
}
77+
}
78+
```
79+
80+
```java
81+
@Service
82+
public class SalesforceClient {
83+
84+
private final WebClient salesforceWebClient;
85+
86+
public SalesforceClient(@Qualifier("sfWebClient") final WebClient salesforceWebClient) {
87+
this.salesforceWebClient = salesforceWebClient;
88+
}
89+
90+
public Mono<String> querySalesforce() {
91+
return webClient
92+
.get()
93+
.uri("/services/data/v50.0/query&q={query}", "SELECT Id FROM Case")
94+
.retrieve()
95+
.toEntity(String.class)
96+
.map(HttpEntity::getBody);
97+
}
98+
}
99+
```
100+
101+
### Minimum Requirements
102+
103+
In your project, the following minimum versions of Spring Boot are required to use this library:
104+
105+
* token-manager-for-salesforce-webflux: Spring Boot > 2.2.6.RELEASE
106+
* Spring Boot > 2.4.0 is recommended to support Wiretap for WebClient debug logging
107+
* token-manager-for-salesforce-webmvc: Spring Boot > 2.2.0.RELEASE
108+
109+
### Metrics
110+
111+
The application also emits one micrometer metric. If a token refresh fails, a counter is incremented. The counter is called `exception_counter` and has one tag `exception_type` with value `token_refresh_exception`. This can be used to set up an alert in Grafana if a token refresh ever fails.
112+
113+
### How does it work?
114+
115+
This library follows the [OAuth 2.0 Username-Password Flow](https://help.salesforce.com/articleView?id=remoteaccess_oauth_username_password_flow.htm&type=5) and is intended to be used with first-party applications.
116+
117+
When your application starts up it will not have a token. The first time it makes an API call, the library intercepts the request, makes the appropriate API call to `/services/oauth2/token` for your configured instance as documented [here](https://help.salesforce.com/articleView?id=remoteaccess_oauth_endpoints.htm&type=5). The generated token is attached to the request as an `Authorization` header and the request proceeds. It is also cached in memory.
118+
119+
Subsequent requests use the cached token and do not try to request a new token unless a 401 response is received. When a 401 is received, it attempts to generate a new token and retries the request. We use this behavior because Salesforce auth tokens do not return an `expires_in` property and the length of time they are valid for can vary from instance to instance based on admin settings.
120+
121+
### Debugging Requests
122+
123+
It is possible and occasionally useful to log complete HTTP requests and responses including URLs, query params, headers and bodies. Be careful as this has the potential to expose sensitive data such as passwords, auth tokens or API keys. It is recommended to only use this when running the application locally.
124+
125+
To enable request/response logging for either mvc or webflux library, add the following to your `application.yml`:
126+
127+
```yaml
128+
logging:
129+
level:
130+
com.tgt.crm.token: TRACE
131+
org.springframework.web.client.RestTemplate: DEBUG # additional RestTemplate debug logs, only applies to MVC. WARNING: logs sensitive info
132+
org.apache.http: DEBUG # additional detailed logging for RestTemplate, only applies to MVC. WARNING: logs sensitive info
133+
reactor.netty: TRACE # additional detailed logging for WebClient, only applies to WebFlux
134+
```
135+
136+
Note that setting log level to `DEBUG` will enable all debug logging except request/response logging. This is by design to help prevent unintentional sensitive data exposure.
137+
138+
## Local Development
139+
140+
If you make changes to this library locally and want to test those changes with another application, you can use [Gradle Composite Builds](https://docs.gradle.org/current/userguide/composite_builds.html). Essentially you just tell your other application to point to this project on your local file system instead of downloading the dependency from a repository.
141+
142+
In the `settings.gradle` file in the root of the other project (you may have to create the file if it doesn't exist in that project), add the following line:
143+
144+
```
145+
includeBuild '../token-manager-for-salesforce'
146+
```
147+
148+
Where `../token-manager-for-salesforce` is the relative path to this project on your local file system. Now when you build the other project, it should use your local copy of `token-manager-for-salesforce`. Be sure to remove this change before committing.
149+
150+
## Publish a new version
151+
152+
Make the desired changes locally. Open a PR against the master branch, get it reviewed and merge. Tag this commit with a tag following [semantic versioning](https://semver.org/). This will trigger a new deployment of the library to [Github Packages](https://github.com/orgs/target/packages?repo_name=token-manager-for-salesforce).
153+
154+
## Troubleshooting
155+
156+
Problem: When I try to start my application I am getting a `NoClassDefFoundError` or a `NoSuchMethodError`.
157+
158+
Solution: Check the version of Spring Boot you are using in your app and that it meets the minimum requirement listed above in the README.
159+
160+
## License
161+
162+
token-manager-for-salesforce is licensed under the [MIT License](LICENSE.md)
163+
164+
Salesforce is a trademark of Salesforce.com, inc., and is used here with permission.

0 commit comments

Comments
 (0)