Compare commits
66
Commits
v0.4.0
...
f6c0544d9a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6c0544d9a | ||
|
|
0e6f4bb9c0 | ||
|
|
88601efa1b | ||
|
|
9e7118bcf8 | ||
|
|
c3a5c5f3e5 | ||
|
|
20fabf9667 | ||
|
|
b6821b0076 | ||
|
|
732f92ee78 | ||
|
|
4b560141a1 | ||
|
|
31229ff627 | ||
|
|
d2acc3ce74 | ||
|
|
9aba45ab0e | ||
|
|
9a312b464e | ||
|
|
bc373dad59 | ||
|
|
b13a9ad02e | ||
|
|
65339f900d | ||
|
|
7e065552a6 | ||
|
|
6a11d881e1 | ||
|
|
7446dcc659 | ||
|
|
42e06245e1 | ||
|
|
36d44ed7a4 | ||
|
|
68846b6676 | ||
|
|
a651d478b0 | ||
|
|
3c480f19f8 | ||
|
|
32a35781b5 | ||
|
|
59111ea53c | ||
|
|
982a95451d | ||
|
|
be2fb5d89e | ||
|
|
d213f72138 | ||
|
|
824bcf060d | ||
|
|
dbedcdfe16 | ||
|
|
87b39fca7b | ||
|
|
d052555ba7 | ||
|
|
dfa2753619 | ||
|
|
0a47bb6338 | ||
|
|
25228af9f0 | ||
|
|
d4fba87e13 | ||
|
|
9919230a3b | ||
|
|
ba9bc9ea93 | ||
|
|
eea6e72145 | ||
|
|
c68b865798 | ||
|
|
41d35fe745 | ||
|
|
c2d10bb929 | ||
|
|
f3e05e1bc7 | ||
|
|
90664f4007 | ||
|
|
2c233437da | ||
|
|
84c5295345 | ||
|
|
6d139329f1 | ||
|
|
b5caee443e | ||
|
|
053979d4e1 | ||
|
|
d57da1e60f | ||
|
|
3613df6974 | ||
|
|
0acf0d0834 | ||
|
|
5ed9da4036 | ||
|
|
84a37b8a8d | ||
|
|
c292c27444 | ||
|
|
744abd47ff | ||
|
|
9f301337b6 | ||
|
|
0a401b164c | ||
|
|
7b08820d1a | ||
|
|
83995ba5fa | ||
|
|
d586567fd6 | ||
|
|
3505aee124 | ||
|
|
ee3dcda8ea | ||
|
|
c01946fc05 | ||
|
|
09cb00db19 |
No files matched your search
@@ -0,0 +1,138 @@
|
|||||||
|
name: Publish JUnit Report (Short Names)
|
||||||
|
description: Normalize JUnit XML report names and publish a test report to the repo.
|
||||||
|
inputs:
|
||||||
|
token:
|
||||||
|
description: Gitea token with write access to the repository.
|
||||||
|
required: true
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: composite
|
||||||
|
steps:
|
||||||
|
- name: Install python3
|
||||||
|
shell: bash
|
||||||
|
run: apk add --no-cache python3
|
||||||
|
|
||||||
|
- name: Normalize JUnit report names
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
mkdir -p junit-short
|
||||||
|
shopt -s globstar nullglob
|
||||||
|
for f in **/target/*-reports/TEST-*.xml; do
|
||||||
|
base="$(basename "$f")"
|
||||||
|
short="${base#TEST-}"
|
||||||
|
cp "$f" "junit-short/${short}"
|
||||||
|
done
|
||||||
|
|
||||||
|
- name: Generate Markdown Test Report
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
mkdir -p reports
|
||||||
|
python3 - <<'EOF'
|
||||||
|
import glob, xml.etree.ElementTree as ET
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
generated_at = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
|
||||||
|
|
||||||
|
# --- JUnit ---
|
||||||
|
files = glob.glob("junit-short/*.xml")
|
||||||
|
total_tests = total_failures = total_errors = total_skipped = 0
|
||||||
|
test_rows = []
|
||||||
|
|
||||||
|
for f in sorted(files):
|
||||||
|
tree = ET.parse(f)
|
||||||
|
r = tree.getroot()
|
||||||
|
suites = r.findall("testsuite") if r.tag == "testsuites" else [r]
|
||||||
|
for ts in suites:
|
||||||
|
name = ts.get("name", f)
|
||||||
|
tests = int(ts.get("tests", 0))
|
||||||
|
failures = int(ts.get("failures", 0))
|
||||||
|
errors = int(ts.get("errors", 0))
|
||||||
|
skipped = int(ts.get("skipped", 0))
|
||||||
|
passed = tests - failures - errors - skipped
|
||||||
|
status = "✅" if (failures + errors) == 0 else "❌"
|
||||||
|
total_tests += tests
|
||||||
|
total_failures += failures
|
||||||
|
total_errors += errors
|
||||||
|
total_skipped += skipped
|
||||||
|
test_rows.append(f"| {status} | {name} | {tests} | {passed} | {failures + errors} | {skipped} |")
|
||||||
|
|
||||||
|
total_passed = total_tests - total_failures - total_errors - total_skipped
|
||||||
|
overall = "✅ All tests passed" if (total_failures + total_errors) == 0 else "❌ Some tests failed"
|
||||||
|
|
||||||
|
# --- JaCoCo ---
|
||||||
|
def counter(el, type_):
|
||||||
|
c = next((x for x in el.findall("counter") if x.get("type") == type_), None)
|
||||||
|
if c is None:
|
||||||
|
return 0, 0
|
||||||
|
covered = int(c.get("covered", 0))
|
||||||
|
missed = int(c.get("missed", 0))
|
||||||
|
return covered, covered + missed
|
||||||
|
|
||||||
|
cov_rows = []
|
||||||
|
jacoco_files = glob.glob("**/target/site/jacoco/jacoco.xml", recursive=True)
|
||||||
|
|
||||||
|
for jf in sorted(jacoco_files):
|
||||||
|
tree = ET.parse(jf)
|
||||||
|
root = tree.getroot()
|
||||||
|
for pkg in root.findall("package"):
|
||||||
|
name = pkg.get("name", "").replace("/", ".")
|
||||||
|
line_cov, line_total = counter(pkg, "LINE")
|
||||||
|
branch_cov, branch_total = counter(pkg, "BRANCH")
|
||||||
|
line_pct = f"{100 * line_cov / line_total:.0f}%" if line_total else "n/a"
|
||||||
|
branch_pct = f"{100 * branch_cov / branch_total:.0f}%" if branch_total else "n/a"
|
||||||
|
cov_rows.append(f"| {name} | {line_pct} ({line_cov}/{line_total}) | {branch_pct} ({branch_cov}/{branch_total}) |")
|
||||||
|
|
||||||
|
# --- Markdown zusammenbauen ---
|
||||||
|
md = (
|
||||||
|
"# Test Report\n\n"
|
||||||
|
f"_Generated on {generated_at}_\n\n"
|
||||||
|
f"**{overall}**\n\n"
|
||||||
|
"## Test Results\n\n"
|
||||||
|
"| | Tests | Passed | Failed | Skipped |\n"
|
||||||
|
"|---|---|---|---|---|\n"
|
||||||
|
f"| **Total** | {total_tests} | {total_passed} | {total_failures + total_errors} | {total_skipped} |\n\n"
|
||||||
|
"### Details\n\n"
|
||||||
|
"| Status | Suite | Tests | Passed | Failed | Skipped |\n"
|
||||||
|
"|---|---|---|---|---|---|\n"
|
||||||
|
) + "\n".join(test_rows) + "\n\n"
|
||||||
|
|
||||||
|
if cov_rows:
|
||||||
|
md += (
|
||||||
|
"## Coverage\n\n"
|
||||||
|
"| Package | Line Coverage | Branch Coverage |\n"
|
||||||
|
"|---|---|---|\n"
|
||||||
|
) + "\n".join(cov_rows) + "\n"
|
||||||
|
else:
|
||||||
|
md += "_No JaCoCo report found._\n"
|
||||||
|
|
||||||
|
with open("reports/test.md", "w") as out:
|
||||||
|
out.write(md)
|
||||||
|
print(md)
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Commit Test-Report to Repo
|
||||||
|
# pull requests have no branch to push to (ref_name is e.g. "1/merge")
|
||||||
|
if: ${{ github.event_name == 'push' }}
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
GIT_USER: gitea-actions-bot
|
||||||
|
GIT_EMAIL: bot@mein-gateway.de
|
||||||
|
GITEA_TOKEN: ${{ inputs.token }}
|
||||||
|
run: |
|
||||||
|
git config user.name "$GIT_USER"
|
||||||
|
git config user.email "$GIT_EMAIL"
|
||||||
|
git remote set-url origin https://$GIT_USER:$GITEA_TOKEN@git.mein-gateway.de/${{ github.repository }}.git
|
||||||
|
git fetch origin
|
||||||
|
git checkout ${{ github.ref_name }}
|
||||||
|
git add reports/
|
||||||
|
git diff --cached --quiet && echo "No changes" && exit 0
|
||||||
|
git commit -m "ci: update test report [skip ci]"
|
||||||
|
# rebase onto commits pushed in the meantime instead of overwriting them;
|
||||||
|
# on conflicts in reports/ the freshly generated report wins
|
||||||
|
for attempt in 1 2 3; do
|
||||||
|
git pull --rebase --autostash -X theirs origin ${{ github.ref_name }}
|
||||||
|
git push origin ${{ github.ref_name }} && exit 0
|
||||||
|
echo "Push rejected (attempt $attempt), retrying..."
|
||||||
|
sleep 5
|
||||||
|
done
|
||||||
|
exit 1
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
name: "Setup Maven with GitHub Packages"
|
||||||
|
|
||||||
|
description: "Sets up JDK and caches Maven dependencies."
|
||||||
|
|
||||||
|
inputs:
|
||||||
|
java-distribution:
|
||||||
|
description: "Java distribution to use"
|
||||||
|
default: "temurin"
|
||||||
|
java-version:
|
||||||
|
description: "Java version to use"
|
||||||
|
default: "17"
|
||||||
|
required: true
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: "composite"
|
||||||
|
steps:
|
||||||
|
- name: Set up JDK
|
||||||
|
with:
|
||||||
|
distribution: ${{ inputs.java-distribution }}
|
||||||
|
java-version: ${{ inputs.java-version }}
|
||||||
|
uses: actions/setup-java@v5
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
name: Build and Analyse
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- develop
|
||||||
|
- 'feature/**'
|
||||||
|
pull_request:
|
||||||
|
types: [ opened, synchronize, reopened ]
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
|
||||||
|
build-and-analyse:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
with:
|
||||||
|
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
|
||||||
|
|
||||||
|
- name: Setup Java and Maven
|
||||||
|
uses: ./.gitea/actions/setup-java-maven
|
||||||
|
|
||||||
|
- name: Build and test
|
||||||
|
env:
|
||||||
|
# required by the live tests (CfClientTest, CfClientPenTest), they are skipped if not set
|
||||||
|
API_TOKEN: ${{ secrets.API_TOKEN }}
|
||||||
|
run: mvn -B verify
|
||||||
|
|
||||||
|
- name: Publish Test Report
|
||||||
|
uses: ./.gitea/actions/publish-report
|
||||||
|
if: ${{ always() }}
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
name: Publish JUnit Report (Short Names)
|
|
||||||
description: Normalize JUnit XML report names and publish a summary-only test report.
|
|
||||||
inputs:
|
|
||||||
token:
|
|
||||||
description: GitHub token for creating the check run.
|
|
||||||
required: true
|
|
||||||
report-name:
|
|
||||||
description: Name shown for the test report.
|
|
||||||
required: false
|
|
||||||
default: Summary of JUnit Tests
|
|
||||||
|
|
||||||
runs:
|
|
||||||
using: composite
|
|
||||||
steps:
|
|
||||||
- name: Normalize JUnit report names
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
mkdir -p junit-short
|
|
||||||
shopt -s globstar nullglob
|
|
||||||
for f in **/target/*-reports/TEST-*.xml; do
|
|
||||||
base="$(basename "$f")"
|
|
||||||
short="${base#TEST-}"
|
|
||||||
short="${short%.xml}"
|
|
||||||
cp "$f" "junit-short/${short}"
|
|
||||||
done
|
|
||||||
|
|
||||||
- name: Publish Test Report
|
|
||||||
uses: dorny/test-reporter@v2
|
|
||||||
with:
|
|
||||||
token: ${{ inputs.token }}
|
|
||||||
name: ${{ inputs.report-name }}
|
|
||||||
path: "*"
|
|
||||||
reporter: java-junit
|
|
||||||
only-summary: true
|
|
||||||
working-directory: "junit-short"
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
name: "Setup Maven with GitHub Packages"
|
|
||||||
|
|
||||||
description: "Sets up JDK, caches Maven dependencies, and configures GitHub Packages for Maven repositories."
|
|
||||||
|
|
||||||
inputs:
|
|
||||||
java-version:
|
|
||||||
description: "Java version to install"
|
|
||||||
default: "17"
|
|
||||||
required: true
|
|
||||||
java-distribution:
|
|
||||||
description: "Java distribution to use"
|
|
||||||
default: "corretto"
|
|
||||||
|
|
||||||
runs:
|
|
||||||
using: "composite"
|
|
||||||
steps:
|
|
||||||
- name: Set up JDK
|
|
||||||
uses: actions/setup-java@v4
|
|
||||||
with:
|
|
||||||
distribution: ${{ inputs.java-distribution }}
|
|
||||||
java-version: ${{ inputs.java-version }}
|
|
||||||
|
|
||||||
- name: Cache Maven Repository
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/.m2/repository
|
|
||||||
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
|
|
||||||
restore-keys: |
|
|
||||||
${{ runner.os }}-maven-
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
name: Build and Analyse
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- develop
|
|
||||||
- feature*
|
|
||||||
pull_request:
|
|
||||||
types: [ opened, synchronize, reopened ]
|
|
||||||
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
shell: bash
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
|
|
||||||
build-and-analyse:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
|
|
||||||
|
|
||||||
- name: Setup Java and Maven
|
|
||||||
uses: ./.github/actions/setup-java-maven
|
|
||||||
|
|
||||||
- name: Build and analyze with SonarCloud
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
|
||||||
CF_API_TOKEN: ${{ secrets.API_TOKEN }}
|
|
||||||
run: |
|
|
||||||
echo "Running SonarCloud analysis..."
|
|
||||||
mvn -B -DtestClasspath=src/test/ verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=th-schwarz_CloudflareDNS-java
|
|
||||||
|
|
||||||
- name: Publish Test Report
|
|
||||||
uses: ./.github/actions/publish-report/
|
|
||||||
if: ${{ always() }}
|
|
||||||
with:
|
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
report-name: Summary of JUnit Tests
|
|
||||||
@@ -11,3 +11,4 @@
|
|||||||
/info.txt
|
/info.txt
|
||||||
cf.yml
|
cf.yml
|
||||||
/docs/apidocs/javadoc.sh
|
/docs/apidocs/javadoc.sh
|
||||||
|
/.claude/settings.local.json
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
|
|
||||||
when:
|
|
||||||
- event: push
|
|
||||||
branch: develop
|
|
||||||
|
|
||||||
steps:
|
|
||||||
# - name: hello
|
|
||||||
# image: alpine
|
|
||||||
# commands:
|
|
||||||
# - echo "Hello World!"
|
|
||||||
|
|
||||||
- name: maven verify
|
|
||||||
image: maven:3-amazoncorretto-17-alpine
|
|
||||||
commands:
|
|
||||||
- mvn -B verify
|
|
||||||
@@ -1,14 +1,8 @@
|
|||||||
# CloudflareDNS-java
|
# CloudflareDNS-java
|
||||||
|
|
||||||
[](https://ci.codeberg.org/repos/16522)
|
[](https://git.mein-gateway.de/thischwa/CloudflareDNS-java/actions?workflow=build-and-analyse.yml)
|
||||||
|
|
||||||
[](https://sonarcloud.io/summary/new_code?id=th-schwarz_CloudflareDNS-java)
|
[Test report](reports/test.md)
|
||||||
[](https://sonarcloud.io/summary/new_code?id=th-schwarz_CloudflareDNS-java)
|
|
||||||
[](https://sonarcloud.io/summary/new_code?id=th-schwarz_CloudflareDNS-java)
|
|
||||||
[](https://sonarcloud.io/summary/new_code?id=th-schwarz_CloudflareDNS-java)
|
|
||||||
[](https://sonarcloud.io/summary/new_code?id=th-schwarz_CloudflareDNS-java)
|
|
||||||
|
|
||||||
[](https://codeberg.org/th-schwarz/CloudflareDNS-java)
|
|
||||||
|
|
||||||
## Preface
|
## Preface
|
||||||
|
|
||||||
@@ -16,7 +10,7 @@ This project provides a java client for minimalistic access to the Cloudflare AP
|
|||||||
managing DNS settings such as creating, updating and deleting DNS records.
|
managing DNS settings such as creating, updating and deleting DNS records.
|
||||||
|
|
||||||
If you encounter any bugs or find missing features, feel free to report them on
|
If you encounter any bugs or find missing features, feel free to report them on
|
||||||
the [Codeberg Issues page](https://codeberg.org/th-schwarz/CloudflareDNS-java/issues).
|
the [GitHub Issues page](https://github.com/th-schwarz/CloudflareDNS-java/issues).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -28,63 +22,20 @@ This guide comes without any warranty. Use at your own risk. The author is not r
|
|||||||
|
|
||||||
## Get It
|
## Get It
|
||||||
|
|
||||||
The project has its own maven repository. It can be added to the `pom.xml`:
|
Java 17 or higher is required.
|
||||||
|
|
||||||
```xml
|
The project has its own maven repository. Follow the instructions on the latest [package](https://git.mein-gateway.de/thischwa/-/packages/maven/codes.thischwa:cloudflaredns) to add the repository to your project.
|
||||||
<repositories>
|
|
||||||
<repository>
|
|
||||||
<id>gitea</id>
|
|
||||||
<url>https://codeberg.org/api/packages/th-schwarz/maven</url>
|
|
||||||
</repository>
|
|
||||||
</repositories>
|
|
||||||
```
|
|
||||||
|
|
||||||
The dependency is:
|
|
||||||
```xml
|
|
||||||
<dependency>
|
|
||||||
<groupId>codes.thischwa</groupId>
|
|
||||||
<artifactId>cloudflaredns</artifactId>
|
|
||||||
<version>[version]</version>
|
|
||||||
</dependency>
|
|
||||||
```
|
|
||||||
|
|
||||||
## Changelog
|
## Changelog
|
||||||
|
|
||||||
- 0.4.0-SNAPSHOT:
|
See [changelog](changelog.md)
|
||||||
- **Breaking Change**: renamed `client.zone().record()` to `client.zone().getRecord()`
|
|
||||||
- Code quality improvements: Increasing test coverage
|
|
||||||
- 0.3.0:
|
|
||||||
- **Breaking Change**:
|
|
||||||
- **New Fluent API**: Changed the initialization of the client(`new CfDnsClientBuilder().withApiTokenAuth("your-api-token").build()`)
|
|
||||||
- Authentication with API token.
|
|
||||||
- 0.2.0:
|
|
||||||
- **Breaking Change**: `emptyResultThrowsException` default changed from `true` to `false`. Now applies to both
|
|
||||||
single and multiple result requests. Empty results will be returned by default without throwing exceptions.
|
|
||||||
- API method names refactored for consistency: `zoneListAll` → `zoneList`, `zoneInfo` → `zoneGet`, `sldListAll` →
|
|
||||||
`recordList`
|
|
||||||
- RecordEntity getter methods renamed for clarity: `getName()` → `getSld()`
|
|
||||||
- **New Fluent API**: Changed the initialization of the client(`new CfDnsClientBuilder().withApiTokenAuth("your-api-token").build()`) and added chainable method interface for more readable DNS operations (
|
|
||||||
`client.zone().record()...`)
|
|
||||||
- Code quality improvements: removed duplication in batch operations, improved type safety in HTTP methods,
|
|
||||||
optimized string concatenation, removed mutable setters from CfDnsClient
|
|
||||||
- Enhanced type validation in `RecordEntity.build()` with better error messages
|
|
||||||
- CfClient#recordList must return multiple RecordEntries
|
|
||||||
- add a missing source jar
|
|
||||||
- ResponseResultInfo#Errors: wrong object structure
|
|
||||||
- changing multiple records with put, post, patch and delete for dns-records
|
|
||||||
- 0.1.0:
|
|
||||||
- refactored / extended tests
|
|
||||||
- 0.1.0-beta.3:
|
|
||||||
- fixed json deserialization
|
|
||||||
- added logging of api errors
|
|
||||||
- 0.1.0-beta.1: 1st runnable version
|
|
||||||
|
|
||||||
## Methods Overview
|
## Methods Overview
|
||||||
|
|
||||||
The methods can be categorized as follows:
|
The methods can be categorized as follows:
|
||||||
|
|
||||||
- `Zone`: list, info
|
- `Zone`: list, info
|
||||||
- `Record`: list, info, create, update, delete
|
- `Record`: list, info, create, update, delete, batch
|
||||||
|
|
||||||
The API provides two styles for working with DNS records:
|
The API provides two styles for working with DNS records:
|
||||||
|
|
||||||
@@ -92,7 +43,8 @@ The API provides two styles for working with DNS records:
|
|||||||
2. **Fluent API**: Chainable method calls for more readable code
|
2. **Fluent API**: Chainable method calls for more readable code
|
||||||
|
|
||||||
The following text focuses on the basic methods. For further information, take a look at
|
The following text focuses on the basic methods. For further information, take a look at
|
||||||
the [javadoc of the CfDnsClient](https://cloudflaredns-java-f4ee3a.gitlab.io/apidocs/codes/thischwa/cf/CfDnsClient.html).
|
the \
|
||||||
|
[](https://javadoc.mein-gateway.de/CloudflareDNS-java/index.html)
|
||||||
|
|
||||||
### Instantiation of `CfDnsClient`
|
### Instantiation of `CfDnsClient`
|
||||||
|
|
||||||
@@ -110,6 +62,15 @@ CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
|||||||
.build();
|
.build();
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The client is thread-safe and should be reused, it holds a pool of HTTP connections.
|
||||||
|
`CfDnsClient` implements `AutoCloseable`, call `close()` (or use try-with-resources) to release the connections:
|
||||||
|
|
||||||
|
```java
|
||||||
|
try (CfDnsClient cfDnsClient = new CfDnsClientBuilder().withApiTokenAuth("your-api-token").build()) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
### `zoneList`
|
### `zoneList`
|
||||||
|
|
||||||
Retrieve all zones within the Cloudflare account.
|
Retrieve all zones within the Cloudflare account.
|
||||||
@@ -121,6 +82,12 @@ List<ZoneEntity> zones = cfDnsClient.zoneList();
|
|||||||
zones.forEach(zone -> System.out.println("Zone: " + zone.getName()));
|
zones.forEach(zone -> System.out.println("Zone: " + zone.getName()));
|
||||||
```
|
```
|
||||||
|
|
||||||
|
By default, up to 1000 zones are fetched in a single request. Use a `PagingRequest` to control paging:
|
||||||
|
|
||||||
|
```java
|
||||||
|
List<ZoneEntity> zones = cfDnsClient.zoneList(PagingRequest.of(1, 50)); // page 1, 50 zones per page
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### `zoneGet`
|
### `zoneGet`
|
||||||
@@ -142,65 +109,109 @@ System.out.println("Zone ID: " + zone.getId());
|
|||||||
|
|
||||||
Retrieve records for a given zone. There are two variants:
|
Retrieve records for a given zone. There are two variants:
|
||||||
|
|
||||||
#### List by SLD
|
#### List by subdomain (`recordListBySubdomain`)
|
||||||
Retrieve all records for a specific second-level domain (SLD) under a given zone.
|
Retrieve all records for a specific subdomain under a given zone, optionally filtered by record types.
|
||||||
|
|
||||||
- **Parameters**:
|
- **Parameters**:
|
||||||
- `ZoneEntity zone` - The zone object.
|
- `ZoneEntity zone` - The zone object.
|
||||||
- `String sld` - Second-level domain (e.g., "www" in "www.example.com").
|
- `String subdomain` - The subdomain relative to the zone (e.g., "www" in "www.example.com"
|
||||||
|
or "my.sub" in "my.sub.example.com"). Use `CfDnsClient.APEX` (`"@"`) for the zone apex.
|
||||||
|
- `RecordType... types` - Optional record types to filter by. If not specified, returns all record types.
|
||||||
- **Returns**: A list of `RecordEntity` objects.
|
- **Returns**: A list of `RecordEntity` objects.
|
||||||
|
|
||||||
```java
|
```java
|
||||||
List<RecordEntity> records = cfDnsClient.recordList(zone, "sld");
|
// Get all records for a specific subdomain
|
||||||
records.forEach(record ->
|
List<RecordEntity> wwwRecords = cfDnsClient.recordListBySubdomain(zone, "www");
|
||||||
System.out.println("Record Type: "+record.getType()
|
|
||||||
+", Value: "+record.getContent())
|
// Get only A records for a specific subdomain
|
||||||
);
|
List<RecordEntity> wwwARecords = cfDnsClient.recordListBySubdomain(zone, "www", RecordType.A);
|
||||||
|
|
||||||
|
// Get the records of the zone apex (e.g. "example.com")
|
||||||
|
List<RecordEntity> apexRecords = cfDnsClient.recordListBySubdomain(zone, CfDnsClient.APEX);
|
||||||
```
|
```
|
||||||
|
|
||||||
#### List by Zone (optional filtering)
|
#### List by type (`recordListByType`)
|
||||||
Retrieve DNS record details for a zone or a specific SLD, optionally filtered by record types.
|
Retrieve all records of a zone, optionally filtered by record types.
|
||||||
|
|
||||||
- **Parameters**:
|
|
||||||
- `ZoneEntity zone` - The zone object.
|
|
||||||
- `String sld` - (Optional) The second-level domain.
|
|
||||||
- `RecordType... types` - Optional record types to filter by (e.g., A, CNAME). If not specified, returns all record types.
|
|
||||||
- **Returns**: A list of `RecordEntity` objects matching the criteria.
|
|
||||||
|
|
||||||
```java
|
```java
|
||||||
// Get all records for a specific SLD
|
// Get only A and AAAA records of a zone
|
||||||
List<RecordEntity> allSldRecords = cfDnsClient.recordList(zone, "www");
|
List<RecordEntity> ipZoneRecords = cfDnsClient.recordListByType(zone, RecordType.A, RecordType.AAAA);
|
||||||
|
```
|
||||||
|
|
||||||
// Get only A records for a specific SLD
|
If exactly one record type is given, the filtering is done by Cloudflare, otherwise by the client.
|
||||||
List<RecordEntity> aSldRecords = cfDnsClient.recordList(zone, "www", RecordType.A);
|
|
||||||
|
|
||||||
|
#### List all records of a zone (`recordList`)
|
||||||
|
|
||||||
|
```java
|
||||||
// Get all records of a zone
|
// Get all records of a zone
|
||||||
List<RecordEntity> allZoneRecords = cfDnsClient.recordList(zone);
|
List<RecordEntity> allZoneRecords = cfDnsClient.recordList(zone);
|
||||||
|
|
||||||
// Get only A and AAAA records of a zone
|
// Get the records of a zone page by page (page 2, 100 records per page)
|
||||||
List<RecordEntity> ipZoneRecords = cfDnsClient.recordList(zone, RecordType.A, RecordType.AAAA);
|
List<RecordEntity> pagedRecords = cfDnsClient.recordList(zone, PagingRequest.of(2, 100));
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Without a `PagingRequest`, all pages are fetched and the complete result is returned.
|
||||||
|
With a `PagingRequest`, exactly the requested page is returned.
|
||||||
|
|
||||||
|
`RecordEntity#getSubdomain()` returns the record name relative to its zone, e.g. `my.sub` for
|
||||||
|
`my.sub.example.com` and `"@"` for the zone apex. The timestamps `getCreatedOn()` and `getModifiedOn()`
|
||||||
|
are of type `java.time.Instant` (UTC).
|
||||||
|
|
||||||
|
#### Group by FQDN
|
||||||
|
|
||||||
|
The static helper `CfDnsClient.groupRecordsByFqdn` groups a list of records by their fully qualified domain name:
|
||||||
|
|
||||||
|
```java
|
||||||
|
Map<String, List<RecordEntity>> byFqdn = CfDnsClient.groupRecordsByFqdn(cfDnsClient.recordList(zone));
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### `recordCreate`
|
### `recordCreateSubdomain` / `recordCreate`
|
||||||
|
|
||||||
Create a new DNS record in a specific zone.
|
Create a new DNS record in a specific zone.
|
||||||
|
|
||||||
- **Parameters**:
|
- **Parameters**:
|
||||||
- `ZoneEntity zone` - DNS zone object.
|
- `ZoneEntity zone` - The DNS zone object.
|
||||||
- `String sld` - The sub-tld of the new record.
|
- `String subdomain` - The subdomain of the new record relative to the zone (e.g., "api" in "api.example.com").
|
||||||
- `int ttl` - The time-to-live in seconds of the new rcord.
|
- `int ttl` - The time-to-live in seconds of the new record.
|
||||||
|
- `RecordType type` - The record type (e.g., A, AAAA, CNAME).
|
||||||
|
- `String content` - The content of the record (e.g., the IP address of an A record).
|
||||||
|
- **Returns**: The created `RecordEntity`.
|
||||||
|
|
||||||
```java
|
```java
|
||||||
RecordEntity created = client.recordCreateSld(zone, "api", 60, RecordType.A, "192.168.1.1");
|
RecordEntity created = cfDnsClient.recordCreateSubdomain(zone, "api", 60, RecordType.A, "192.168.1.1");
|
||||||
System.out.println("Created Record ID: " + created.getId());
|
System.out.println("Created Record ID: " + created.getId());
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Alternatively, the record can be created with its fully qualified name or from a `RecordEntity`:
|
||||||
|
|
||||||
|
```java
|
||||||
|
cfDnsClient.recordCreate(zone, "api.example.com", 60, RecordType.A, "192.168.1.1");
|
||||||
|
cfDnsClient.recordCreate(zone, RecordEntity.build("api.example.com", RecordType.A, 60, "192.168.1.1"));
|
||||||
|
```
|
||||||
|
|
||||||
|
Records which need more than a content, like MX, SRV or CAA records, can be created from a `RecordEntity`.
|
||||||
|
Besides `priority` and `data`, the attributes `proxied`, `comment` and `tags` are supported:
|
||||||
|
|
||||||
|
```java
|
||||||
|
// MX record with priority
|
||||||
|
RecordEntity mx = RecordEntity.build("example.com", RecordType.MX, 3600, "mail.example.com");
|
||||||
|
mx.setPriority(10);
|
||||||
|
cfDnsClient.recordCreate(zone, mx);
|
||||||
|
|
||||||
|
// SRV record with structured data (keys as in the Cloudflare API), the priority is part of the data
|
||||||
|
RecordEntity srv = RecordEntity.build("_sip._tcp.example.com", RecordType.SRV, 3600, null);
|
||||||
|
srv.setData(Map.of("priority", 10, "weight", 5, "port", 5060, "target", "sip.example.com"));
|
||||||
|
cfDnsClient.recordCreate(zone, srv);
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### `recordUpdate`
|
### `recordUpdate`
|
||||||
|
|
||||||
Update an existing DNS record.
|
Update an existing DNS record (partial update: attributes which are `null` remain unchanged).
|
||||||
|
Read-only attributes like timestamps are ignored, the given `RecordEntity` isn't modified.
|
||||||
|
|
||||||
- **Parameters**:
|
- **Parameters**:
|
||||||
- `ZoneEntity zone` - The zone that contains the record.
|
- `ZoneEntity zone` - The zone that contains the record.
|
||||||
@@ -227,19 +238,25 @@ boolean isDeleted = cfDnsClient.recordDelete(zone, record);
|
|||||||
System.out.println(isDeleted ? "Deletion successful." : "Deletion failed.");
|
System.out.println(isDeleted ? "Deletion successful." : "Deletion failed.");
|
||||||
```
|
```
|
||||||
|
|
||||||
|
If only the ID is known, the record can be deleted by its ID:
|
||||||
|
|
||||||
|
```java
|
||||||
|
cfDnsClient.recordDelete(zone, record.getId());
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### `recordDeleteTypeIfExists`
|
### `recordDeleteTypeIfExists`
|
||||||
|
|
||||||
Delete a DNS record of a specific type if it exists.
|
Delete the DNS records of the given types if they exist.
|
||||||
|
|
||||||
- **Parameters**:
|
- **Parameters**:
|
||||||
- `ZoneEntity zone` - Target zone.
|
- `ZoneEntity zone` - Target zone.
|
||||||
- `String sld` - Second-level domain.
|
- `String subdomain` - The subdomain relative to the zone.
|
||||||
- `RecordType type` - Record type.
|
- `RecordType... types` - One or more record types.
|
||||||
|
|
||||||
```java
|
```java
|
||||||
cfDnsClient.recordDeleteTypeIfExists(zone, "api", RecordType.A);
|
cfDnsClient.recordDeleteTypeIfExists(zone, "api", RecordType.A, RecordType.AAAA);
|
||||||
System.out.println("Deletion attempt completed.");
|
System.out.println("Deletion attempt completed.");
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -278,8 +295,8 @@ Partially update existing records. **Record IDs are required** - fetch them firs
|
|||||||
```java
|
```java
|
||||||
// Step 1: Fetch existing records to get their IDs
|
// Step 1: Fetch existing records to get their IDs
|
||||||
List<RecordEntity> recordsToUpdate = new ArrayList<>();
|
List<RecordEntity> recordsToUpdate = new ArrayList<>();
|
||||||
recordsToUpdate.add(cfDnsClient.recordList(zone, "api",RecordType.A).get(0));
|
recordsToUpdate.add(cfDnsClient.recordListBySubdomain(zone, "api",RecordType.A).get(0));
|
||||||
recordsToUpdate.add(cfDnsClient.recordList(zone, "cdn",RecordType.A).get(0));
|
recordsToUpdate.add(cfDnsClient.recordListBySubdomain(zone, "cdn",RecordType.A).get(0));
|
||||||
|
|
||||||
// Step 2: Modify only the fields you want to update
|
// Step 2: Modify only the fields you want to update
|
||||||
recordsToUpdate.forEach(record ->record.setContent("192.168.2.10"));
|
recordsToUpdate.forEach(record ->record.setContent("192.168.2.10"));
|
||||||
@@ -296,8 +313,8 @@ Fully replace existing records. **Record IDs are required** - fetch them first:
|
|||||||
```java
|
```java
|
||||||
// Step 1: Fetch existing records to get their IDs
|
// Step 1: Fetch existing records to get their IDs
|
||||||
List<RecordEntity> recordsToReplace = new ArrayList<>();
|
List<RecordEntity> recordsToReplace = new ArrayList<>();
|
||||||
recordsToReplace.add(cfDnsClient.recordList(zone, "mail",RecordType.A).get(0));
|
recordsToReplace.add(cfDnsClient.recordListBySubdomain(zone, "mail",RecordType.A).get(0));
|
||||||
recordsToReplace.add(cfDnsClient.recordList(zone, "cdn",RecordType.A).get(0));
|
recordsToReplace.add(cfDnsClient.recordListBySubdomain(zone, "cdn",RecordType.A).get(0));
|
||||||
|
|
||||||
// Step 2: Modify all fields as needed (full replacement)
|
// Step 2: Modify all fields as needed (full replacement)
|
||||||
recordsToReplace.get(0).setContent("192.168.3.10");
|
recordsToReplace.get(0).setContent("192.168.3.10");
|
||||||
@@ -317,8 +334,8 @@ Delete existing records. **Record IDs are required** - fetch them first:
|
|||||||
```java
|
```java
|
||||||
// Step 1: Fetch existing records to get their IDs
|
// Step 1: Fetch existing records to get their IDs
|
||||||
List<RecordEntity> recordsToDelete = new ArrayList<>();
|
List<RecordEntity> recordsToDelete = new ArrayList<>();
|
||||||
recordsToDelete.add(cfDnsClient.recordList(zone, "cdn",RecordType.A).get(0));
|
recordsToDelete.add(cfDnsClient.recordListBySubdomain(zone, "cdn",RecordType.A).get(0));
|
||||||
recordsToDelete.add(cfDnsClient.recordList(zone, "mail",RecordType.A).get(0));
|
recordsToDelete.add(cfDnsClient.recordListBySubdomain(zone, "mail",RecordType.A).get(0));
|
||||||
|
|
||||||
// Step 2: Send batch delete request
|
// Step 2: Send batch delete request
|
||||||
BatchEntry result = cfDnsClient.recordBatch(zone, null, null, null, recordsToDelete);
|
BatchEntry result = cfDnsClient.recordBatch(zone, null, null, null, recordsToDelete);
|
||||||
@@ -337,12 +354,12 @@ List<RecordEntity> newRecords = Arrays.asList(
|
|||||||
|
|
||||||
// Fetch existing records for update/delete (IDs required)
|
// Fetch existing records for update/delete (IDs required)
|
||||||
List<RecordEntity> recordsToUpdate = Arrays.asList(
|
List<RecordEntity> recordsToUpdate = Arrays.asList(
|
||||||
cfDnsClient.recordList(zone, "existing-api", RecordType.A).get(0)
|
cfDnsClient.recordListBySubdomain(zone, "existing-api", RecordType.A).get(0)
|
||||||
);
|
);
|
||||||
recordsToUpdate.get(0).setContent("192.168.1.200");
|
recordsToUpdate.get(0).setContent("192.168.1.200");
|
||||||
|
|
||||||
List<RecordEntity> recordsToDelete = Arrays.asList(
|
List<RecordEntity> recordsToDelete = Arrays.asList(
|
||||||
cfDnsClient.recordList(zone, "old-api", RecordType.A).get(0)
|
cfDnsClient.recordListBySubdomain(zone, "old-api", RecordType.A).get(0)
|
||||||
);
|
);
|
||||||
|
|
||||||
// Execute all operations in a single batch request
|
// Execute all operations in a single batch request
|
||||||
@@ -370,28 +387,28 @@ that reduces verbosity and improves code readability.
|
|||||||
### Basic Usage
|
### Basic Usage
|
||||||
|
|
||||||
```java
|
```java
|
||||||
// Create a DNS getRecord
|
// Create a DNS record
|
||||||
client.zone("example.com")
|
client.zone("example.com")
|
||||||
.record("api")
|
.getRecord("api")
|
||||||
.create(RecordType.A, "192.168.1.1",60);
|
.create(RecordType.A, "192.168.1.1",60);
|
||||||
|
|
||||||
// Get DNS records of a subdomain
|
// Get DNS records of a subdomain
|
||||||
List<RecordEntity> records = client.zone("example.com")
|
List<RecordEntity> records = client.zone("example.com")
|
||||||
.record("www", RecordType.A)
|
.getRecord("www", RecordType.A)
|
||||||
.get();
|
.get();
|
||||||
|
|
||||||
// Get all DNS records of a zone
|
// Get all DNS records of a zone
|
||||||
List<RecordEntity> zoneRecords = client.zone("example.com")
|
List<RecordEntity> zoneRecords = client.zone("example.com")
|
||||||
.list(RecordType.A, RecordType.AAAA);
|
.list(RecordType.A, RecordType.AAAA);
|
||||||
|
|
||||||
// Update a DNS getRecord
|
// Update a DNS record
|
||||||
RecordEntity updated = client.zone("example.com")
|
RecordEntity updated = client.zone("example.com")
|
||||||
.record("api", RecordType.A)
|
.getRecord("api", RecordType.A)
|
||||||
.update("192.168.1.2");
|
.update("192.168.1.2");
|
||||||
|
|
||||||
// Delete DNS records
|
// Delete DNS records
|
||||||
client.zone("example.com")
|
client.zone("example.com")
|
||||||
.record("old-service")
|
.getRecord("old-service")
|
||||||
.delete(RecordType.A, RecordType.AAAA);
|
.delete(RecordType.A, RecordType.AAAA);
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -409,25 +426,25 @@ CfDnsClient client = new CfDnsClientBuilder()
|
|||||||
.withApiTokenAuth("your-api-token")
|
.withApiTokenAuth("your-api-token")
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
// Create a new getRecord
|
// Create a new record
|
||||||
client.zone("example.com")
|
client.zone("example.com")
|
||||||
.record("api")
|
.getRecord("api")
|
||||||
.create(RecordType.A, "192.168.100.1",60);
|
.create(RecordType.A, "192.168.100.1",60);
|
||||||
|
|
||||||
// Retrieve and verify
|
// Retrieve and verify
|
||||||
List<RecordEntity> records = client.zone("example.com")
|
List<RecordEntity> records = client.zone("example.com")
|
||||||
.record("api", RecordType.A)
|
.getRecord("api", RecordType.A)
|
||||||
.get();
|
.get();
|
||||||
System.out.println("IP: "+records.get(0).getContent());
|
System.out.println("IP: "+records.get(0).getContent());
|
||||||
|
|
||||||
// Update the getRecord
|
// Update the record
|
||||||
client.zone("example.com")
|
client.zone("example.com")
|
||||||
.record("api",RecordType.A)
|
.getRecord("api",RecordType.A)
|
||||||
.update("192.168.100.2");
|
.update("192.168.100.2");
|
||||||
|
|
||||||
// Clean up
|
// Clean up
|
||||||
client.zone("example.com")
|
client.zone("example.com")
|
||||||
.record("api")
|
.getRecord("api")
|
||||||
.delete(RecordType.A);
|
.delete(RecordType.A);
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -437,7 +454,10 @@ client.zone("example.com")
|
|||||||
|
|
||||||
The `CfDnsClient` provides internal error-handling mechanisms through exceptions. For example:
|
The `CfDnsClient` provides internal error-handling mechanisms through exceptions. For example:
|
||||||
- `CloudflareApiException` is thrown for errors during API communication or invalid responses.
|
- `CloudflareApiException` is thrown for errors during API communication or invalid responses.
|
||||||
- `CloudflareNotFoundException` is thrown when the requested resource (single or multiple) is not found, if enabled via the `emptyResultThrowsException` flag during initialization. **Default is `false`**, meaning empty results will be returned without throwing an exception.
|
`getStatusCode()` returns the HTTP status code (or `CloudflareApiException.NO_STATUS_CODE` if there was no response)
|
||||||
|
and `getErrors()` the error codes and messages reported by Cloudflare.
|
||||||
|
- `CloudflareNotFoundException` is thrown if Cloudflare responds with HTTP status 404 (e.g. deleting a non-existing record).
|
||||||
|
- `CloudflareNotFoundException` is also thrown when the requested resource (single or multiple) is not found, if enabled via the `emptyResultThrowsException` flag during initialization. **Default is `false`**, meaning empty results will be returned without throwing an exception.
|
||||||
|
|
||||||
To enable exception throwing for empty results:
|
To enable exception throwing for empty results:
|
||||||
|
|
||||||
@@ -452,13 +472,14 @@ CfDnsClient client = new CfDnsClientBuilder()
|
|||||||
|
|
||||||
```java
|
```java
|
||||||
try {
|
try {
|
||||||
List<RecordEntity> records = cfDnsClient.recordList(zone, "www", RecordType.A);
|
List<RecordEntity> records = cfDnsClient.recordListBySubdomain(zone, "www", RecordType.A);
|
||||||
System.out.println("Record IP: "+records.get(0).getContent());
|
System.out.println("Record IP: "+records.get(0).getContent());
|
||||||
} catch (CloudflareApiException e) {
|
} catch (CloudflareApiException e) {
|
||||||
if (e instanceof CloudflareNotFoundException) {
|
if (e instanceof CloudflareNotFoundException) {
|
||||||
log.warn("Sld not found: www");
|
log.warn("Subdomain not found: www");
|
||||||
} else {
|
} else {
|
||||||
log.error("Error while getting sld info of www", e);
|
log.error("Error while getting records of subdomain www (HTTP status {}, errors {})",
|
||||||
|
e.getStatusCode(), e.getErrors(), e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -466,6 +487,3 @@ try {
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
# Summary
|
|
||||||
|
|
||||||
`CfDnsClient` offers a simple interface for managing DNS entries via Cloudflare's public API, allowing seamless CRUD operations and automation-friendly workflows.
|
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
- 0.6.0-SNAPSHOT:
|
||||||
|
- **Breaking Changes**:
|
||||||
|
- `recordList` overloads replaced, because they were ambiguous (e.g. `recordList(zone, null)` didn't compile):
|
||||||
|
- `recordList(zone, String subdomain, RecordType... types)` and `recordList(zone, String subdomain)` → `recordListBySubdomain(zone, subdomain, types...)`
|
||||||
|
- `recordList(zone, RecordType... types)` → `recordListByType(zone, types...)`
|
||||||
|
- `recordList(zone)` and `recordList(zone, PagingRequest)` remain unchanged
|
||||||
|
- timestamps of `RecordEntity` and `ZoneEntity` (`createdOn`, `modifiedOn`, `activatedOn`) are of type `java.time.Instant` instead of `LocalDateTime`, so the time zone (UTC) isn't lost anymore
|
||||||
|
- Cloudflare responses with HTTP status 404 throw a `CloudflareNotFoundException` (independent of `emptyResultThrowsException`)
|
||||||
|
- unexpected runtime exceptions aren't wrapped into a `CloudflareApiException("Unexpected error!")` anymore
|
||||||
|
- batch DELETE sends only the record IDs, batch PATCH sends all writable attributes which aren't `null` (before: only the content)
|
||||||
|
- `CfDnsClient` uses one shared HTTP client with connection pooling instead of a new one per request and implements `AutoCloseable`, call `close()` to release the connections
|
||||||
|
- `CloudflareApiException` provides the HTTP status code (`getStatusCode()`) and the errors reported by Cloudflare (`getErrors()`)
|
||||||
|
- `RecordEntity` supports the attributes `priority` (MX, URI), `data` (e.g. SRV incl. its priority, CAA), `comment` and `tags`; they are also considered by batch operations, as is `proxied`
|
||||||
|
- `recordCreate` and `recordUpdate` don't modify the given `RecordEntity` anymore and send only writable attributes
|
||||||
|
- fluent `update(content)` sends only the new content (partial update)
|
||||||
|
- filtering by exactly one record type is done by Cloudflare (`?type=`), unknown record types in responses don't break the client-side filter anymore
|
||||||
|
- updated dependencies: jackson 3.2.4, httpclient5 5.6.4, lombok 1.18.48, logback-classic 1.6.6, mockito-junit-jupiter 5.24.0
|
||||||
|
- updated maven plugins: maven-compiler-plugin 3.16.0, maven-surefire-plugin 3.6.0, maven-jar-plugin 3.5.1
|
||||||
|
- README: fixed fluent API examples, documented paging and further methods
|
||||||
|
- fixed "getRecord" wording in javadoc, log and exception messages (e.g. "Invalid record type")
|
||||||
|
- **Deprecation**: the misleading term "sld" was renamed to "subdomain", the old methods will be removed in a future release:
|
||||||
|
- `RecordEntity#getSld()` → `RecordEntity#getSubdomain()`
|
||||||
|
- `CfDnsClient#recordCreateSld(...)` → `CfDnsClient#recordCreateSubdomain(...)`
|
||||||
|
- `getSubdomain()` returns `"@"` for the zone apex; `CfDnsClient.APEX` can be used to address the zone apex
|
||||||
|
- fixed: API errors were wrapped into a generic "Unexpected error!" exception
|
||||||
|
- fixed: `zoneGet` threw an `IndexOutOfBoundsException` for unknown zones, it now returns `null` or throws a `CloudflareNotFoundException` (depending on `emptyResultThrowsException`)
|
||||||
|
- fixed: `getSubdomain()` failed for apex records and records with multi-level subdomains, batch operations now send the full record name
|
||||||
|
- fixed: `zoneList()` and `recordList(...)` without `PagingRequest` returned only the first page, now all pages are fetched
|
||||||
|
- fixed: `recordDelete` threw a `NullPointerException` for an empty result
|
||||||
|
- 0.5.0:
|
||||||
|
- moved the project to git.mein-gateway.de
|
||||||
|
- replaced sonarqube with own actions
|
||||||
|
- migrate to jackson 3.x
|
||||||
|
- 0.4.0:
|
||||||
|
- fixed some paging issues
|
||||||
|
- **Breaking Change**: renamed `client.zone().record()` to `client.zone().getRecord()`
|
||||||
|
- Code quality improvements: Increasing test coverage
|
||||||
|
- 0.3.0:
|
||||||
|
- **Breaking Change**:
|
||||||
|
- **New Fluent API**: Changed the initialization of the client(`new CfDnsClientBuilder().withApiTokenAuth("your-api-token").build()`)
|
||||||
|
- Authentication with API token.
|
||||||
|
- 0.2.0:
|
||||||
|
- **Breaking Change**: `emptyResultThrowsException` default changed from `true` to `false`. Now applies to both
|
||||||
|
single and multiple result requests. Empty results will be returned by default without throwing exceptions.
|
||||||
|
- API method names refactored for consistency: `zoneListAll` → `zoneList`, `zoneInfo` → `zoneGet`, `sldListAll` →
|
||||||
|
`recordList`
|
||||||
|
- RecordEntity getter methods renamed for clarity: `getName()` → `getSld()`
|
||||||
|
- **New Fluent API**: Changed the initialization of the client(`new CfDnsClientBuilder().withApiTokenAuth("your-api-token").build()`) and added chainable method interface for more readable DNS operations (
|
||||||
|
`client.zone().record()...`)
|
||||||
|
- Code quality improvements: removed duplication in batch operations, improved type safety in HTTP methods,
|
||||||
|
optimized string concatenation, removed mutable setters from CfDnsClient
|
||||||
|
- Enhanced type validation in `RecordEntity.build()` with better error messages
|
||||||
|
- CfClient#recordList must return multiple RecordEntries
|
||||||
|
- add a missing source jar
|
||||||
|
- ResponseResultInfo#Errors: wrong object structure
|
||||||
|
- changing multiple records with put, post, patch and delete for dns-records
|
||||||
|
- 0.1.0:
|
||||||
|
- refactored / extended tests
|
||||||
|
- 0.1.0-beta.3:
|
||||||
|
- fixed json deserialization
|
||||||
|
- added logging of api errors
|
||||||
|
- 0.1.0-beta.1: 1st runnable version
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 19 KiB |
@@ -1,15 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
||||||
<title>Cloudflare DNS Client - java</title>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>Cloudflare DNS Client - java</h1>
|
|
||||||
<p>A Java-based client for interacting with the Cloudflare DNS API.</p>
|
|
||||||
<p>
|
|
||||||
<a href="apidocs/index.html" target="_blank">View API Documentation</a>
|
|
||||||
</p>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -4,18 +4,20 @@
|
|||||||
|
|
||||||
<groupId>codes.thischwa</groupId>
|
<groupId>codes.thischwa</groupId>
|
||||||
<artifactId>cloudflaredns</artifactId>
|
<artifactId>cloudflaredns</artifactId>
|
||||||
<version>0.4.0</version>
|
<version>0.6.0-SNAPSHOT</version>
|
||||||
<name>CloudflareDNS-java</name>
|
<name>CloudflareDNS-java</name>
|
||||||
<inceptionYear>2025</inceptionYear>
|
<inceptionYear>2025</inceptionYear>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<issueManagement>
|
<issueManagement>
|
||||||
<url>https://codeberg.org/th-schwarz/CloudflareDNS-java/issues</url>
|
<url>https://github.com/th-schwarz/CloudflareDNS-java/issues</url>
|
||||||
<system>Codeberg Issues</system>
|
<system>GitHub Issues</system>
|
||||||
</issueManagement>
|
</issueManagement>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<java.version>17</java.version>
|
<java.version>17</java.version>
|
||||||
|
<maven.compiler.source>${java.version}</maven.compiler.source>
|
||||||
|
<maven.compiler.target>${java.version}</maven.compiler.target>
|
||||||
<file.encoding>UTF-8</file.encoding>
|
<file.encoding>UTF-8</file.encoding>
|
||||||
<project.build.sourceEncoding>${file.encoding}</project.build.sourceEncoding>
|
<project.build.sourceEncoding>${file.encoding}</project.build.sourceEncoding>
|
||||||
<project.reporting.outputEncoding>${file.encoding}</project.reporting.outputEncoding>
|
<project.reporting.outputEncoding>${file.encoding}</project.reporting.outputEncoding>
|
||||||
@@ -34,44 +36,35 @@
|
|||||||
<linkXRef>false</linkXRef>
|
<linkXRef>false</linkXRef>
|
||||||
|
|
||||||
<!-- 3rd party dependencies -->
|
<!-- 3rd party dependencies -->
|
||||||
<jackson.version>2.21.1</jackson.version>
|
<jackson.version>3.2.4</jackson.version>
|
||||||
<httpclient5.version>5.5.1</httpclient5.version>
|
<httpclient5.version>5.6.4</httpclient5.version>
|
||||||
<lombok.version>1.18.36</lombok.version>
|
<lombok.version>1.18.48</lombok.version>
|
||||||
<slf4j.version>2.0.17</slf4j.version>
|
<slf4j.version>2.0.18</slf4j.version>
|
||||||
<logback-classic.version>1.5.25</logback-classic.version>
|
<logback-classic.version>1.6.6</logback-classic.version>
|
||||||
<junit5.version>5.14.2</junit5.version>
|
<junit5.version>5.14.2</junit5.version>
|
||||||
<mockito-junit5.version>5.21.0</mockito-junit5.version>
|
<mockito-junit5.version>5.24.0</mockito-junit5.version>
|
||||||
|
|
||||||
<!-- sonarqube -->
|
|
||||||
<sonar.organization>th-schwarz</sonar.organization>
|
|
||||||
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
|
|
||||||
<sonar.sourceEncoding>${file.encoding}</sonar.sourceEncoding>
|
|
||||||
<sonar.projectKey>th-schwarz_CloudflareDNS-java</sonar.projectKey>
|
|
||||||
<sonar.projectName>CloudflareDNS-java</sonar.projectName>
|
|
||||||
<sonar.branch.name>develop</sonar.branch.name>
|
|
||||||
<sonar.test.exclusions>src/test/java/**/*</sonar.test.exclusions>
|
|
||||||
|
|
||||||
<lombok-maven-plugin.version>1.18.20.0</lombok-maven-plugin.version>
|
<lombok-maven-plugin.version>1.18.20.0</lombok-maven-plugin.version>
|
||||||
|
<jetbrains-annotations.version>26.1.0</jetbrains-annotations.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<scm>
|
<scm>
|
||||||
<developerConnection>scm:git:git@codeberg.org:th-schwarz/CloudflareDNS-java.git</developerConnection>
|
<developerConnection>scm:git:https://git.mein-gateway.de/thischwa/CloudflareDNS-java.git</developerConnection>
|
||||||
<connection>scm:git:git@codeberg.org:th-schwarz/CloudflareDNS-java.git</connection>
|
<connection>scm:git:https://git.mein-gateway.de/thischwa/CloudflareDNS-java.git</connection>
|
||||||
<url>https://codeberg.org/th-schwarz/CloudflareDNS-java</url>
|
<url>https://git.mein-gateway.de/thischwa/CloudflareDNS-java</url>
|
||||||
<tag>v0.4.0</tag>
|
<tag>HEAD</tag>
|
||||||
</scm>
|
</scm>
|
||||||
|
|
||||||
<distributionManagement>
|
<distributionManagement>
|
||||||
<repository>
|
<repository>
|
||||||
<id>codeberg-cloudflaredns</id>
|
<id>mygitea</id>
|
||||||
<url>https://codeberg.org/api/packages/th-schwarz/maven</url>
|
<url>https://git.mein-gateway.de/api/packages/thischwa/maven</url>
|
||||||
<releases>
|
<releases>
|
||||||
<enabled>true</enabled>
|
<enabled>true</enabled>
|
||||||
</releases>
|
</releases>
|
||||||
</repository>
|
</repository>
|
||||||
<snapshotRepository>
|
<snapshotRepository>
|
||||||
<id>codeberg-cloudflaredns</id>
|
<id>mygitea</id>
|
||||||
<url>https://codeberg.org/api/packages/th-schwarz/maven</url>
|
<url>https://git.mein-gateway.de/api/packages/thischwa/maven</url>
|
||||||
<snapshots>
|
<snapshots>
|
||||||
<enabled>true</enabled>
|
<enabled>true</enabled>
|
||||||
</snapshots>
|
</snapshots>
|
||||||
@@ -103,19 +96,14 @@
|
|||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.fasterxml.jackson.core</groupId>
|
<groupId>tools.jackson.core</groupId>
|
||||||
<artifactId>jackson-databind</artifactId>
|
<artifactId>jackson-databind</artifactId>
|
||||||
<version>${jackson.version}</version>
|
<version>${jackson.version}</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
|
||||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
|
||||||
<version>${jackson.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.jetbrains</groupId>
|
<groupId>org.jetbrains</groupId>
|
||||||
<artifactId>annotations</artifactId>
|
<artifactId>annotations</artifactId>
|
||||||
<version>24.0.0</version>
|
<version>${jetbrains-annotations.version}</version>
|
||||||
<scope>compile</scope>
|
<scope>compile</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
@@ -144,7 +132,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.13.0</version>
|
<version>3.16.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>${java.version}</source>
|
<source>${java.version}</source>
|
||||||
<target>${java.version}</target>
|
<target>${java.version}</target>
|
||||||
@@ -154,7 +142,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-javadoc-plugin</artifactId>
|
<artifactId>maven-javadoc-plugin</artifactId>
|
||||||
<version>3.11.2</version>
|
<version>3.12.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<failOnError>false</failOnError>
|
<failOnError>false</failOnError>
|
||||||
<failOnWarnings>false</failOnWarnings>
|
<failOnWarnings>false</failOnWarnings>
|
||||||
@@ -208,7 +196,7 @@
|
|||||||
<!-- generates the code coverage report for sonar cube -->
|
<!-- generates the code coverage report for sonar cube -->
|
||||||
<groupId>org.jacoco</groupId>
|
<groupId>org.jacoco</groupId>
|
||||||
<artifactId>jacoco-maven-plugin</artifactId>
|
<artifactId>jacoco-maven-plugin</artifactId>
|
||||||
<version>0.8.13</version>
|
<version>0.8.15</version>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<id>prepare-agent</id>
|
<id>prepare-agent</id>
|
||||||
@@ -233,7 +221,7 @@
|
|||||||
<!-- to export test summary -->
|
<!-- to export test summary -->
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>3.5.3</version>
|
<version>3.6.0</version>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
<plugin>
|
<plugin>
|
||||||
@@ -267,7 +255,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-jar-plugin</artifactId>
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
<version>3.4.2</version>
|
<version>3.5.1</version>
|
||||||
<executions>
|
<executions>
|
||||||
<execution>
|
<execution>
|
||||||
<id>attach-delomboked-sources</id>
|
<id>attach-delomboked-sources</id>
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Test Report
|
||||||
|
|
||||||
|
_Generated on 2026-11-03 17:19:07 UTC_
|
||||||
|
|
||||||
|
**✅ All tests passed**
|
||||||
|
|
||||||
|
## Test Results
|
||||||
|
|
||||||
|
| | Tests | Passed | Failed | Skipped |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| **Total** | 143 | 121 | 0 | 22 |
|
||||||
|
|
||||||
|
### Details
|
||||||
|
|
||||||
|
| Status | Suite | Tests | Passed | Failed | Skipped |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| ✅ | codes.thischwa.cf.CfBasicHttpClientErrorTest | 5 | 5 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.CfBasicHttpClientTest | 9 | 9 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.CfClientPenTest | 4 | 0 | 0 | 4 |
|
||||||
|
| ✅ | codes.thischwa.cf.CfClientTest | 18 | 0 | 0 | 18 |
|
||||||
|
| ✅ | codes.thischwa.cf.CfDnsClientBuilderTest | 16 | 16 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.CfDnsClientMockTest | 33 | 33 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.CfRequestTest | 8 | 8 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.ObjectMapperTest | 4 | 4 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.ResponseValidatorTest | 11 | 11 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.fluent.FluentApiTest | 15 | 15 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.model.BatchEntryTest | 2 | 2 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.model.PagingRequestTest | 4 | 4 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.model.RecordEntityTest | 10 | 10 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.model.RecordTypeTest | 3 | 3 | 0 | 0 |
|
||||||
|
| ✅ | codes.thischwa.cf.model.ZoneEntityTest | 1 | 1 | 0 | 0 |
|
||||||
|
|
||||||
|
## Coverage
|
||||||
|
|
||||||
|
| Package | Line Coverage | Branch Coverage |
|
||||||
|
|---|---|---|
|
||||||
|
| codes.thischwa.cf.fluent | 100% (23/23) | 100% (4/4) |
|
||||||
|
| codes.thischwa.cf.model | 100% (97/97) | 93% (13/14) |
|
||||||
|
| codes.thischwa.cf | 91% (304/334) | 84% (114/136) |
|
||||||
@@ -1,9 +1,11 @@
|
|||||||
package codes.thischwa.cf;
|
package codes.thischwa.cf;
|
||||||
|
|
||||||
import codes.thischwa.cf.model.AbstractResponse;
|
import codes.thischwa.cf.model.AbstractResponse;
|
||||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import java.io.IOException;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
import org.apache.hc.client5.http.classic.methods.HttpDelete;
|
||||||
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
import org.apache.hc.client5.http.classic.methods.HttpGet;
|
||||||
@@ -16,22 +18,29 @@ import org.apache.hc.core5.http.ClassicHttpRequest;
|
|||||||
import org.apache.hc.core5.http.ClassicHttpResponse;
|
import org.apache.hc.core5.http.ClassicHttpResponse;
|
||||||
import org.apache.hc.core5.http.ContentType;
|
import org.apache.hc.core5.http.ContentType;
|
||||||
import org.apache.hc.core5.http.HttpHeaders;
|
import org.apache.hc.core5.http.HttpHeaders;
|
||||||
|
import org.apache.hc.core5.http.HttpStatus;
|
||||||
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
import org.apache.hc.core5.http.io.entity.EntityUtils;
|
||||||
import org.apache.hc.core5.http.io.entity.StringEntity;
|
import org.apache.hc.core5.http.io.entity.StringEntity;
|
||||||
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
|
import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
|
||||||
import org.jetbrains.annotations.NotNull;
|
import org.jetbrains.annotations.NotNull;
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
import tools.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Abstract base class for creating HTTP clients to interact with the Cloudflare API. Provides
|
* Abstract base class for creating HTTP clients to interact with the Cloudflare API. Provides
|
||||||
* methods for handling GET and POST requests and includes utilities for constructing HTTP clients,
|
* methods for handling GET and POST requests and includes utilities for constructing HTTP clients,
|
||||||
* managing authentication, and handling JSON serialization.
|
* managing authentication, and handling JSON serialization.
|
||||||
|
*
|
||||||
|
* <p>One underlying HTTP client (with connection pooling) is shared for all requests. It is
|
||||||
|
* released by {@link #close()}.
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
abstract class CfBasicHttpClient {
|
abstract class CfBasicHttpClient implements AutoCloseable {
|
||||||
|
|
||||||
private final String baseUrl;
|
private final String baseUrl;
|
||||||
private final CfDnsClientBuilder.CfAuth auth;
|
private final CfDnsClientBuilder.CfAuth auth;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
private final CloseableHttpClient httpClient;
|
||||||
|
|
||||||
private record ResultWrapper(int statusCode, String responseBody) {
|
private record ResultWrapper(int statusCode, String responseBody) {
|
||||||
}
|
}
|
||||||
@@ -46,6 +55,18 @@ abstract class CfBasicHttpClient {
|
|||||||
this.baseUrl = baseUrl;
|
this.baseUrl = baseUrl;
|
||||||
this.auth = auth;
|
this.auth = auth;
|
||||||
this.objectMapper = JsonConf.initObjectMapper();
|
this.objectMapper = JsonConf.initObjectMapper();
|
||||||
|
this.httpClient = createHttpClient();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Releases the underlying HTTP client and its connections. The client must not be used anymore
|
||||||
|
* afterwards.
|
||||||
|
*
|
||||||
|
* @throws IOException if an I/O error occurs while closing the HTTP client
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
public void close() throws IOException {
|
||||||
|
httpClient.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private CloseableHttpClient createHttpClient() {
|
private CloseableHttpClient createHttpClient() {
|
||||||
@@ -63,45 +84,50 @@ abstract class CfBasicHttpClient {
|
|||||||
private <T extends AbstractResponse> T executeRequest(ClassicHttpRequest request,
|
private <T extends AbstractResponse> T executeRequest(ClassicHttpRequest request,
|
||||||
Class<T> responseType)
|
Class<T> responseType)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
String logUri = null;
|
String requestInfo = request.getMethod() + " " + request.getRequestUri();
|
||||||
try (CloseableHttpClient client = createHttpClient()) {
|
ResultWrapper result;
|
||||||
ResultWrapper result = client.execute(request,
|
try {
|
||||||
(ClassicHttpResponse response) -> new ResultWrapper(response.getCode(),
|
result = httpClient.execute(request, (ClassicHttpResponse response) -> new ResultWrapper(
|
||||||
EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8)));
|
response.getCode(),
|
||||||
|
response.getEntity() == null ? ""
|
||||||
|
: EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8)));
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new CloudflareApiException("Request failed: " + requestInfo, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean httpSuccess = result.statusCode >= 200 && result.statusCode < 300;
|
||||||
|
T respObj;
|
||||||
|
try {
|
||||||
|
respObj = objectMapper.readValue(result.responseBody, responseType);
|
||||||
|
} catch (JacksonException e) {
|
||||||
|
if (!httpSuccess) {
|
||||||
|
// e.g. an HTML error page of a proxy
|
||||||
|
throw buildException(requestInfo + " failed with status code " + result.statusCode,
|
||||||
|
result.statusCode, null);
|
||||||
|
}
|
||||||
|
throw new CloudflareApiException("Error processing JSON response of " + requestInfo, e);
|
||||||
|
}
|
||||||
|
|
||||||
T respObj = objectMapper.readValue(result.responseBody, responseType);
|
ResponseResultInfo resultInfo = respObj.getResponseResultInfo();
|
||||||
if (!respObj.getResponseResultInfo().isSuccess()) {
|
boolean apiSuccess = resultInfo != null && resultInfo.isSuccess();
|
||||||
log.error("API error.");
|
if (!httpSuccess || !apiSuccess) {
|
||||||
StringBuilder errorMessage = new StringBuilder("API error");
|
List<ResponseResultInfo.Error> errors = resultInfo == null ? null : resultInfo.getErrors();
|
||||||
if (!respObj.getResponseResultInfo().getErrors().isEmpty()) {
|
String message = "API error";
|
||||||
errorMessage.append(": ");
|
if (errors != null && !errors.isEmpty()) {
|
||||||
respObj.getResponseResultInfo().getErrors().forEach(e -> {
|
message += ": " + errors.stream().map(Object::toString).collect(Collectors.joining("; "));
|
||||||
log.error(" - {}", e.toString());
|
|
||||||
errorMessage.append(e).append("; ");
|
|
||||||
});
|
|
||||||
// Remove trailing "; "
|
|
||||||
if (errorMessage.toString().endsWith("; ")) {
|
|
||||||
errorMessage.setLength(errorMessage.length() - 2);
|
|
||||||
}
|
}
|
||||||
|
log.debug("{} failed with status code {}: {}", requestInfo, result.statusCode, message);
|
||||||
|
throw buildException(message, result.statusCode, errors);
|
||||||
}
|
}
|
||||||
throw new CloudflareApiException(errorMessage.toString());
|
|
||||||
}
|
|
||||||
logUri = request.getRequestUri();
|
|
||||||
if (result.statusCode >= 200 && result.statusCode < 300) {
|
|
||||||
return respObj;
|
return respObj;
|
||||||
} else {
|
|
||||||
log.error("{} request failed for URL {}: Status {}", request.getMethod(), request.getUri(),
|
|
||||||
result.statusCode);
|
|
||||||
throw new CloudflareApiException(
|
|
||||||
request.getMethod() + " request failed with status code: " + result.statusCode);
|
|
||||||
}
|
}
|
||||||
} catch (JsonProcessingException e) {
|
|
||||||
log.error("JSON parsing error for request to {}", logUri, e);
|
private static CloudflareApiException buildException(String message, int statusCode,
|
||||||
throw new CloudflareApiException("Error processing JSON response", e);
|
List<ResponseResultInfo.Error> errors) {
|
||||||
} catch (Exception e) {
|
if (statusCode == HttpStatus.SC_NOT_FOUND) {
|
||||||
throw new CloudflareApiException("Unexpected error!", e);
|
return new CloudflareNotFoundException(message, statusCode, errors);
|
||||||
}
|
}
|
||||||
|
return new CloudflareApiException(message, statusCode, errors);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -182,7 +208,7 @@ abstract class CfBasicHttpClient {
|
|||||||
log.trace("Request methode [{}] payload: {}", request.getMethod(), jsonPayload);
|
log.trace("Request methode [{}] payload: {}", request.getMethod(), jsonPayload);
|
||||||
request.setEntity(new StringEntity(jsonPayload,
|
request.setEntity(new StringEntity(jsonPayload,
|
||||||
ContentType.APPLICATION_JSON));
|
ContentType.APPLICATION_JSON));
|
||||||
} catch (JsonProcessingException e) {
|
} catch (JacksonException e) {
|
||||||
throw new CloudflareApiException("Error serializing JSON payload", e);
|
throw new CloudflareApiException("Error serializing JSON payload", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package codes.thischwa.cf;
|
|||||||
|
|
||||||
import codes.thischwa.cf.fluent.ZoneOperations;
|
import codes.thischwa.cf.fluent.ZoneOperations;
|
||||||
import codes.thischwa.cf.fluent.ZoneOperationsImpl;
|
import codes.thischwa.cf.fluent.ZoneOperationsImpl;
|
||||||
|
import codes.thischwa.cf.model.AbstractMultipleResponse;
|
||||||
import codes.thischwa.cf.model.AbstractResponse;
|
import codes.thischwa.cf.model.AbstractResponse;
|
||||||
import codes.thischwa.cf.model.BatchEntry;
|
import codes.thischwa.cf.model.BatchEntry;
|
||||||
import codes.thischwa.cf.model.BatchResponse;
|
import codes.thischwa.cf.model.BatchResponse;
|
||||||
@@ -10,14 +11,17 @@ import codes.thischwa.cf.model.RecordEntity;
|
|||||||
import codes.thischwa.cf.model.RecordMultipleResponse;
|
import codes.thischwa.cf.model.RecordMultipleResponse;
|
||||||
import codes.thischwa.cf.model.RecordSingleResponse;
|
import codes.thischwa.cf.model.RecordSingleResponse;
|
||||||
import codes.thischwa.cf.model.RecordType;
|
import codes.thischwa.cf.model.RecordType;
|
||||||
|
import codes.thischwa.cf.model.ResponseEntity;
|
||||||
|
import codes.thischwa.cf.model.ResultInfo;
|
||||||
import codes.thischwa.cf.model.ZoneEntity;
|
import codes.thischwa.cf.model.ZoneEntity;
|
||||||
import codes.thischwa.cf.model.ZoneMultipleResponse;
|
import codes.thischwa.cf.model.ZoneMultipleResponse;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -28,26 +32,30 @@ import org.jetbrains.annotations.Nullable;
|
|||||||
* records and zones within the Cloudflare system, including creating, updating, retrieving, and
|
* records and zones within the Cloudflare system, including creating, updating, retrieving, and
|
||||||
* deleting DNS records.
|
* deleting DNS records.
|
||||||
*
|
*
|
||||||
|
* <p>The client is thread-safe and should be reused. It holds a pool of HTTP connections, which is
|
||||||
|
* released by {@link #close()}.
|
||||||
|
*
|
||||||
* <p>Example with API token authentication (recommended):
|
* <p>Example with API token authentication (recommended):
|
||||||
* <pre><code>
|
* <pre><code>
|
||||||
* // Create a new CfDnsClient instance with API token
|
* // Create a new CfDnsClient instance with API token
|
||||||
* CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
* try (CfDnsClient cfDnsClient = new CfDnsClientBuilder()
|
||||||
* .withApiTokenAuth("your-api-token")
|
* .withApiTokenAuth("your-api-token")
|
||||||
* .build();
|
* .build()) {
|
||||||
*
|
*
|
||||||
* // Retrieve a zone
|
* // Retrieve a zone
|
||||||
* ZoneEntity zone = cfDnsClient.zoneGet("example.com");
|
* ZoneEntity zone = cfDnsClient.zoneGet("example.com");
|
||||||
* System.out.println("Zone ID: " + zone.getId());
|
* System.out.println("Zone ID: " + zone.getId());
|
||||||
*
|
*
|
||||||
* // Retrieve records of a subdomain
|
* // Retrieve records of a subdomain
|
||||||
* List<RecordEntity> records = cfDnsClient.recordList(zone, "sld");
|
* List<RecordEntity> records = cfDnsClient.recordListBySubdomain(zone, "www");
|
||||||
* records.forEach(record ->
|
* records.forEach(record ->
|
||||||
* System.out.println("Record Type: " + record.getType() + ", Value: " + record.getContent())
|
* System.out.println("Record Type: " + record.getType() + ", Value: " + record.getContent())
|
||||||
* );
|
* );
|
||||||
*
|
*
|
||||||
* // Create a record for the subdomain "api"
|
* // Create a record for the subdomain "api"
|
||||||
* RecordEntity created = cfDnsClient.recordCreateSld(zone, "api", 60, RecordType.A, "192.168.1.10");
|
* RecordEntity created = cfDnsClient.recordCreateSubdomain(zone, "api", 60, RecordType.A, "192.168.1.10");
|
||||||
* System.out.println("Created Record ID: " + created.getId());
|
* System.out.println("Created Record ID: " + created.getId());
|
||||||
|
* }
|
||||||
* </code></pre>
|
* </code></pre>
|
||||||
*
|
*
|
||||||
* <p>Example with email/key authentication (legacy):
|
* <p>Example with email/key authentication (legacy):
|
||||||
@@ -77,10 +85,27 @@ import org.jetbrains.annotations.Nullable;
|
|||||||
@Slf4j
|
@Slf4j
|
||||||
public class CfDnsClient extends CfBasicHttpClient {
|
public class CfDnsClient extends CfBasicHttpClient {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Page size used when fetching all zones. Cloudflare allows max. 50 zones per page.
|
||||||
|
*/
|
||||||
|
static final int ZONES_PER_PAGE = 50;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Page size used when fetching all DNS records.
|
||||||
|
*/
|
||||||
|
static final int RECORDS_PER_PAGE = 1000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Conventional name for the zone apex (the zone name itself).
|
||||||
|
*/
|
||||||
|
public static final String APEX = "@";
|
||||||
|
|
||||||
private final ResponseValidator responseValidator;
|
private final ResponseValidator responseValidator;
|
||||||
|
|
||||||
private final boolean emptyResultThrowsException;
|
private final boolean emptyResultThrowsException;
|
||||||
|
|
||||||
|
private final int recordsPerPage;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new instance of {@code CfDnsClient}.
|
* Constructs a new instance of {@code CfDnsClient}.
|
||||||
*
|
*
|
||||||
@@ -91,13 +116,26 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
* @param auth The authentication mechanism to use (ApiTokenAuth or EmailKeyAuth)
|
* @param auth The authentication mechanism to use (ApiTokenAuth or EmailKeyAuth)
|
||||||
*/
|
*/
|
||||||
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth) {
|
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth) {
|
||||||
|
this(emptyResultThrowsException, baseUrl, auth, RECORDS_PER_PAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs a new instance of {@code CfDnsClient} with a custom page size for fetching all DNS
|
||||||
|
* records. Intended for tests, which need to fetch multiple pages with only a few records.
|
||||||
|
*/
|
||||||
|
CfDnsClient(boolean emptyResultThrowsException, String baseUrl, CfDnsClientBuilder.CfAuth auth,
|
||||||
|
int recordsPerPage) {
|
||||||
super(baseUrl, auth);
|
super(baseUrl, auth);
|
||||||
this.responseValidator = new ResponseValidator(emptyResultThrowsException);
|
this.responseValidator = new ResponseValidator(emptyResultThrowsException);
|
||||||
this.emptyResultThrowsException = emptyResultThrowsException;
|
this.emptyResultThrowsException = emptyResultThrowsException;
|
||||||
|
this.recordsPerPage = recordsPerPage;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String buildFqdn(ZoneEntity zone, String sld) {
|
private static String buildFqdn(ZoneEntity zone, String subdomain) {
|
||||||
return sld + "." + zone.getName();
|
if (APEX.equals(subdomain)) {
|
||||||
|
return zone.getName();
|
||||||
|
}
|
||||||
|
return subdomain + "." + zone.getName();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -129,25 +167,30 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
*
|
*
|
||||||
* @param zoneName the name of the DNS zone (e.g., "example.com")
|
* @param zoneName the name of the DNS zone (e.g., "example.com")
|
||||||
* @return a ZoneOperations instance for chaining operations
|
* @return a ZoneOperations instance for chaining operations
|
||||||
* @throws CloudflareApiException if the zone cannot be found or accessed
|
* @throws CloudflareNotFoundException if the zone doesn't exist
|
||||||
|
* @throws CloudflareApiException if the zone cannot be accessed
|
||||||
*/
|
*/
|
||||||
public ZoneOperations zone(String zoneName) throws CloudflareApiException {
|
public ZoneOperations zone(String zoneName) throws CloudflareApiException {
|
||||||
ZoneEntity zoneEntity = zoneGet(zoneName);
|
ZoneEntity zoneEntity = zoneGet(zoneName);
|
||||||
|
if (zoneEntity == null) {
|
||||||
|
throw new CloudflareNotFoundException("Zone not found: " + zoneName);
|
||||||
|
}
|
||||||
return new ZoneOperationsImpl(this, zoneEntity);
|
return new ZoneOperationsImpl(this, zoneEntity);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a list of all zones from the Cloudflare API.
|
* Retrieves a list of all zones from the Cloudflare API. If there are more zones than fit on one
|
||||||
|
* page, all pages are fetched.
|
||||||
*
|
*
|
||||||
* @return A list of ZoneEntity objects representing the zones retrieved from the Cloudflare API.
|
* @return A list of ZoneEntity objects representing the zones retrieved from the Cloudflare API.
|
||||||
* @throws CloudflareApiException If an error occurs during the API request or response handling.
|
* @throws CloudflareApiException If an error occurs during the API request or response handling.
|
||||||
*/
|
*/
|
||||||
public List<ZoneEntity> zoneList() throws CloudflareApiException {
|
public List<ZoneEntity> zoneList() throws CloudflareApiException {
|
||||||
return zoneList(PagingRequest.defaultPaging());
|
return getAllPages(CfRequest.ZONE_LIST.buildPath(), ZoneMultipleResponse.class, ZONES_PER_PAGE);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a list of all DNS zones using the provided paging request parameters.
|
* Retrieves a single page of DNS zones using the provided paging request parameters.
|
||||||
*
|
*
|
||||||
* @param pagingRequest the pagination request object containing parameters for paging and
|
* @param pagingRequest the pagination request object containing parameters for paging and
|
||||||
* filtering zone data
|
* filtering zone data
|
||||||
@@ -166,124 +209,145 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
* Retrieves detailed information about a specific zone by its name.
|
* Retrieves detailed information about a specific zone by its name.
|
||||||
*
|
*
|
||||||
* @param name The name of the zone to retrieve information for.
|
* @param name The name of the zone to retrieve information for.
|
||||||
* @return A {@link ZoneEntity} object that contains details of the specified zone.
|
* @return A {@link ZoneEntity} object that contains details of the specified zone, or
|
||||||
* @throws CloudflareApiException If an error occurs while making the API request or processing
|
* {@code null} if the zone doesn't exist and 'emptyResultThrowsException' is disabled.
|
||||||
* the response.
|
* @throws CloudflareNotFoundException If the zone doesn't exist and 'emptyResultThrowsException'
|
||||||
|
* is enabled.
|
||||||
|
* @throws CloudflareApiException If an error occurs while making the API request or
|
||||||
|
* processing the response.
|
||||||
*/
|
*/
|
||||||
|
@Nullable
|
||||||
public ZoneEntity zoneGet(String name) throws CloudflareApiException {
|
public ZoneEntity zoneGet(String name) throws CloudflareApiException {
|
||||||
String endpoint = CfRequest.ZONE_INFO.buildPath(name);
|
String endpoint = CfRequest.ZONE_INFO.buildPath(name);
|
||||||
ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class);
|
ZoneMultipleResponse response = getRequest(endpoint, ZoneMultipleResponse.class);
|
||||||
checkResponse(response, true);
|
checkResponse(response, true);
|
||||||
return response.getResult().get(0);
|
List<ZoneEntity> zones = response.getResult();
|
||||||
|
return (zones == null || zones.isEmpty()) ? null : zones.get(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a list of DNS records for a specified zone, with optional paging support.
|
* Retrieves all DNS records for a specified zone. If there are more records than fit on one
|
||||||
|
* page, all pages are fetched.
|
||||||
*
|
*
|
||||||
* @param zone The zone entity containing information about the target zone.
|
* @param zone The zone entity containing information about the target zone.
|
||||||
* @return A list of RecordEntity objects representing the DNS records of the specified zone.
|
* @return A list of RecordEntity objects representing the DNS records of the specified zone.
|
||||||
* @throws CloudflareApiException If an error occurs during the API request or response processing.
|
* @throws CloudflareApiException If an error occurs during the API request or response processing.
|
||||||
*/
|
*/
|
||||||
public List<RecordEntity> recordList(ZoneEntity zone) throws CloudflareApiException {
|
public List<RecordEntity> recordList(ZoneEntity zone) throws CloudflareApiException {
|
||||||
return recordList(zone, (PagingRequest) null);
|
return recordList(zone, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a list of DNS records for a specified zone, with optional paging support.
|
* Retrieves DNS records for a specified zone, with optional paging support.
|
||||||
*
|
*
|
||||||
* @param zone The zone entity containing information about the target zone.
|
* @param zone The zone entity containing information about the target zone.
|
||||||
* @param pagingRequest The paging request containing parameters such as page size and number.
|
* @param pagingRequest The paging request containing parameters such as page size and number.
|
||||||
|
* If {@code null}, all pages are fetched.
|
||||||
* @return A list of RecordEntity objects representing the DNS records of the specified zone.
|
* @return A list of RecordEntity objects representing the DNS records of the specified zone.
|
||||||
* @throws CloudflareApiException If an error occurs during the API request or response processing.
|
* @throws CloudflareApiException If an error occurs during the API request or response processing.
|
||||||
*/
|
*/
|
||||||
public List<RecordEntity> recordList(ZoneEntity zone, @Nullable PagingRequest pagingRequest) throws CloudflareApiException {
|
public List<RecordEntity> recordList(ZoneEntity zone, @Nullable PagingRequest pagingRequest)
|
||||||
PagingRequest pr = pagingRequest == null ? PagingRequest.defaultPaging() : pagingRequest;
|
throws CloudflareApiException {
|
||||||
String endpoint = pr.addQueryString(CfRequest.RECORD_LIST.buildPath(zone.getId()));
|
String path = CfRequest.RECORD_LIST.buildPath(zone.getId());
|
||||||
RecordMultipleResponse resp = getRequest(endpoint, RecordMultipleResponse.class);
|
if (pagingRequest == null) {
|
||||||
|
return filterAndSetZoneRecords(zone, null,
|
||||||
|
getAllPages(path, RecordMultipleResponse.class, recordsPerPage));
|
||||||
|
}
|
||||||
|
RecordMultipleResponse resp = getRequest(pagingRequest.addQueryString(path), RecordMultipleResponse.class);
|
||||||
checkResponse(resp);
|
checkResponse(resp);
|
||||||
return resp.getResult();
|
return filterAndSetZoneRecords(zone, null, resp.getResult());
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves DNS records for the specified second-level domain (SLD) within a zone.
|
* Retrieves DNS records for the specified subdomain within a zone.
|
||||||
*
|
* Optionally, filters by one or more DNS record types.
|
||||||
* @param zone the zone entity representing the DNS zone to query
|
|
||||||
* @param sld the second-level domain (SLD) to filter the records
|
|
||||||
* @return a list of RecordEntity objects that match the specified SLD within the zone
|
|
||||||
* @throws CloudflareNotFoundException if the specified SLD is not found in the zone
|
|
||||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
|
||||||
*/
|
|
||||||
public List<RecordEntity> recordList(ZoneEntity zone, String sld) throws CloudflareApiException {
|
|
||||||
return recordList(zone, sld, (RecordType[]) null);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieves DNS records for the specified second-level domain (SLD) within a zone.
|
|
||||||
* Optionally, filters by one or more DNS getRecord types.
|
|
||||||
*
|
*
|
||||||
* @param zone The zone entity containing information about the domain zone.
|
* @param zone The zone entity containing information about the domain zone.
|
||||||
* @param sld The second-level domain (SLD) for which to retrieve DNS records.
|
* @param subdomain The subdomain relative to the zone (e.g. "www" for "www.example.com"),
|
||||||
* @param types Optional parameter specifying one or more DNS getRecord types to filter the results.
|
* or {@link #APEX} for the zone apex.
|
||||||
|
* @param types Optional DNS record types to filter the results. If none are given, records of
|
||||||
|
* all types are returned.
|
||||||
* @return A list of {@code RecordEntity} objects representing the DNS records for the specified domain.
|
* @return A list of {@code RecordEntity} objects representing the DNS records for the specified domain.
|
||||||
* @throws CloudflareNotFoundException if the specified SLD is not found in the zone
|
* @throws CloudflareNotFoundException if no records were found and 'emptyResultThrowsException'
|
||||||
|
* is enabled
|
||||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
||||||
*/
|
*/
|
||||||
public List<RecordEntity> recordList(ZoneEntity zone, String sld, @Nullable RecordType... types)
|
public List<RecordEntity> recordListBySubdomain(ZoneEntity zone, String subdomain,
|
||||||
|
@Nullable RecordType... types)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
String fqdn = buildFqdn(zone, sld);
|
String fqdn = buildFqdn(zone, subdomain);
|
||||||
String endpoint = CfRequest.RECORD_LIST_NAME.buildPath(zone.getId(), fqdn);
|
String endpoint = addTypeFilter(CfRequest.RECORD_LIST_NAME.buildPath(zone.getId(), fqdn), types);
|
||||||
RecordMultipleResponse resp = getRequest(endpoint, RecordMultipleResponse.class);
|
List<RecordEntity> recs = getAllPages(endpoint, RecordMultipleResponse.class, recordsPerPage);
|
||||||
checkResponse(resp, false);
|
|
||||||
List<RecordEntity> recs = resp.getResult();
|
|
||||||
return filterAndSetZoneRecords(zone, types, recs);
|
return filterAndSetZoneRecords(zone, types, recs);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a list of all DNS records for a given zone.
|
* Retrieves all DNS records of the given types for a zone.
|
||||||
* Optionally, filters by one or more DNS getRecord types.
|
|
||||||
*
|
*
|
||||||
* @param zone The zone entity containing information about the domain zone.
|
* @param zone The zone entity containing information about the domain zone.
|
||||||
* @param types Optional parameter specifying one or more DNS getRecord types to filter the results.
|
* @param types Optional DNS record types to filter the results. If none are given, records of all
|
||||||
|
* types are returned.
|
||||||
* @return A list of {@code RecordEntity} objects representing the DNS records for the specified zone.
|
* @return A list of {@code RecordEntity} objects representing the DNS records for the specified zone.
|
||||||
|
* @throws CloudflareNotFoundException if no records were found and 'emptyResultThrowsException'
|
||||||
|
* is enabled
|
||||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
||||||
*/
|
*/
|
||||||
public List<RecordEntity> recordList(ZoneEntity zone, RecordType... types)
|
public List<RecordEntity> recordListByType(ZoneEntity zone, @Nullable RecordType... types)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
String endpoint = CfRequest.RECORD_LIST.buildPath(zone.getId());
|
String endpoint = addTypeFilter(CfRequest.RECORD_LIST.buildPath(zone.getId()), types);
|
||||||
RecordMultipleResponse resp = getRequest(endpoint, RecordMultipleResponse.class);
|
List<RecordEntity> recs = getAllPages(endpoint, RecordMultipleResponse.class, recordsPerPage);
|
||||||
checkResponse(resp, false);
|
|
||||||
List<RecordEntity> recs = resp.getResult();
|
|
||||||
return filterAndSetZoneRecords(zone, types, recs);
|
return filterAndSetZoneRecords(zone, types, recs);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new DNS getRecord for a given second-level domain (SLD) within the specified zone.
|
* Creates a new DNS record for a given subdomain within the specified zone.
|
||||||
*
|
*
|
||||||
* @param zone The ZoneEntity representing the DNS zone where the getRecord is to be created.
|
* @param zone The ZoneEntity representing the DNS zone where the record is to be created.
|
||||||
* @param sld The second-level domain (SLD) for which the DNS getRecord is being created.
|
* @param subdomain The subdomain relative to the zone (e.g. "api" for "api.example.com"),
|
||||||
* @param ttl The time-to-live (TTL) value for the DNS getRecord in seconds.
|
* or {@link #APEX} for the zone apex.
|
||||||
* @param type The RecordType specifying the type of the DNS getRecord (e.g., A, AAAA, CNAME).
|
* @param ttl The time-to-live (TTL) value for the DNS record in seconds.
|
||||||
* @param content The content of the DNS getRecord (e.g., IP address for A/AAAA records, target
|
* @param type The RecordType specifying the type of the DNS record (e.g., A, AAAA, CNAME).
|
||||||
|
* @param content The content of the DNS record (e.g., IP address for A/AAAA records, target
|
||||||
* domain for CNAME).
|
* domain for CNAME).
|
||||||
* @return The created RecordEntity object containing details of the newly created DNS getRecord.
|
* @return The created RecordEntity object containing details of the newly created DNS record.
|
||||||
* @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API
|
* @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API
|
||||||
* or creating the getRecord.
|
* or creating the record.
|
||||||
*/
|
*/
|
||||||
public RecordEntity recordCreateSld(ZoneEntity zone, String sld, int ttl, RecordType type,
|
public RecordEntity recordCreateSubdomain(ZoneEntity zone, String subdomain, int ttl, RecordType type,
|
||||||
String content) throws CloudflareApiException {
|
String content) throws CloudflareApiException {
|
||||||
String fqdn = buildFqdn(zone, sld);
|
String fqdn = buildFqdn(zone, subdomain);
|
||||||
return recordCreate(zone, fqdn, ttl, type, content);
|
return recordCreate(zone, fqdn, ttl, type, content);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a DNS getRecord in the specified DNS zone with the provided details.
|
* Creates a new DNS record for a given subdomain within the specified zone.
|
||||||
*
|
*
|
||||||
* @param zone the DNS zone in which the getRecord will be created
|
* @param zone The ZoneEntity representing the DNS zone where the record is to be created.
|
||||||
* @param name the name of the DNS getRecord (e.g., www.example.com)
|
* @param subdomain The subdomain relative to the zone.
|
||||||
* @param ttl the time-to-live (TTL) value for the DNS getRecord
|
* @param ttl The time-to-live (TTL) value for the DNS record in seconds.
|
||||||
* @param type the type of the DNS getRecord (e.g., A, AAAA, CNAME)
|
* @param type The RecordType specifying the type of the DNS record.
|
||||||
* @param content the content or value of the DNS getRecord
|
* @param content The content of the DNS record.
|
||||||
* @return the created DNS getRecord as a {@link RecordEntity} object
|
* @return The created RecordEntity object containing details of the newly created DNS record.
|
||||||
|
* @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API
|
||||||
|
* or creating the record.
|
||||||
|
* @deprecated The name was misleading, use
|
||||||
|
* {@link #recordCreateSubdomain(ZoneEntity, String, int, RecordType, String)} instead.
|
||||||
|
*/
|
||||||
|
@Deprecated(since = "0.6.0", forRemoval = true)
|
||||||
|
public RecordEntity recordCreateSld(ZoneEntity zone, String subdomain, int ttl, RecordType type,
|
||||||
|
String content) throws CloudflareApiException {
|
||||||
|
return recordCreateSubdomain(zone, subdomain, ttl, type, content);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a DNS record in the specified DNS zone with the provided details.
|
||||||
|
*
|
||||||
|
* @param zone the DNS zone in which the record will be created
|
||||||
|
* @param name the name of the DNS record (e.g., www.example.com)
|
||||||
|
* @param ttl the time-to-live (TTL) value for the DNS record
|
||||||
|
* @param type the type of the DNS record (e.g., A, AAAA, CNAME)
|
||||||
|
* @param content the content or value of the DNS record
|
||||||
|
* @return the created DNS record as a {@link RecordEntity} object
|
||||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
||||||
*/
|
*/
|
||||||
public RecordEntity recordCreate(ZoneEntity zone, String name, int ttl, RecordType type,
|
public RecordEntity recordCreate(ZoneEntity zone, String name, int ttl, RecordType type,
|
||||||
@@ -293,51 +357,54 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new DNS getRecord in the specified zone using the Cloudflare API.
|
* Creates a new DNS record in the specified zone using the Cloudflare API.
|
||||||
*
|
*
|
||||||
* @param zone The zone entity where the getRecord will be created. Contains details such as zone
|
* @param zone The zone entity where the record will be created. Contains details such as zone
|
||||||
* ID.
|
* ID.
|
||||||
* @param rec The getRecord entity representing the DNS getRecord to be created, including its
|
* @param rec The record entity representing the DNS record to be created, including its
|
||||||
* attributes.
|
* attributes. Read-only attributes (e.g. ID, timestamps) are ignored, the given
|
||||||
* @return The created getRecord entity as returned by the Cloudflare API.
|
* object isn't modified.
|
||||||
|
* @return The created record entity as returned by the Cloudflare API.
|
||||||
* @throws CloudflareApiException If an error occurs while interacting with the Cloudflare API.
|
* @throws CloudflareApiException If an error occurs while interacting with the Cloudflare API.
|
||||||
*/
|
*/
|
||||||
public RecordEntity recordCreate(ZoneEntity zone, RecordEntity rec)
|
public RecordEntity recordCreate(ZoneEntity zone, RecordEntity rec)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
String endpoint = CfRequest.RECORD_CREATE.buildPath(zone.getId());
|
String endpoint = CfRequest.RECORD_CREATE.buildPath(zone.getId());
|
||||||
RecordSingleResponse resp = postRequest(endpoint, rec, RecordSingleResponse.class);
|
RecordEntity payload = writableCopy(rec, false);
|
||||||
|
RecordSingleResponse resp = postRequest(endpoint, payload, RecordSingleResponse.class);
|
||||||
checkResponse(resp);
|
checkResponse(resp);
|
||||||
log.info("Record {} of type {} successful created.", rec.getSld(), rec.getType());
|
log.info("Record {} of type {} successful created.", rec.getSubdomain(), rec.getType());
|
||||||
RecordEntity retRec = resp.getResult();
|
RecordEntity retRec = resp.getResult();
|
||||||
retRec.setZoneId(zone.getId());
|
assignZone(retRec, zone);
|
||||||
return retRec;
|
return retRec;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes a DNS getRecord of the specified type within a given zone on the Cloudflare API.
|
* Deletes a DNS record of the specified type within a given zone on the Cloudflare API.
|
||||||
*
|
*
|
||||||
* @param zone The zone entity that specifies the zone in which the getRecord exists.
|
* @param zone The zone entity that specifies the zone in which the record exists.
|
||||||
* @param rec The getRecord entity that represents the DNS getRecord to be deleted.
|
* @param rec The record entity that represents the DNS record to be deleted.
|
||||||
* @return {@code true} if the DNS getRecord was successfully deleted; {@code false} otherwise.
|
* @return {@code true} if the DNS record was successfully deleted; {@code false} otherwise.
|
||||||
* @throws CloudflareApiException if there is an issue during the API communication, or the
|
* @throws CloudflareApiException if there is an issue during the API communication, or the
|
||||||
* request fails for any reason.
|
* request fails for any reason.
|
||||||
*/
|
*/
|
||||||
public boolean recordDelete(ZoneEntity zone, RecordEntity rec) throws CloudflareApiException {
|
public boolean recordDelete(ZoneEntity zone, RecordEntity rec) throws CloudflareApiException {
|
||||||
boolean changed = recordDelete(zone, rec.getId());
|
boolean changed = recordDelete(zone, rec.getId());
|
||||||
if (changed) {
|
if (changed) {
|
||||||
log.debug("Record {} of the type [{}] successful deleted.", rec.getSld(), rec.getType());
|
log.debug("Record {} of the type [{}] successful deleted.", rec.getSubdomain(), rec.getType());
|
||||||
} else {
|
} else {
|
||||||
log.warn("Record {} of the type [{}] was not deleted.", rec.getSld(), rec.getType());
|
log.warn("Record {} of the type [{}] was not deleted.", rec.getSubdomain(), rec.getType());
|
||||||
}
|
}
|
||||||
return changed;
|
return changed;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes a DNS getRecord of the specified type within a given zone on the Cloudflare API.
|
* Deletes a DNS record of the specified type within a given zone on the Cloudflare API.
|
||||||
*
|
*
|
||||||
* @param zone The zone entity that specifies the zone in which the getRecord exists.
|
* @param zone The zone entity that specifies the zone in which the record exists.
|
||||||
* @param id The getRecord entity that represents the DNS getRecord to be deleted.
|
* @param id The ID of the DNS record to be deleted.
|
||||||
* @return {@code true} if the DNS getRecord was successfully deleted; {@code false} otherwise.
|
* @return {@code true} if the API confirms the deletion of the record with the given ID;
|
||||||
|
* {@code false} otherwise.
|
||||||
* @throws CloudflareApiException if there is an issue during the API communication or the request
|
* @throws CloudflareApiException if there is an issue during the API communication or the request
|
||||||
* fails for any reason.
|
* fails for any reason.
|
||||||
*/
|
*/
|
||||||
@@ -345,48 +412,54 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
String endpoint = CfRequest.RECORD_DELETE.buildPath(zone.getId(), id);
|
String endpoint = CfRequest.RECORD_DELETE.buildPath(zone.getId(), id);
|
||||||
RecordSingleResponse resp = deleteRequest(endpoint, RecordSingleResponse.class);
|
RecordSingleResponse resp = deleteRequest(endpoint, RecordSingleResponse.class);
|
||||||
checkResponse(resp);
|
checkResponse(resp);
|
||||||
log.debug("Record id#{} successful deleted.", id);
|
RecordEntity deleted = resp.getResult();
|
||||||
return resp.getResult().getId().equals(id);
|
boolean confirmed = deleted != null && id.equals(deleted.getId());
|
||||||
|
if (confirmed) {
|
||||||
|
log.debug("Record id#{} successfully deleted.", id);
|
||||||
|
}
|
||||||
|
return confirmed;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates an existing DNS getRecord in a specified Cloudflare zone.
|
* Updates an existing DNS record in a specified Cloudflare zone (partial update, attributes
|
||||||
|
* which are {@code null} remain unchanged).
|
||||||
*
|
*
|
||||||
* @param zone the zone entity containing the ID of the target zone
|
* @param zone the zone entity containing the ID of the target zone
|
||||||
* @param rec the getRecord entity containing the ID of the DNS getRecord to be updated and its updated
|
* @param rec the record entity containing the ID of the DNS record to be updated and its updated
|
||||||
* data
|
* data. Read-only attributes (e.g. timestamps) are ignored, the given object isn't
|
||||||
* @return the updated getRecord entity as returned by the Cloudflare API
|
* modified.
|
||||||
|
* @return the updated record entity as returned by the Cloudflare API
|
||||||
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
* @throws CloudflareApiException if an error occurs while interacting with the Cloudflare API
|
||||||
*/
|
*/
|
||||||
public RecordEntity recordUpdate(ZoneEntity zone, RecordEntity rec)
|
public RecordEntity recordUpdate(ZoneEntity zone, RecordEntity rec)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
// reset all dates, it causes an API issue
|
|
||||||
rec.setModifiedOn(null);
|
|
||||||
rec.setCreatedOn(null);
|
|
||||||
String endpoint = CfRequest.RECORD_UPDATE.buildPath(zone.getId(), rec.getId());
|
String endpoint = CfRequest.RECORD_UPDATE.buildPath(zone.getId(), rec.getId());
|
||||||
RecordSingleResponse resp = patchRequest(endpoint, rec, RecordSingleResponse.class);
|
RecordEntity payload = writableCopy(rec, false);
|
||||||
|
RecordSingleResponse resp = patchRequest(endpoint, payload, RecordSingleResponse.class);
|
||||||
checkResponse(resp);
|
checkResponse(resp);
|
||||||
log.info("Record {} of type {} successful updated.", rec.getSld(), rec.getType());
|
log.info("Record {} of type {} successful updated.", rec.getSubdomain(), rec.getType());
|
||||||
return resp.getResult();
|
RecordEntity retRec = resp.getResult();
|
||||||
|
assignZone(retRec, zone);
|
||||||
|
return retRec;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes DNS records of a specific type within a given zone if they exist. If no getRecord of the
|
* Deletes DNS records of a specific type within a given zone if they exist. If no record of the
|
||||||
* specified type exists, it logs this occurrence without throwing an exception.
|
* specified type exists, it logs this occurrence without throwing an exception.
|
||||||
*
|
*
|
||||||
* @param zone The DNS zone entity in which the getRecord exists.
|
* @param zone The DNS zone entity in which the record exists.
|
||||||
* @param sld The second-level domain for which the getRecord is being checked.
|
* @param subdomain The subdomain relative to the zone for which the records are being checked.
|
||||||
* @param recordTypes The types of DNS records that should be deleted if they exist.
|
* @param recordTypes The types of DNS records that should be deleted if they exist.
|
||||||
* @throws CloudflareApiException If an error occurs during API communication.
|
* @throws CloudflareApiException If an error occurs during API communication.
|
||||||
*/
|
*/
|
||||||
public void recordDeleteTypeIfExists(ZoneEntity zone, String sld, RecordType... recordTypes)
|
public void recordDeleteTypeIfExists(ZoneEntity zone, String subdomain, RecordType... recordTypes)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
String fqdn = buildFqdn(zone, sld);
|
String fqdn = buildFqdn(zone, subdomain);
|
||||||
List<RecordEntity> recs;
|
List<RecordEntity> recs;
|
||||||
try {
|
try {
|
||||||
recs = recordList(zone, sld, recordTypes);
|
recs = recordListBySubdomain(zone, subdomain, recordTypes);
|
||||||
} catch (CloudflareNotFoundException e) {
|
} catch (CloudflareNotFoundException e) {
|
||||||
log.trace("No getRecord of type {} found for domain {}.", recordTypes, fqdn);
|
log.trace("No record of type {} found for domain {}.", recordTypes, fqdn);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
for (RecordEntity rec : recs) {
|
for (RecordEntity rec : recs) {
|
||||||
@@ -394,13 +467,13 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
recordDelete(zone, rec);
|
recordDelete(zone, rec);
|
||||||
log.info("Record {} of type {} successful deleted.", fqdn, recordTypes);
|
log.info("Record {} of type {} successful deleted.", fqdn, recordTypes);
|
||||||
} catch (CloudflareApiException e) {
|
} catch (CloudflareApiException e) {
|
||||||
log.error("Failed to delete getRecord {} of type {} for zone {}: {}", fqdn, recordTypes, zone.getName(), e.getMessage());
|
log.error("Failed to delete record {} of type {} for zone {}: {}", fqdn, recordTypes, zone.getName(), e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Processes a batch of DNS getRecord operations (POST, PUT, PATCH, DELETE) for a specified zone.
|
* Processes a batch of DNS record operations (POST, PUT, PATCH, DELETE) for a specified zone.
|
||||||
* This method builds and cleans the input records, sends the batch request to the Cloudflare API,
|
* This method builds and cleans the input records, sends the batch request to the Cloudflare API,
|
||||||
* and returns a result containing processed batch entries.
|
* and returns a result containing processed batch entries.
|
||||||
*
|
*
|
||||||
@@ -408,7 +481,8 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
* @param postRecords A list of DNS records to be created (POST). This parameter is nullable.
|
* @param postRecords A list of DNS records to be created (POST). This parameter is nullable.
|
||||||
* @param putRecords A list of DNS records to be fully replaced (PUT). This parameter is nullable.
|
* @param putRecords A list of DNS records to be fully replaced (PUT). This parameter is nullable.
|
||||||
* @param patchRecords A list of DNS records to be partially updated (PATCH). This parameter is nullable.
|
* @param patchRecords A list of DNS records to be partially updated (PATCH). This parameter is nullable.
|
||||||
* @param deleteRecords A list of DNS records to be deleted (DELETE). This parameter is nullable.
|
* @param deleteRecords A list of DNS records to be deleted (DELETE), only the IDs are used. This
|
||||||
|
* parameter is nullable.
|
||||||
* @return The resulting {@link BatchEntry} containing the processed records after the batch operation.
|
* @return The resulting {@link BatchEntry} containing the processed records after the batch operation.
|
||||||
* @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API.
|
* @throws CloudflareApiException If an error occurs while communicating with the Cloudflare API.
|
||||||
*/
|
*/
|
||||||
@@ -416,18 +490,18 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
@Nullable List<RecordEntity> patchRecords, @Nullable List<RecordEntity> deleteRecords)
|
@Nullable List<RecordEntity> patchRecords, @Nullable List<RecordEntity> deleteRecords)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
BatchEntry batchEntry = new BatchEntry();
|
BatchEntry batchEntry = new BatchEntry();
|
||||||
// build 'clean' getRecord entries
|
// build 'clean' record entries, the given records aren't modified
|
||||||
if (postRecords != null) {
|
if (postRecords != null) {
|
||||||
batchEntry.setPosts(cleanRecordsForPostOrPut(postRecords));
|
batchEntry.setPosts(postRecords.stream().map(rec -> writableCopy(rec, false)).toList());
|
||||||
}
|
}
|
||||||
if (putRecords != null) {
|
if (putRecords != null) {
|
||||||
batchEntry.setPuts(cleanRecordsForPostOrPut(putRecords));
|
batchEntry.setPuts(putRecords.stream().map(rec -> writableCopy(rec, true)).toList());
|
||||||
}
|
}
|
||||||
if (patchRecords != null) {
|
if (patchRecords != null) {
|
||||||
batchEntry.setPatches(cleanRecordsForPatch(patchRecords));
|
batchEntry.setPatches(patchRecords.stream().map(rec -> writableCopy(rec, true)).toList());
|
||||||
}
|
}
|
||||||
if (deleteRecords != null) {
|
if (deleteRecords != null) {
|
||||||
batchEntry.setDeletes(cleanRecordsForDelete(deleteRecords));
|
batchEntry.setDeletes(deleteRecords.stream().map(CfDnsClient::idOnly).toList());
|
||||||
}
|
}
|
||||||
|
|
||||||
String endpoint = CfRequest.RECORD_BATCH.buildPath(zone.getId());
|
String endpoint = CfRequest.RECORD_BATCH.buildPath(zone.getId());
|
||||||
@@ -436,21 +510,27 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
|
|
||||||
// set zone id
|
// set zone id
|
||||||
BatchEntry result = resp.getResult();
|
BatchEntry result = resp.getResult();
|
||||||
setZoneIdForBatchResults(result, zone.getId());
|
setZoneForBatchResults(result, zone);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<RecordEntity> filterAndSetZoneRecords(ZoneEntity zone, @Nullable RecordType[] types, List<RecordEntity> recs)
|
private List<RecordEntity> filterAndSetZoneRecords(ZoneEntity zone, @Nullable RecordType[] types,
|
||||||
|
@Nullable List<RecordEntity> recs)
|
||||||
throws CloudflareNotFoundException {
|
throws CloudflareNotFoundException {
|
||||||
|
if (recs == null) {
|
||||||
|
recs = List.of();
|
||||||
|
}
|
||||||
List<RecordEntity> filtered;
|
List<RecordEntity> filtered;
|
||||||
if (types != null && types.length > 0) {
|
if (types != null && types.length > 0) {
|
||||||
Set<RecordType> allowedTypes = new HashSet<>(Arrays.asList(types));
|
Set<String> allowedTypes = Arrays.stream(types).filter(Objects::nonNull)
|
||||||
|
.map(RecordType::getType).collect(Collectors.toSet());
|
||||||
filtered = recs.stream()
|
filtered = recs.stream()
|
||||||
.filter(rec -> allowedTypes.contains(RecordType.valueOf(rec.getType()))).toList();
|
.filter(rec -> allowedTypes.contains(rec.getType()))
|
||||||
|
.collect(Collectors.toCollection(ArrayList::new));
|
||||||
} else {
|
} else {
|
||||||
filtered = new ArrayList<>(recs);
|
filtered = new ArrayList<>(recs);
|
||||||
}
|
}
|
||||||
filtered.forEach(rec -> rec.setZoneId(zone.getId()));
|
filtered.forEach(rec -> assignZone(rec, zone));
|
||||||
|
|
||||||
// special exception for an empty result, normally it's done in the RecordValidator
|
// special exception for an empty result, normally it's done in the RecordValidator
|
||||||
if (filtered.isEmpty() && emptyResultThrowsException) {
|
if (filtered.isEmpty() && emptyResultThrowsException) {
|
||||||
@@ -460,35 +540,87 @@ public class CfDnsClient extends CfBasicHttpClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private List<RecordEntity> cleanRecordsForPostOrPut(List<RecordEntity> records) {
|
/**
|
||||||
List<RecordEntity> cleaned = new ArrayList<>();
|
* Creates a copy of the record containing only the attributes which can be written to the API.
|
||||||
records.forEach(
|
* Read-only attributes like timestamps, zone info, 'proxiable' or 'locked' are omitted.
|
||||||
rec -> cleaned.add(RecordEntity.build(rec.getId(), rec.getSld(), rec.getType(), rec.getTtl(), rec.getContent())));
|
*/
|
||||||
return cleaned;
|
private static RecordEntity writableCopy(RecordEntity rec, boolean withId) {
|
||||||
|
RecordEntity copy = new RecordEntity();
|
||||||
|
if (withId) {
|
||||||
|
copy.setId(rec.getId());
|
||||||
|
}
|
||||||
|
copy.setName(rec.getName());
|
||||||
|
copy.setType(rec.getType());
|
||||||
|
copy.setContent(rec.getContent());
|
||||||
|
copy.setTtl(rec.getTtl());
|
||||||
|
copy.setProxied(rec.getProxied());
|
||||||
|
copy.setPriority(rec.getPriority());
|
||||||
|
copy.setComment(rec.getComment());
|
||||||
|
copy.setTags(rec.getTags() == null ? null : new ArrayList<>(rec.getTags()));
|
||||||
|
copy.setData(rec.getData() == null ? null : new LinkedHashMap<>(rec.getData()));
|
||||||
|
return copy;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<RecordEntity> cleanRecordsForPatch(List<RecordEntity> records) {
|
private static RecordEntity idOnly(RecordEntity rec) {
|
||||||
List<RecordEntity> cleaned = new ArrayList<>();
|
RecordEntity copy = new RecordEntity();
|
||||||
records.forEach(rec -> cleaned.add(RecordEntity.build(rec.getId(), rec.getContent())));
|
copy.setId(rec.getId());
|
||||||
return cleaned;
|
return copy;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<RecordEntity> cleanRecordsForDelete(List<RecordEntity> records) {
|
/**
|
||||||
List<RecordEntity> cleaned = new ArrayList<>();
|
* Adds the server-side type filter to the endpoint. The API supports only one type, so the
|
||||||
records.forEach(
|
* filter is only added if exactly one type is given. Multiple types are filtered client-side.
|
||||||
rec -> cleaned.add(RecordEntity.build(rec.getId(), rec.getSld(), rec.getType(), null, rec.getContent())));
|
*/
|
||||||
return cleaned;
|
private static String addTypeFilter(String endpoint, @Nullable RecordType[] types) {
|
||||||
|
if (types == null || types.length != 1 || types[0] == null) {
|
||||||
|
return endpoint;
|
||||||
|
}
|
||||||
|
return endpoint + (endpoint.contains("?") ? "&" : "?") + "type=" + types[0].getType();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setZoneIdForBatchResults(BatchEntry result, String zoneId) {
|
private void setZoneForBatchResults(@Nullable BatchEntry result, ZoneEntity zone) {
|
||||||
if (result.getPosts() != null) {
|
if (result == null) {
|
||||||
result.getPosts().forEach(rec -> rec.setZoneId(zoneId));
|
return;
|
||||||
}
|
}
|
||||||
if (result.getPuts() != null) {
|
for (List<RecordEntity> recs : Arrays.asList(result.getPosts(), result.getPuts(),
|
||||||
result.getPuts().forEach(rec -> rec.setZoneId(zoneId));
|
result.getPatches(), result.getDeletes())) {
|
||||||
|
if (recs != null) {
|
||||||
|
recs.forEach(rec -> assignZone(rec, zone));
|
||||||
}
|
}
|
||||||
if (result.getPatches() != null) {
|
}
|
||||||
result.getPatches().forEach(rec -> rec.setZoneId(zoneId));
|
}
|
||||||
|
|
||||||
|
private static void assignZone(@Nullable RecordEntity rec, ZoneEntity zone) {
|
||||||
|
if (rec != null) {
|
||||||
|
rec.setZoneId(zone.getId());
|
||||||
|
rec.setZoneName(zone.getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetches all pages of a paginated endpoint and returns the combined results.
|
||||||
|
*
|
||||||
|
* @param endpoint the endpoint path, may already contain a query string
|
||||||
|
* @param responseType the expected response type
|
||||||
|
* @param perPage the page size to request
|
||||||
|
*/
|
||||||
|
private <E extends ResponseEntity, R extends AbstractMultipleResponse<E>> List<E> getAllPages(
|
||||||
|
String endpoint, Class<R> responseType, int perPage) throws CloudflareApiException {
|
||||||
|
List<E> all = new ArrayList<>();
|
||||||
|
int page = 1;
|
||||||
|
while (true) {
|
||||||
|
String pagedEndpoint = PagingRequest.of(page, perPage).addQueryString(endpoint);
|
||||||
|
R resp = getRequest(pagedEndpoint, responseType);
|
||||||
|
checkResponse(resp);
|
||||||
|
List<E> result = resp.getResult();
|
||||||
|
if (result != null) {
|
||||||
|
all.addAll(result);
|
||||||
|
}
|
||||||
|
ResultInfo info = resp.getResultInfo();
|
||||||
|
if (info == null || result == null || result.isEmpty() || page >= info.totalPages()) {
|
||||||
|
return all;
|
||||||
|
}
|
||||||
|
page++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,20 +27,20 @@ public enum CfRequest {
|
|||||||
*/
|
*/
|
||||||
RECORD_LIST("/zones/%s/dns_records"),
|
RECORD_LIST("/zones/%s/dns_records"),
|
||||||
/**
|
/**
|
||||||
* Represents the API endpoint path for retrieving information about a DNS getRecord within a
|
* Represents the API endpoint path for retrieving information about a DNS record within a
|
||||||
* specific DNS zone by its name. The endpoint path includes placeholders for the zone identifier
|
* specific DNS zone by its name. The endpoint path includes placeholders for the zone identifier
|
||||||
* and the getRecord name, which need to be provided to construct the complete path.
|
* and the record name, which need to be provided to construct the complete path.
|
||||||
*/
|
*/
|
||||||
RECORD_LIST_NAME("/zones/%s/dns_records?name=%s"),
|
RECORD_LIST_NAME("/zones/%s/dns_records?name=%s"),
|
||||||
/**
|
/**
|
||||||
* Represents the API endpoint path for creating a new DNS getRecord within a specific DNS zone. The
|
* Represents the API endpoint path for creating a new DNS record within a specific DNS zone. The
|
||||||
* endpoint path includes a placeholder for the zone identifier, which needs to be provided to
|
* endpoint path includes a placeholder for the zone identifier, which needs to be provided to
|
||||||
* construct the complete path.
|
* construct the complete path.
|
||||||
*/
|
*/
|
||||||
RECORD_CREATE("/zones/%s/dns_records"),
|
RECORD_CREATE("/zones/%s/dns_records"),
|
||||||
/**
|
/**
|
||||||
* Represents the API endpoint path for updating an existing DNS getRecord within a specific DNS
|
* Represents the API endpoint path for updating an existing DNS record within a specific DNS
|
||||||
* zone. The endpoint path includes placeholders for the zone identifier and the getRecord
|
* zone. The endpoint path includes placeholders for the zone identifier and the record
|
||||||
* identifier, which need to be provided to construct the complete path.
|
* identifier, which need to be provided to construct the complete path.
|
||||||
*/
|
*/
|
||||||
RECORD_UPDATE("/zones/%s/dns_records/%s"),
|
RECORD_UPDATE("/zones/%s/dns_records/%s"),
|
||||||
@@ -51,8 +51,8 @@ public enum CfRequest {
|
|||||||
*/
|
*/
|
||||||
RECORD_BATCH("/zones/%s/dns_records/batch"),
|
RECORD_BATCH("/zones/%s/dns_records/batch"),
|
||||||
/**
|
/**
|
||||||
* Represents the API endpoint path for deleting an existing DNS getRecord within a specific DNS
|
* Represents the API endpoint path for deleting an existing DNS record within a specific DNS
|
||||||
* zone. The endpoint path includes placeholders for the zone identifier and the getRecord
|
* zone. The endpoint path includes placeholders for the zone identifier and the record
|
||||||
* identifier, which need to be provided to construct the complete path.
|
* identifier, which need to be provided to construct the complete path.
|
||||||
*/
|
*/
|
||||||
RECORD_DELETE("/zones/%s/dns_records/%s");
|
RECORD_DELETE("/zones/%s/dns_records/%s");
|
||||||
|
|||||||
@@ -1,14 +1,34 @@
|
|||||||
package codes.thischwa.cf;
|
package codes.thischwa.cf;
|
||||||
|
|
||||||
|
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||||
import java.io.Serial;
|
import java.io.Serial;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a custom exception for errors encountered while interacting with the Cloudflare API.
|
* Represents a custom exception for errors encountered while interacting with the Cloudflare API.
|
||||||
|
*
|
||||||
|
* <p>If the error was caused by an API response, {@link #getStatusCode()} returns the HTTP status
|
||||||
|
* code and {@link #getErrors()} the errors reported by Cloudflare.
|
||||||
*/
|
*/
|
||||||
public class CloudflareApiException extends Exception {
|
public class CloudflareApiException extends Exception {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Value of {@link #getStatusCode()} if the exception was not caused by an HTTP response.
|
||||||
|
*/
|
||||||
|
public static final int NO_STATUS_CODE = -1;
|
||||||
|
|
||||||
@Serial
|
@Serial
|
||||||
private static final long serialVersionUID = 1L;
|
private static final long serialVersionUID = 2L;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The HTTP status code of the response, or {@link #NO_STATUS_CODE}.
|
||||||
|
*/
|
||||||
|
private final int statusCode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The errors reported by Cloudflare. Transient, because the error class isn't serializable.
|
||||||
|
*/
|
||||||
|
private final transient List<ResponseResultInfo.Error> errors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new CloudflareApiException with the specified detail message.
|
* Constructs a new CloudflareApiException with the specified detail message.
|
||||||
@@ -16,7 +36,7 @@ public class CloudflareApiException extends Exception {
|
|||||||
* @param message the detail message, which provides more information about the exception.
|
* @param message the detail message, which provides more information about the exception.
|
||||||
*/
|
*/
|
||||||
public CloudflareApiException(String message) {
|
public CloudflareApiException(String message) {
|
||||||
super(message);
|
this(message, NO_STATUS_CODE, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -29,5 +49,40 @@ public class CloudflareApiException extends Exception {
|
|||||||
*/
|
*/
|
||||||
public CloudflareApiException(String message, Throwable cause) {
|
public CloudflareApiException(String message, Throwable cause) {
|
||||||
super(message, cause);
|
super(message, cause);
|
||||||
|
this.statusCode = NO_STATUS_CODE;
|
||||||
|
this.errors = List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs a new CloudflareApiException caused by an API response.
|
||||||
|
*
|
||||||
|
* @param message the detail message
|
||||||
|
* @param statusCode the HTTP status code of the response, or {@link #NO_STATUS_CODE}
|
||||||
|
* @param errors the errors reported by Cloudflare, may be {@code null}
|
||||||
|
*/
|
||||||
|
public CloudflareApiException(String message, int statusCode,
|
||||||
|
List<ResponseResultInfo.Error> errors) {
|
||||||
|
super(message);
|
||||||
|
this.statusCode = statusCode;
|
||||||
|
this.errors = errors == null ? List.of() : List.copyOf(errors);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the HTTP status code of the response that caused this exception.
|
||||||
|
*
|
||||||
|
* @return the HTTP status code, or {@link #NO_STATUS_CODE} if the exception wasn't caused by an
|
||||||
|
* HTTP response
|
||||||
|
*/
|
||||||
|
public int getStatusCode() {
|
||||||
|
return statusCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the errors reported by Cloudflare.
|
||||||
|
*
|
||||||
|
* @return an unmodifiable list of errors, never {@code null}
|
||||||
|
*/
|
||||||
|
public List<ResponseResultInfo.Error> getErrors() {
|
||||||
|
return errors == null ? List.of() : errors;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,21 @@
|
|||||||
package codes.thischwa.cf;
|
package codes.thischwa.cf;
|
||||||
|
|
||||||
|
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||||
|
import java.io.Serial;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This exception is thrown to indicate that a requested resource was not found during interaction
|
* This exception is thrown to indicate that a requested resource was not found during interaction
|
||||||
* with the Cloudflare API.
|
* with the Cloudflare API.
|
||||||
*
|
*
|
||||||
* <p>It extends {@link CloudflareApiException} to provide specific errors related to situations
|
* <p>It is thrown if Cloudflare responds with HTTP status 404, or if a result is empty and
|
||||||
* where Cloudflare responds with a "not found" operation.
|
* 'emptyResultThrowsException' is enabled.
|
||||||
*/
|
*/
|
||||||
public class CloudflareNotFoundException extends CloudflareApiException {
|
public class CloudflareNotFoundException extends CloudflareApiException {
|
||||||
|
|
||||||
|
@Serial
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Constructs a new CloudflareNotFoundException with the specified detail message.
|
* Constructs a new CloudflareNotFoundException with the specified detail message.
|
||||||
*
|
*
|
||||||
@@ -18,4 +25,16 @@ public class CloudflareNotFoundException extends CloudflareApiException {
|
|||||||
public CloudflareNotFoundException(String message) {
|
public CloudflareNotFoundException(String message) {
|
||||||
super(message);
|
super(message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs a new CloudflareNotFoundException caused by an API response.
|
||||||
|
*
|
||||||
|
* @param message the detail message
|
||||||
|
* @param statusCode the HTTP status code of the response
|
||||||
|
* @param errors the errors reported by Cloudflare, may be {@code null}
|
||||||
|
*/
|
||||||
|
public CloudflareNotFoundException(String message, int statusCode,
|
||||||
|
List<ResponseResultInfo.Error> errors) {
|
||||||
|
super(message, statusCode, errors);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
package codes.thischwa.cf;
|
package codes.thischwa.cf;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
import tools.jackson.databind.DeserializationFeature;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import tools.jackson.databind.ObjectMapper;
|
||||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
import tools.jackson.databind.PropertyNamingStrategies;
|
||||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The JsonConf class provides a utility method for initializing and configuring a shared
|
* The JsonConf class provides a utility method for initializing and configuring a shared
|
||||||
@@ -16,11 +16,11 @@ class JsonConf {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static ObjectMapper initObjectMapper() {
|
static ObjectMapper initObjectMapper() {
|
||||||
ObjectMapper mapper = new ObjectMapper();
|
return JsonMapper.builder()
|
||||||
mapper.registerModule(new JavaTimeModule());
|
.changeDefaultPropertyInclusion(
|
||||||
mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
|
incl -> incl.withValueInclusion(JsonInclude.Include.NON_NULL))
|
||||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
|
||||||
mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
|
.propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE)
|
||||||
return mapper;
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
package codes.thischwa.cf;
|
package codes.thischwa.cf;
|
||||||
|
|
||||||
|
import codes.thischwa.cf.model.AbstractMultipleResponse;
|
||||||
import codes.thischwa.cf.model.AbstractResponse;
|
import codes.thischwa.cf.model.AbstractResponse;
|
||||||
import codes.thischwa.cf.model.AbstractSingleResponse;
|
import codes.thischwa.cf.model.AbstractSingleResponse;
|
||||||
import codes.thischwa.cf.model.RecordMultipleResponse;
|
|
||||||
import codes.thischwa.cf.model.ResponseResultInfo;
|
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@@ -16,7 +16,7 @@ import java.util.stream.Collectors;
|
|||||||
* metadata. If the response indicates failure, an exception is thrown with descriptive error
|
* metadata. If the response indicates failure, an exception is thrown with descriptive error
|
||||||
* messages.
|
* messages.
|
||||||
* <li>It validates the number of results in the API response payload to detect unexpected counts.
|
* <li>It validates the number of results in the API response payload to detect unexpected counts.
|
||||||
* For {@link RecordMultipleResponse}, it checks if results are empty or if more than one result
|
* For {@link AbstractMultipleResponse}, it checks if results are empty or if more than one result
|
||||||
* was returned when a single result was expected. For {@link AbstractSingleResponse}, it checks
|
* was returned when a single result was expected. For {@link AbstractSingleResponse}, it checks
|
||||||
* if the result is null. Depending on the parameter 'emptyResultThrowsException', an exception
|
* if the result is null. Depending on the parameter 'emptyResultThrowsException', an exception
|
||||||
* will be triggered or an empty/null result will be returned.
|
* will be triggered or an empty/null result will be returned.
|
||||||
@@ -45,16 +45,16 @@ class ResponseValidator {
|
|||||||
|
|
||||||
private void validateResultCount(AbstractResponse resp, boolean singleResultExpected)
|
private void validateResultCount(AbstractResponse resp, boolean singleResultExpected)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
if (resp instanceof RecordMultipleResponse respMulti) {
|
if (resp instanceof AbstractMultipleResponse<?> respMulti) {
|
||||||
validateMultipleResponse(respMulti, singleResultExpected);
|
validateMultipleResponse(respMulti, singleResultExpected);
|
||||||
} else if (resp instanceof AbstractSingleResponse<?> respSingle) {
|
} else if (resp instanceof AbstractSingleResponse<?> respSingle) {
|
||||||
validateSingleResponse(respSingle);
|
validateSingleResponse(respSingle);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void validateMultipleResponse(RecordMultipleResponse response, boolean singleResultExpected)
|
private void validateMultipleResponse(AbstractMultipleResponse<?> response, boolean singleResultExpected)
|
||||||
throws CloudflareApiException {
|
throws CloudflareApiException {
|
||||||
int totalCount = response.getResultInfo().totalCount();
|
int totalCount = getTotalCount(response);
|
||||||
if (singleResultExpected && totalCount > 1) {
|
if (singleResultExpected && totalCount > 1) {
|
||||||
throw new CloudflareApiException("Unexpected result count: " + totalCount);
|
throw new CloudflareApiException("Unexpected result count: " + totalCount);
|
||||||
}
|
}
|
||||||
@@ -63,6 +63,17 @@ class ResponseValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determines the total count of the results. Falls back to the size of the result list if the
|
||||||
|
* response contains no result info.
|
||||||
|
*/
|
||||||
|
private static int getTotalCount(AbstractMultipleResponse<?> response) {
|
||||||
|
if (response.getResultInfo() != null) {
|
||||||
|
return response.getResultInfo().totalCount();
|
||||||
|
}
|
||||||
|
return response.getResult() == null ? 0 : response.getResult().size();
|
||||||
|
}
|
||||||
|
|
||||||
private void validateSingleResponse(AbstractSingleResponse<?> response)
|
private void validateSingleResponse(AbstractSingleResponse<?> response)
|
||||||
throws CloudflareNotFoundException {
|
throws CloudflareNotFoundException {
|
||||||
if (emptyResultThrowsException && response.getResult() == null) {
|
if (emptyResultThrowsException && response.getResult() == null) {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import codes.thischwa.cf.model.RecordType;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fluent interface for getRecord-level operations.
|
* Fluent interface for record-level operations.
|
||||||
* Provides a chainable API for CRUD operations on DNS records.
|
* Provides a chainable API for CRUD operations on DNS records.
|
||||||
*/
|
*/
|
||||||
public interface RecordOperations {
|
public interface RecordOperations {
|
||||||
@@ -20,29 +20,29 @@ public interface RecordOperations {
|
|||||||
List<RecordEntity> get() throws CloudflareApiException;
|
List<RecordEntity> get() throws CloudflareApiException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new DNS getRecord with the specified parameters.
|
* Creates a new DNS record with the specified parameters.
|
||||||
*
|
*
|
||||||
* @param type the DNS getRecord type (e.g., A, AAAA, CNAME)
|
* @param type the DNS record type (e.g., A, AAAA, CNAME)
|
||||||
* @param content the content of the DNS getRecord (e.g., IP address)
|
* @param content the content of the DNS record (e.g., IP address)
|
||||||
* @param ttl the time-to-live value in seconds
|
* @param ttl the time-to-live value in seconds
|
||||||
* @return the created RecordEntity
|
* @return the created RecordEntity
|
||||||
* @throws CloudflareApiException if an error occurs while creating the getRecord
|
* @throws CloudflareApiException if an error occurs while creating the record
|
||||||
*/
|
*/
|
||||||
RecordEntity create(RecordType type, String content, int ttl) throws CloudflareApiException;
|
RecordEntity create(RecordType type, String content, int ttl) throws CloudflareApiException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Updates an existing DNS getRecord with new content.
|
* Updates an existing DNS record with new content.
|
||||||
*
|
*
|
||||||
* @param newContent the new content for the DNS getRecord
|
* @param newContent the new content for the DNS record
|
||||||
* @return the updated RecordEntity
|
* @return the updated RecordEntity
|
||||||
* @throws CloudflareApiException if an error occurs while updating the getRecord
|
* @throws CloudflareApiException if an error occurs while updating the record
|
||||||
*/
|
*/
|
||||||
RecordEntity update(String newContent) throws CloudflareApiException;
|
RecordEntity update(String newContent) throws CloudflareApiException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes DNS records of the specified types.
|
* Deletes DNS records of the specified types.
|
||||||
*
|
*
|
||||||
* @param types the DNS getRecord types to delete
|
* @param types the DNS record types to delete
|
||||||
* @throws CloudflareApiException if an error occurs while deleting records
|
* @throws CloudflareApiException if an error occurs while deleting records
|
||||||
*/
|
*/
|
||||||
void delete(RecordType... types) throws CloudflareApiException;
|
void delete(RecordType... types) throws CloudflareApiException;
|
||||||
|
|||||||
@@ -9,13 +9,13 @@ import java.util.List;
|
|||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Implementation of RecordOperations for fluent API access to getRecord-level operations.
|
* Implementation of RecordOperations for fluent API access to record-level operations.
|
||||||
*/
|
*/
|
||||||
public class RecordOperationsImpl implements RecordOperations {
|
public class RecordOperationsImpl implements RecordOperations {
|
||||||
|
|
||||||
private final CfDnsClient client;
|
private final CfDnsClient client;
|
||||||
private final ZoneEntity zone;
|
private final ZoneEntity zone;
|
||||||
private final String sld;
|
private final String subdomain;
|
||||||
private final RecordType[] types;
|
private final RecordType[] types;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,42 +23,41 @@ public class RecordOperationsImpl implements RecordOperations {
|
|||||||
*
|
*
|
||||||
* @param client the CfDnsClient instance to use for operations
|
* @param client the CfDnsClient instance to use for operations
|
||||||
* @param zone the ZoneEntity representing the DNS zone
|
* @param zone the ZoneEntity representing the DNS zone
|
||||||
* @param sld the subdomain (second-level domain) name
|
* @param subdomain the subdomain relative to the zone, or "@" for the zone apex
|
||||||
* @param types optional array of RecordType to filter by
|
* @param types optional array of RecordType to filter by
|
||||||
*/
|
*/
|
||||||
public RecordOperationsImpl(CfDnsClient client, ZoneEntity zone, String sld, @Nullable RecordType[] types) {
|
public RecordOperationsImpl(CfDnsClient client, ZoneEntity zone, String subdomain, @Nullable RecordType[] types) {
|
||||||
this.client = client;
|
this.client = client;
|
||||||
this.zone = zone;
|
this.zone = zone;
|
||||||
this.sld = sld;
|
this.subdomain = subdomain;
|
||||||
this.types = types;
|
this.types = types;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<RecordEntity> get() throws CloudflareApiException {
|
public List<RecordEntity> get() throws CloudflareApiException {
|
||||||
return client.recordList(zone, sld, types);
|
return client.recordListBySubdomain(zone, subdomain, types);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public RecordEntity create(RecordType type, String content, int ttl) throws CloudflareApiException {
|
public RecordEntity create(RecordType type, String content, int ttl) throws CloudflareApiException {
|
||||||
return client.recordCreateSld(zone, sld, ttl, type, content);
|
return client.recordCreateSubdomain(zone, subdomain, ttl, type, content);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public RecordEntity update(String newContent) throws CloudflareApiException {
|
public RecordEntity update(String newContent) throws CloudflareApiException {
|
||||||
List<RecordEntity> recs = get();
|
List<RecordEntity> recs = get();
|
||||||
if (recs.isEmpty()) {
|
if (recs.isEmpty()) {
|
||||||
throw new CloudflareApiException("No recs found to update for subdomain: " + sld);
|
throw new CloudflareApiException("No recs found to update for subdomain: " + subdomain);
|
||||||
}
|
}
|
||||||
if (recs.size() > 1) {
|
if (recs.size() > 1) {
|
||||||
throw new CloudflareApiException("Multiple recs found. Please use recordUpdate() directly for precise control.");
|
throw new CloudflareApiException("Multiple recs found. Please use recordUpdate() directly for precise control.");
|
||||||
}
|
}
|
||||||
RecordEntity rec = recs.get(0);
|
// partial update: only the content is changed
|
||||||
rec.setContent(newContent);
|
return client.recordUpdate(zone, RecordEntity.build(recs.get(0).getId(), newContent));
|
||||||
return client.recordUpdate(zone, rec);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void delete(RecordType... types) throws CloudflareApiException {
|
public void delete(RecordType... types) throws CloudflareApiException {
|
||||||
client.recordDeleteTypeIfExists(zone, sld, types);
|
client.recordDeleteTypeIfExists(zone, subdomain, types);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,21 +13,21 @@ public interface ZoneOperations {
|
|||||||
/**
|
/**
|
||||||
* Selects a record (subdomain) within the zone for further operations.
|
* Selects a record (subdomain) within the zone for further operations.
|
||||||
*
|
*
|
||||||
* @param sld the second-level domain (subdomain) name
|
* @param subdomain the subdomain relative to the zone (e.g. "www"), or "@" for the zone apex
|
||||||
* @return a RecordOperations instance for chaining record-specific operations
|
* @return a RecordOperations instance for chaining record-specific operations
|
||||||
* @throws CloudflareApiException if the zone cannot be found or accessed
|
* @throws CloudflareApiException if the zone cannot be found or accessed
|
||||||
*/
|
*/
|
||||||
RecordOperations getRecord(String sld) throws CloudflareApiException;
|
RecordOperations getRecord(String subdomain) throws CloudflareApiException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Selects a record with specific types within the zone for further operations.
|
* Selects a record with specific types within the zone for further operations.
|
||||||
*
|
*
|
||||||
* @param sld the second-level domain (subdomain) name
|
* @param subdomain the subdomain relative to the zone (e.g. "www"), or "@" for the zone apex
|
||||||
* @param types optional DNS record types to filter by
|
* @param types optional DNS record types to filter by
|
||||||
* @return a RecordOperations instance for chaining record-specific operations
|
* @return a RecordOperations instance for chaining record-specific operations
|
||||||
* @throws CloudflareApiException if the zone cannot be found or accessed
|
* @throws CloudflareApiException if the zone cannot be found or accessed
|
||||||
*/
|
*/
|
||||||
RecordOperations getRecord(String sld, @Nullable RecordType... types) throws CloudflareApiException;
|
RecordOperations getRecord(String subdomain, @Nullable RecordType... types) throws CloudflareApiException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lists all DNS records within the zone, optionally filtered by types.
|
* Lists all DNS records within the zone, optionally filtered by types.
|
||||||
|
|||||||
@@ -28,17 +28,17 @@ public class ZoneOperationsImpl implements ZoneOperations {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public RecordOperations getRecord(String sld) throws CloudflareApiException {
|
public RecordOperations getRecord(String subdomain) throws CloudflareApiException {
|
||||||
return new RecordOperationsImpl(client, zone, sld, null);
|
return new RecordOperationsImpl(client, zone, subdomain, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public RecordOperations getRecord(String sld, @Nullable RecordType... types) throws CloudflareApiException {
|
public RecordOperations getRecord(String subdomain, @Nullable RecordType... types) throws CloudflareApiException {
|
||||||
return new RecordOperationsImpl(client, zone, sld, types);
|
return new RecordOperationsImpl(client, zone, subdomain, types);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<RecordEntity> list(@Nullable RecordType... types) throws CloudflareApiException {
|
public List<RecordEntity> list(@Nullable RecordType... types) throws CloudflareApiException {
|
||||||
return client.recordList(zone, types);
|
return client.recordListByType(zone, types);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
*
|
*
|
||||||
* <p>Example usage:
|
* <p>Example usage:
|
||||||
* <pre><code>
|
* <pre><code>
|
||||||
* // Create a DNS getRecord
|
* // Create a DNS record
|
||||||
* client.zone("example.com")
|
* client.zone("example.com")
|
||||||
* .getRecord("api")
|
* .getRecord("api")
|
||||||
* .create(RecordType.A, "192.168.1.1", 60);
|
* .create(RecordType.A, "192.168.1.1", 60);
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
* .getRecord("www", RecordType.A)
|
* .getRecord("www", RecordType.A)
|
||||||
* .get();
|
* .get();
|
||||||
*
|
*
|
||||||
* // Update a DNS getRecord
|
* // Update a DNS record
|
||||||
* client.zone("example.com")
|
* client.zone("example.com")
|
||||||
* .getRecord("api", RecordType.A)
|
* .getRecord("api", RecordType.A)
|
||||||
* .update("192.168.1.2");
|
* .update("192.168.1.2");
|
||||||
|
|||||||
@@ -5,11 +5,11 @@ import lombok.Data;
|
|||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a batch entry containing different types of operations on getRecord entities.
|
* Represents a batch entry containing different types of operations on record entities.
|
||||||
*
|
*
|
||||||
* <p>A BatchEntry groups together collections of operations (patches, posts, puts, and deletes)
|
* <p>A BatchEntry groups together collections of operations (patches, posts, puts, and deletes)
|
||||||
* intended to be performed as part of a single batch process. Each operation corresponds to a specific
|
* intended to be performed as part of a single batch process. Each operation corresponds to a specific
|
||||||
* type of action on DNS getRecord entities.
|
* type of action on DNS record entities.
|
||||||
*
|
*
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li><b>patches</b>: A list of {@link RecordEntity} objects representing partial updates to existing records.
|
* <li><b>patches</b>: A list of {@link RecordEntity} objects representing partial updates to existing records.
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ package codes.thischwa.cf.model;
|
|||||||
*
|
*
|
||||||
* <p>This class is used for API responses where the primary result is a batch entry,
|
* <p>This class is used for API responses where the primary result is a batch entry,
|
||||||
* which includes collections of operations such as patches, posts, puts, and deletes
|
* which includes collections of operations such as patches, posts, puts, and deletes
|
||||||
* performed on DNS getRecord entities.
|
* performed on DNS record entities.
|
||||||
*
|
*
|
||||||
* <p>Extends {@code AbstractSingleResponse} with {@code BatchEntry} as the generic type,
|
* <p>Extends {@code AbstractSingleResponse} with {@code BatchEntry} as the generic type,
|
||||||
* ensuring that the response result is a batch of operations.
|
* ensuring that the response result is a batch of operations.
|
||||||
|
|||||||
@@ -1,51 +1,83 @@
|
|||||||
package codes.thischwa.cf.model;
|
package codes.thischwa.cf.model;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
import org.jetbrains.annotations.Nullable;
|
import org.jetbrains.annotations.Nullable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents a DNS getRecord entity within a specific zone.
|
* Represents a DNS record entity within a specific zone.
|
||||||
*
|
*
|
||||||
* <p>Attributes defined in this class include:
|
* <p>Attributes defined in this class include:
|
||||||
*
|
*
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>DNS getRecord type such as "A" or "CNAME".
|
* <li>DNS record type such as "A" or "CNAME".
|
||||||
* <li>Name of the DNS getRecord.
|
* <li>Name of the DNS record.
|
||||||
* <li>Content of the DNS getRecord, such as an IP address.
|
* <li>Content of the DNS record, such as an IP address.
|
||||||
* <li>Flags indicating whether the getRecord is proxiable or proxied.
|
* <li>Flags indicating whether the record is proxiable or proxied.
|
||||||
* <li>TTL (Time-To-Live) for the DNS getRecord.
|
* <li>TTL (Time-To-Live) for the DNS record.
|
||||||
* <li>A locked status to indicate the immutability of the getRecord.
|
* <li>Priority, required for MX and URI records (for SRV records it's part of the data).
|
||||||
|
* <li>Structured data, required for e.g. SRV, CAA, LOC or TLSA records instead of content.
|
||||||
|
* <li>An optional comment and tags.
|
||||||
|
* <li>A locked status to indicate the immutability of the record.
|
||||||
* <li>Zone-specific metadata including zone ID and name.
|
* <li>Zone-specific metadata including zone ID and name.
|
||||||
* <li>Timestamps for creation and modification.
|
* <li>Timestamps for creation and modification (UTC).
|
||||||
* </ul>
|
* </ul>
|
||||||
*
|
*
|
||||||
* <p>Provides a static factory method {@code build} for creating a DNS getRecord with specific
|
* <p>Provides a static factory method {@code build} for creating a DNS record with specific
|
||||||
* attributes.
|
* attributes.
|
||||||
*/
|
*/
|
||||||
@EqualsAndHashCode(callSuper = true)
|
@EqualsAndHashCode(callSuper = true)
|
||||||
@Data
|
@Data
|
||||||
public class RecordEntity extends AbstractEntity {
|
public class RecordEntity extends AbstractEntity {
|
||||||
|
private static final String APEX = "@";
|
||||||
|
|
||||||
private String type;
|
private String type;
|
||||||
private String name;
|
private String name;
|
||||||
private String content;
|
private String content;
|
||||||
private Boolean proxiable;
|
private Boolean proxiable;
|
||||||
private Boolean proxied;
|
private Boolean proxied;
|
||||||
private Integer ttl;
|
private Integer ttl;
|
||||||
|
/**
|
||||||
|
* Priority of the record, required for MX and URI records. For SRV records the priority is
|
||||||
|
* part of {@link #data}.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private Integer priority;
|
||||||
|
/**
|
||||||
|
* Comment of the record, only used by Cloudflare.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private String comment;
|
||||||
|
/**
|
||||||
|
* Custom tags of the record in the form "name:value", only used by Cloudflare.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private List<String> tags;
|
||||||
|
/**
|
||||||
|
* Structured content of the record, e.g. for SRV records the keys "priority", "weight", "port"
|
||||||
|
* and "target".
|
||||||
|
* The keys are the same as in the Cloudflare API.
|
||||||
|
*/
|
||||||
|
@Nullable
|
||||||
|
private Map<String, Object> data;
|
||||||
private Boolean locked;
|
private Boolean locked;
|
||||||
@Nullable
|
@Nullable
|
||||||
private String zoneId;
|
private String zoneId;
|
||||||
@Nullable
|
@Nullable
|
||||||
private String zoneName;
|
private String zoneName;
|
||||||
@Nullable
|
@Nullable
|
||||||
private LocalDateTime modifiedOn;
|
private Instant modifiedOn;
|
||||||
@Nullable
|
@Nullable
|
||||||
private LocalDateTime createdOn;
|
private Instant createdOn;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes a new instance of the RecordEntity class and invokes the parent constructor from
|
* Initializes a new instance of the RecordEntity class and invokes the parent constructor from
|
||||||
* the AbstractEntity class. The RecordEntity class represents a DNS getRecord entity within a
|
* the AbstractEntity class. The RecordEntity class represents a DNS record entity within a
|
||||||
* specific zone, encapsulating attributes such as type, name, content, TTL, and other related
|
* specific zone, encapsulating attributes such as type, name, content, TTL, and other related
|
||||||
* metadata.
|
* metadata.
|
||||||
*/
|
*/
|
||||||
@@ -56,10 +88,10 @@ public class RecordEntity extends AbstractEntity {
|
|||||||
/**
|
/**
|
||||||
* Builds and returns a {@link RecordEntity} instance with the specified attributes.
|
* Builds and returns a {@link RecordEntity} instance with the specified attributes.
|
||||||
*
|
*
|
||||||
* @param name the name of the DNS getRecord
|
* @param name the name of the DNS record
|
||||||
* @param type the {@link RecordType} of the DNS getRecord
|
* @param type the {@link RecordType} of the DNS record
|
||||||
* @param ttl the time-to-live (TTL) value for the DNS getRecord
|
* @param ttl the time-to-live (TTL) value for the DNS record
|
||||||
* @param content the content of the DNS getRecord, typically an IP address
|
* @param content the content of the DNS record, typically an IP address
|
||||||
* @return a {@link RecordEntity} populated with the provided attributes
|
* @return a {@link RecordEntity} populated with the provided attributes
|
||||||
*/
|
*/
|
||||||
public static RecordEntity build(String name, RecordType type, Integer ttl, String content) {
|
public static RecordEntity build(String name, RecordType type, Integer ttl, String content) {
|
||||||
@@ -74,8 +106,8 @@ public class RecordEntity extends AbstractEntity {
|
|||||||
/**
|
/**
|
||||||
* Builds and returns a {@link RecordEntity} instance with the specified ID and content.
|
* Builds and returns a {@link RecordEntity} instance with the specified ID and content.
|
||||||
*
|
*
|
||||||
* @param id the unique identifier for the DNS getRecord
|
* @param id the unique identifier for the DNS record
|
||||||
* @param content the content of the DNS getRecord, typically an IP address or other getRecord data
|
* @param content the content of the DNS record, typically an IP address or other record data
|
||||||
* @return a {@link RecordEntity} populated with the provided ID and content
|
* @return a {@link RecordEntity} populated with the provided ID and content
|
||||||
*/
|
*/
|
||||||
public static RecordEntity build(String id, String content) {
|
public static RecordEntity build(String id, String content) {
|
||||||
@@ -88,11 +120,11 @@ public class RecordEntity extends AbstractEntity {
|
|||||||
/**
|
/**
|
||||||
* Builds and returns a {@link RecordEntity} instance with the specified attributes.
|
* Builds and returns a {@link RecordEntity} instance with the specified attributes.
|
||||||
*
|
*
|
||||||
* @param id the unique identifier for the DNS getRecord
|
* @param id the unique identifier for the DNS record
|
||||||
* @param name the name of the DNS getRecord
|
* @param name the name of the DNS record
|
||||||
* @param type the type of the DNS getRecord, represented as a string (e.g., "A", "CNAME")
|
* @param type the type of the DNS record, represented as a string (e.g., "A", "CNAME")
|
||||||
* @param ttl the time-to-live (TTL) value for the DNS getRecord
|
* @param ttl the time-to-live (TTL) value for the DNS record
|
||||||
* @param content the content of the DNS getRecord, typically an IP address or other getRecord data
|
* @param content the content of the DNS record, typically an IP address or other record data
|
||||||
* @return a {@link RecordEntity} populated with the provided attributes
|
* @return a {@link RecordEntity} populated with the provided attributes
|
||||||
* @throws IllegalArgumentException if the type string is not a valid RecordType
|
* @throws IllegalArgumentException if the type string is not a valid RecordType
|
||||||
*/
|
*/
|
||||||
@@ -101,7 +133,7 @@ public class RecordEntity extends AbstractEntity {
|
|||||||
try {
|
try {
|
||||||
recordType = RecordType.valueOf(type);
|
recordType = RecordType.valueOf(type);
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
throw new IllegalArgumentException("Invalid getRecord type: " + type + ". Must be one of: "
|
throw new IllegalArgumentException("Invalid record type: " + type + ". Must be one of: "
|
||||||
+ java.util.Arrays.toString(RecordType.values()), e);
|
+ java.util.Arrays.toString(RecordType.values()), e);
|
||||||
}
|
}
|
||||||
RecordEntity rec = new RecordEntity();
|
RecordEntity rec = new RecordEntity();
|
||||||
@@ -114,22 +146,31 @@ public class RecordEntity extends AbstractEntity {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves the short name (subdomain) of the DNS getRecord.
|
* Retrieves the subdomain of the DNS record, i.e. the record name relative to its zone.
|
||||||
* If the name contains a dot ('.'), only the substring before the first dot is returned.
|
|
||||||
* This is useful for getting the subdomain part of a fully qualified domain name.
|
|
||||||
*
|
*
|
||||||
* @return the short name of the DNS getRecord (substring before the first dot),
|
* <p>If the zone name is known, the zone name is stripped from the record name, e.g.
|
||||||
* or the full name if no dot is present
|
* {@code my.sub.example.com} results in {@code my.sub}. A record at the zone apex results in
|
||||||
|
* {@code "@"}. If the zone name is unknown, only the substring before the first dot is returned.
|
||||||
|
*
|
||||||
|
* @return the short name of the DNS record, {@code "@"} for the zone apex, or the full name if
|
||||||
|
* no dot is present
|
||||||
*/
|
*/
|
||||||
public String getSld() {
|
@JsonIgnore
|
||||||
|
@Nullable
|
||||||
|
public String getSubdomain() {
|
||||||
if (name == null) {
|
if (name == null) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (zoneName != null && name.endsWith(zoneName)) {
|
if (zoneName != null && !zoneName.isEmpty()) {
|
||||||
int zoneNameLength = zoneName.length();
|
String lowerName = name.toLowerCase(Locale.ROOT);
|
||||||
int dotSeparatorLength = 1;
|
String lowerZone = zoneName.toLowerCase(Locale.ROOT);
|
||||||
return name.substring(0, name.length() - zoneNameLength - dotSeparatorLength);
|
if (lowerName.equals(lowerZone)) {
|
||||||
|
return APEX;
|
||||||
|
}
|
||||||
|
if (lowerName.endsWith("." + lowerZone)) {
|
||||||
|
return name.substring(0, name.length() - zoneName.length() - 1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int firstDotPosition = name.indexOf('.');
|
int firstDotPosition = name.indexOf('.');
|
||||||
@@ -139,4 +180,17 @@ public class RecordEntity extends AbstractEntity {
|
|||||||
|
|
||||||
return name;
|
return name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves the subdomain of the DNS record.
|
||||||
|
*
|
||||||
|
* @return the subdomain of the DNS record
|
||||||
|
* @deprecated The name was misleading, use {@link #getSubdomain()} instead.
|
||||||
|
*/
|
||||||
|
@Deprecated(since = "0.6.0", forRemoval = true)
|
||||||
|
@JsonIgnore
|
||||||
|
@Nullable
|
||||||
|
public String getSld() {
|
||||||
|
return getSubdomain();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -9,7 +9,7 @@ public class RecordMultipleResponse extends AbstractMultipleResponse<RecordEntit
|
|||||||
/**
|
/**
|
||||||
* Constructs an instance of RecordMultipleResponse.
|
* Constructs an instance of RecordMultipleResponse.
|
||||||
*
|
*
|
||||||
* <p>This class represents a response containing multiple DNS getRecord entities from the
|
* <p>This class represents a response containing multiple DNS record entities from the
|
||||||
* Cloudflare API. It inherits functionality from AbstractMultipleResponse to handle multiple
|
* Cloudflare API. It inherits functionality from AbstractMultipleResponse to handle multiple
|
||||||
* records of type RecordEntity.
|
* records of type RecordEntity.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ public class RecordSingleResponse extends AbstractSingleResponse<RecordEntity> {
|
|||||||
*
|
*
|
||||||
* <p>This constructor initializes the RecordSingleResponse object by invoking the superclass
|
* <p>This constructor initializes the RecordSingleResponse object by invoking the superclass
|
||||||
* constructor. The RecordSingleResponse represents a specific API response structure that
|
* constructor. The RecordSingleResponse represents a specific API response structure that
|
||||||
* encapsulates a single DNS getRecord entity, providing mechanisms to interact with such data in the
|
* encapsulates a single DNS record entity, providing mechanisms to interact with such data in the
|
||||||
* context of the Cloudflare API.
|
* context of the Cloudflare API.
|
||||||
*/
|
*/
|
||||||
public RecordSingleResponse() {
|
public RecordSingleResponse() {
|
||||||
|
|||||||
@@ -3,86 +3,86 @@ package codes.thischwa.cf.model;
|
|||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Enum representing various DNS getRecord types.
|
* Enum representing various DNS record types.
|
||||||
*
|
*
|
||||||
* <p>Each constant in this enum corresponds to a specific DNS getRecord type, such as "A", "AAAA",
|
* <p>Each constant in this enum corresponds to a specific DNS record type, such as "A", "AAAA",
|
||||||
* "CNAME", or "TXT". This enum provides a means to standardize the representation of these getRecord
|
* "CNAME", or "TXT". This enum provides a means to standardize the representation of these record
|
||||||
* types throughout the application while allowing easy retrieval of their string representation.
|
* types throughout the application while allowing easy retrieval of their string representation.
|
||||||
*/
|
*/
|
||||||
@Getter
|
@Getter
|
||||||
public enum RecordType {
|
public enum RecordType {
|
||||||
/**
|
/**
|
||||||
* Represents the DNS A getRecord type.
|
* Represents the DNS A record type.
|
||||||
*
|
*
|
||||||
* <p>The "A" getRecord type is used to map a domain name to an IPv4 address.
|
* <p>The "A" record type is used to map a domain name to an IPv4 address.
|
||||||
*/
|
*/
|
||||||
A("A"),
|
A("A"),
|
||||||
/**
|
/**
|
||||||
* Represents the DNS AAAA getRecord type.
|
* Represents the DNS AAAA record type.
|
||||||
*
|
*
|
||||||
* <p>The "AAAA" getRecord type maps a domain name to an IPv6 address.
|
* <p>The "AAAA" record type maps a domain name to an IPv6 address.
|
||||||
*/
|
*/
|
||||||
AAAA("AAAA"),
|
AAAA("AAAA"),
|
||||||
/**
|
/**
|
||||||
* Represents the DNS CAA (Certificate Authority Authorization) getRecord type.
|
* Represents the DNS CAA (Certificate Authority Authorization) record type.
|
||||||
*
|
*
|
||||||
* <p>The "CAA" getRecord type is used to specify which certificate authorities (CAs) are allowed to
|
* <p>The "CAA" record type is used to specify which certificate authorities (CAs) are allowed to
|
||||||
* issue SSL/TLS certificates for a domain.
|
* issue SSL/TLS certificates for a domain.
|
||||||
*/
|
*/
|
||||||
CAA("CAA"),
|
CAA("CAA"),
|
||||||
/**
|
/**
|
||||||
* Represents the DNS CERT getRecord type.
|
* Represents the DNS CERT record type.
|
||||||
*
|
*
|
||||||
* <p>The "CERT" getRecord type is used to store certificates and related certificate revocation
|
* <p>The "CERT" record type is used to store certificates and related certificate revocation
|
||||||
* lists or certificate authority data in DNS zones.
|
* lists or certificate authority data in DNS zones.
|
||||||
*/
|
*/
|
||||||
CERT("CERT"),
|
CERT("CERT"),
|
||||||
/**
|
/**
|
||||||
* Represents the DNS CNAME (Canonical Name) getRecord type.
|
* Represents the DNS CNAME (Canonical Name) record type.
|
||||||
*
|
*
|
||||||
* <p>The "CNAME" getRecord type is used to alias one domain name to another.
|
* <p>The "CNAME" record type is used to alias one domain name to another.
|
||||||
*/
|
*/
|
||||||
CNAME("CNAME"),
|
CNAME("CNAME"),
|
||||||
/**
|
/**
|
||||||
* Represents the DNSKEY getRecord type.
|
* Represents the DNSKEY record type.
|
||||||
*
|
*
|
||||||
* <p>The "DNSKEY" getRecord type is used for storing public keys in DNS, as part of the DNS Security
|
* <p>The "DNSKEY" record type is used for storing public keys in DNS, as part of the DNS Security
|
||||||
* Extensions (DNSSEC). It helps in verifying the authenticity of DNS responses through digital
|
* Extensions (DNSSEC). It helps in verifying the authenticity of DNS responses through digital
|
||||||
* signatures.
|
* signatures.
|
||||||
*/
|
*/
|
||||||
DNSKEY("DNSKEY"),
|
DNSKEY("DNSKEY"),
|
||||||
/**
|
/**
|
||||||
* Represents the DNS DS (Delegation Signer) getRecord type.
|
* Represents the DNS DS (Delegation Signer) record type.
|
||||||
*
|
*
|
||||||
* <p>The "DS" getRecord type is used in the DNSSEC (Domain Name System Security Extensions)
|
* <p>The "DS" record type is used in the DNSSEC (Domain Name System Security Extensions)
|
||||||
* protocol. It contains a hash of a DNSKEY getRecord which is utilized in establishing a chain of
|
* protocol. It contains a hash of a DNSKEY record which is utilized in establishing a chain of
|
||||||
* trust from a parent zone to a child zone.
|
* trust from a parent zone to a child zone.
|
||||||
*/
|
*/
|
||||||
DS("DS"),
|
DS("DS"),
|
||||||
/**
|
/**
|
||||||
* Represents the DNS HTTPS (HTTP Service) getRecord type.
|
* Represents the DNS HTTPS (HTTP Service) record type.
|
||||||
*
|
*
|
||||||
* <p>The "HTTPS" getRecord type is used to specify information about the HTTP/3 and related services
|
* <p>The "HTTPS" record type is used to specify information about the HTTP/3 and related services
|
||||||
* offered by a domain.
|
* offered by a domain.
|
||||||
*/
|
*/
|
||||||
HTTPS("HTTPS"),
|
HTTPS("HTTPS"),
|
||||||
/**
|
/**
|
||||||
* Represents the DNS LOC (Location) getRecord type.
|
* Represents the DNS LOC (Location) record type.
|
||||||
*
|
*
|
||||||
* <p>The "LOC" getRecord type is used to store geographical location information for a domain,
|
* <p>The "LOC" record type is used to store geographical location information for a domain,
|
||||||
* including latitude, longitude, altitude, and other details. It enables associating domains with
|
* including latitude, longitude, altitude, and other details. It enables associating domains with
|
||||||
* physical locations.
|
* physical locations.
|
||||||
*/
|
*/
|
||||||
LOC("LOC"),
|
LOC("LOC"),
|
||||||
/**
|
/**
|
||||||
* Represents the DNS MX (Mail Exchange) getRecord type.
|
* Represents the DNS MX (Mail Exchange) record type.
|
||||||
*
|
*
|
||||||
* <p>The "MX" getRecord type is used to specify the mail servers responsible for receiving email
|
* <p>The "MX" record type is used to specify the mail servers responsible for receiving email
|
||||||
* messages on behalf of a domain.
|
* messages on behalf of a domain.
|
||||||
*/
|
*/
|
||||||
MX("MX"),
|
MX("MX"),
|
||||||
/**
|
/**
|
||||||
* Represents the NAPTR getRecord type for DNS configurations.
|
* Represents the NAPTR record type for DNS configurations.
|
||||||
*
|
*
|
||||||
* <p>This constant is used to specify NAPTR (Naming Authority Pointer) DNS records, which allow
|
* <p>This constant is used to specify NAPTR (Naming Authority Pointer) DNS records, which allow
|
||||||
* for service discovery through flexible DNS-based mechanisms. NAPTR records are commonly used in
|
* for service discovery through flexible DNS-based mechanisms. NAPTR records are commonly used in
|
||||||
@@ -99,7 +99,7 @@ public enum RecordType {
|
|||||||
*/
|
*/
|
||||||
NS("NS"),
|
NS("NS"),
|
||||||
/**
|
/**
|
||||||
* Represents the "OPENPGPKEY" DNS getRecord type.
|
* Represents the "OPENPGPKEY" DNS record type.
|
||||||
*
|
*
|
||||||
* <p>This constant is primarily used to identify DNS records of the type "OPENPGPKEY". It may be
|
* <p>This constant is primarily used to identify DNS records of the type "OPENPGPKEY". It may be
|
||||||
* utilized within the system for operations such as creating, retrieving, updating, or managing
|
* utilized within the system for operations such as creating, retrieving, updating, or managing
|
||||||
@@ -107,17 +107,17 @@ public enum RecordType {
|
|||||||
*/
|
*/
|
||||||
OPENPGPKEY("OPENPGPKEY"),
|
OPENPGPKEY("OPENPGPKEY"),
|
||||||
/**
|
/**
|
||||||
* Represents a DNS getRecord type.
|
* Represents a DNS record type.
|
||||||
*
|
*
|
||||||
* <p>The `PTR` value specifically refers to a "pointer getRecord" in the DNS system, which is
|
* <p>The `PTR` value specifically refers to a "pointer record" in the DNS system, which is
|
||||||
* typically used for reverse DNS lookups.
|
* typically used for reverse DNS lookups.
|
||||||
*/
|
*/
|
||||||
PTR("PTR"),
|
PTR("PTR"),
|
||||||
/**
|
/**
|
||||||
* Represents the SMIMEA DNS getRecord type.
|
* Represents the SMIMEA DNS record type.
|
||||||
*
|
*
|
||||||
* <p>The SMIMEA resource getRecord is used to associate a user's certificate information for email
|
* <p>The SMIMEA resource record is used to associate a user's certificate information for email
|
||||||
* message signing or encryption. This type of DNS getRecord is part of the DNS-based Authentication
|
* message signing or encryption. This type of DNS record is part of the DNS-based Authentication
|
||||||
* of Named Entities (DANE) protocol.
|
* of Named Entities (DANE) protocol.
|
||||||
*
|
*
|
||||||
* <p>SMIMEA records provide a mechanism for utilizing certificates in email communication
|
* <p>SMIMEA records provide a mechanism for utilizing certificates in email communication
|
||||||
@@ -134,41 +134,41 @@ public enum RecordType {
|
|||||||
*/
|
*/
|
||||||
SMIMEA("SMIMEA"),
|
SMIMEA("SMIMEA"),
|
||||||
/**
|
/**
|
||||||
* Represents a service getRecord (SRV) type in the DNS configuration model.
|
* Represents a service record (SRV) type in the DNS configuration model.
|
||||||
*
|
*
|
||||||
* <p>This constant may be used to identify and work with SRV getRecord types in various DNS-related
|
* <p>This constant may be used to identify and work with SRV record types in various DNS-related
|
||||||
* operations or integrations.
|
* operations or integrations.
|
||||||
*/
|
*/
|
||||||
SRV("SRV"),
|
SRV("SRV"),
|
||||||
/**
|
/**
|
||||||
* Represents the DNS getRecord type "SSHFP" (SSH Fingerprint), used in DNS to store cryptographic
|
* Represents the DNS record type "SSHFP" (SSH Fingerprint), used in DNS to store cryptographic
|
||||||
* fingerprints associated with SSH host keys.
|
* fingerprints associated with SSH host keys.
|
||||||
*
|
*
|
||||||
* <p>This DNS getRecord type provides a mechanism for verifying the authenticity of an SSH server
|
* <p>This DNS record type provides a mechanism for verifying the authenticity of an SSH server
|
||||||
* before initiating a connection, enhancing the security of SSH communications.
|
* before initiating a connection, enhancing the security of SSH communications.
|
||||||
*/
|
*/
|
||||||
SSHFP("SSHFP"),
|
SSHFP("SSHFP"),
|
||||||
/**
|
/**
|
||||||
* Represents the Service Binding (SVCB) DNS getRecord type.
|
* Represents the Service Binding (SVCB) DNS record type.
|
||||||
*
|
*
|
||||||
* <p>The SVCB getRecord is a DNS resource getRecord used to indicate alternative endpoints or specific
|
* <p>The SVCB record is a DNS resource record used to indicate alternative endpoints or specific
|
||||||
* configuration details for services. It is commonly applied in service discovery and
|
* configuration details for services. It is commonly applied in service discovery and
|
||||||
* protocol-specific configurations.
|
* protocol-specific configurations.
|
||||||
*/
|
*/
|
||||||
SVCB("SVCB"),
|
SVCB("SVCB"),
|
||||||
/**
|
/**
|
||||||
* Represents a constant for the DNS-based Authentication of Named Entities (DANE) TLSA getRecord
|
* Represents a constant for the DNS-based Authentication of Named Entities (DANE) TLSA record
|
||||||
* type.
|
* type.
|
||||||
*
|
*
|
||||||
* <p>The TLSA getRecord is used to associate a TLS server certificate or public key with the domain
|
* <p>The TLSA record is used to associate a TLS server certificate or public key with the domain
|
||||||
* name (e.g., via DNSSEC). It enables cryptographically secured connections by attaching
|
* name (e.g., via DNSSEC). It enables cryptographically secured connections by attaching
|
||||||
* certificate and key constraints to the specific domain.
|
* certificate and key constraints to the specific domain.
|
||||||
*/
|
*/
|
||||||
TLSA("TLSA"),
|
TLSA("TLSA"),
|
||||||
/**
|
/**
|
||||||
* Represents the TXT DNS getRecord type.
|
* Represents the TXT DNS record type.
|
||||||
*
|
*
|
||||||
* <p>The TXT DNS getRecord type is commonly used to store text-based information for various
|
* <p>The TXT DNS record type is commonly used to store text-based information for various
|
||||||
* verification and configuration purposes, such as domain ownership verification or email
|
* verification and configuration purposes, such as domain ownership verification or email
|
||||||
* authentication protocols (e.g., SPF, DKIM).
|
* authentication protocols (e.g., SPF, DKIM).
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package codes.thischwa.cf.model;
|
package codes.thischwa.cf.model;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.Instant;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import lombok.Data;
|
import lombok.Data;
|
||||||
import lombok.EqualsAndHashCode;
|
import lombok.EqualsAndHashCode;
|
||||||
@@ -15,7 +15,7 @@ import lombok.EqualsAndHashCode;
|
|||||||
* <li>Zone name.
|
* <li>Zone name.
|
||||||
* <li>Development mode status.
|
* <li>Development mode status.
|
||||||
* <li>Active and original name servers linked to the zone.
|
* <li>Active and original name servers linked to the zone.
|
||||||
* <li>Timestamps indicating when the zone was created, modified, or activated.
|
* <li>Timestamps (UTC) indicating when the zone was created, modified, or activated.
|
||||||
* <li>Current operational status of the zone (e.g., active, inactive).
|
* <li>Current operational status of the zone (e.g., active, inactive).
|
||||||
* <li>Boolean flag indicating whether the zone is paused.
|
* <li>Boolean flag indicating whether the zone is paused.
|
||||||
* <li>Zone type, representing the nature of the DNS zone (e.g., full, partial).
|
* <li>Zone type, representing the nature of the DNS zone (e.g., full, partial).
|
||||||
@@ -31,9 +31,9 @@ public class ZoneEntity extends AbstractEntity {
|
|||||||
private Integer developmentMode;
|
private Integer developmentMode;
|
||||||
private Set<String> nameServers;
|
private Set<String> nameServers;
|
||||||
private Set<String> originalNameServers;
|
private Set<String> originalNameServers;
|
||||||
private LocalDateTime createdOn;
|
private Instant createdOn;
|
||||||
private LocalDateTime modifiedOn;
|
private Instant modifiedOn;
|
||||||
private LocalDateTime activatedOn;
|
private Instant activatedOn;
|
||||||
private String status;
|
private String status;
|
||||||
private Boolean paused;
|
private Boolean paused;
|
||||||
private String type;
|
private String type;
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
package codes.thischwa.cf;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import codes.thischwa.cf.model.ZoneEntity;
|
||||||
|
import com.sun.net.httpserver.HttpServer;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests the error handling of {@link CfBasicHttpClient} against a local HTTP server.
|
||||||
|
*/
|
||||||
|
class CfBasicHttpClientErrorTest {
|
||||||
|
|
||||||
|
private static final String ZONE_JSON = """
|
||||||
|
{"success":true,"errors":[],"messages":[],
|
||||||
|
"result_info":{"page":1,"per_page":50,"total_pages":1,"count":1,"total_count":1},
|
||||||
|
"result":[{"id":"zone1","name":"example.com","created_on":"2025-01-20T08:56:34.736214Z"}]}
|
||||||
|
""";
|
||||||
|
|
||||||
|
private HttpServer server;
|
||||||
|
private CfDnsClient client;
|
||||||
|
private final AtomicInteger requestCount = new AtomicInteger();
|
||||||
|
private volatile int status;
|
||||||
|
private volatile String body;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws IOException {
|
||||||
|
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
|
||||||
|
server.createContext("/", exchange -> {
|
||||||
|
requestCount.incrementAndGet();
|
||||||
|
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||||
|
exchange.sendResponseHeaders(status, bytes.length);
|
||||||
|
try (OutputStream out = exchange.getResponseBody()) {
|
||||||
|
out.write(bytes);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
server.start();
|
||||||
|
client = new CfDnsClientBuilder()
|
||||||
|
.withApiTokenAuth("test-token")
|
||||||
|
.withBaseUrl("http://localhost:" + server.getAddress().getPort())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() throws IOException {
|
||||||
|
client.close();
|
||||||
|
server.stop(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void respond(int status, String body) {
|
||||||
|
this.status = status;
|
||||||
|
this.body = body;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void apiErrorContainsStatusCodeAndErrors() {
|
||||||
|
respond(400, """
|
||||||
|
{"success":false,"errors":[{"code":1004,"message":"DNS Validation Error"}],"messages":[],"result":null}
|
||||||
|
""");
|
||||||
|
|
||||||
|
CloudflareApiException e = assertThrows(CloudflareApiException.class, () -> client.zoneList());
|
||||||
|
|
||||||
|
assertEquals(CloudflareApiException.class, e.getClass());
|
||||||
|
assertEquals(400, e.getStatusCode());
|
||||||
|
assertEquals(1, e.getErrors().size());
|
||||||
|
assertEquals(1004, e.getErrors().get(0).getCode());
|
||||||
|
assertTrue(e.getMessage().contains("DNS Validation Error"), e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void status404ThrowsNotFound() {
|
||||||
|
respond(404, """
|
||||||
|
{"success":false,"errors":[{"code":81044,"message":"Record does not exist."}],"messages":[],"result":null}
|
||||||
|
""");
|
||||||
|
ZoneEntity zone = new ZoneEntity();
|
||||||
|
zone.setId("zone1");
|
||||||
|
zone.setName("example.com");
|
||||||
|
|
||||||
|
CloudflareApiException e = assertThrows(CloudflareApiException.class,
|
||||||
|
() -> client.recordDelete(zone, "0123456789abcdef0123456789abcdef"));
|
||||||
|
|
||||||
|
assertInstanceOf(CloudflareNotFoundException.class, e);
|
||||||
|
assertEquals(404, e.getStatusCode());
|
||||||
|
assertEquals(81044, e.getErrors().get(0).getCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nonJsonErrorResponseKeepsStatusCode() {
|
||||||
|
respond(502, "<html><body>Bad Gateway</body></html>");
|
||||||
|
|
||||||
|
CloudflareApiException e = assertThrows(CloudflareApiException.class, () -> client.zoneList());
|
||||||
|
|
||||||
|
assertEquals(502, e.getStatusCode());
|
||||||
|
assertTrue(e.getErrors().isEmpty());
|
||||||
|
assertTrue(e.getMessage().contains("502"), e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void successWithTimestampsAndReusedClient() throws CloudflareApiException {
|
||||||
|
respond(200, ZONE_JSON);
|
||||||
|
|
||||||
|
ZoneEntity zone = client.zoneGet("example.com");
|
||||||
|
assertNotNull(zone);
|
||||||
|
assertEquals("2025-01-20T08:56:34.736214Z", zone.getCreatedOn().toString());
|
||||||
|
|
||||||
|
// the same client instance can be used for multiple requests
|
||||||
|
assertEquals(1, client.zoneList().size());
|
||||||
|
assertEquals(2, requestCount.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void exceptionWithoutResponseHasNoStatusCode() {
|
||||||
|
CloudflareApiException e = new CloudflareApiException("test");
|
||||||
|
assertEquals(CloudflareApiException.NO_STATUS_CODE, e.getStatusCode());
|
||||||
|
assertTrue(e.getErrors().isEmpty());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
package codes.thischwa.cf;
|
package codes.thischwa.cf;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
@@ -79,10 +79,10 @@ class CfBasicHttpClientTest {
|
|||||||
});
|
});
|
||||||
|
|
||||||
assertNotNull(exception);
|
assertNotNull(exception);
|
||||||
assertTrue(exception.getMessage().contains("Unexpected error"));
|
// the API error must not be wrapped into a generic "Unexpected error"
|
||||||
Throwable cause = exception.getCause();
|
assertTrue(exception.getMessage().contains("No route for that URI"),
|
||||||
assertInstanceOf(CloudflareApiException.class, cause);
|
"Expected error message: No route for that URI, but it was: " + exception.getMessage());
|
||||||
assertTrue(cause.getMessage().contains("No route for that URI"), "Expected error message: No route for that URI, but it was: " + cause.getMessage());
|
assertNull(exception.getCause());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -56,17 +56,17 @@ public class CfClientPenTest {
|
|||||||
"doesnotexist", "abcdef12345", "unwahrscheinlich-" + System.currentTimeMillis());
|
"doesnotexist", "abcdef12345", "unwahrscheinlich-" + System.currentTimeMillis());
|
||||||
|
|
||||||
for (String sld : syntacticallyInvalidSlds) {
|
for (String sld : syntacticallyInvalidSlds) {
|
||||||
assertThrows(IllegalArgumentException.class, () -> client.recordList(zone, sld),
|
assertThrows(IllegalArgumentException.class, () -> client.recordListBySubdomain(zone, sld),
|
||||||
"Should throw IllegalArgumentException for invalid SLD '" + sld + "'");
|
"Should throw IllegalArgumentException for invalid SLD '" + sld + "'");
|
||||||
}
|
}
|
||||||
for (String sld : syntacticallyValidOrNotAllowedFromCloudflare) {
|
for (String sld : syntacticallyValidOrNotAllowedFromCloudflare) {
|
||||||
assertThrows(CloudflareNotFoundException.class, () -> client.recordList(zone, sld),
|
assertThrows(CloudflareNotFoundException.class, () -> client.recordListBySubdomain(zone, sld),
|
||||||
"Should throw CloudflareNotFoundException for valid but non-existing SLD '" + sld + "'");
|
"Should throw CloudflareNotFoundException for valid but non-existing SLD '" + sld + "'");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Invalid getRecord content and TTL boundaries must be rejected by API")
|
@DisplayName("Invalid record content and TTL boundaries must be rejected by API")
|
||||||
void testInvalidRecordCreateInputsRejected() throws Exception {
|
void testInvalidRecordCreateInputsRejected() throws Exception {
|
||||||
CfDnsClient client = newClient();
|
CfDnsClient client = newClient();
|
||||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||||
@@ -81,11 +81,11 @@ public class CfClientPenTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// A getRecord with invalid IPv4
|
// A record with invalid IPv4
|
||||||
assertThrows(CloudflareApiException.class,
|
assertThrows(CloudflareApiException.class,
|
||||||
() -> client.recordCreate(zone, fqdn, 60, RecordType.A, "999.999.999.999"));
|
() -> client.recordCreate(zone, fqdn, 60, RecordType.A, "999.999.999.999"));
|
||||||
|
|
||||||
// AAAA getRecord with non-IP content
|
// AAAA record with non-IP content
|
||||||
assertThrows(CloudflareApiException.class,
|
assertThrows(CloudflareApiException.class,
|
||||||
() -> client.recordCreate(zone, fqdn, 60, RecordType.AAAA, "not-an-ipv6"));
|
() -> client.recordCreate(zone, fqdn, 60, RecordType.AAAA, "not-an-ipv6"));
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
package codes.thischwa.cf;
|
package codes.thischwa.cf;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.junit.jupiter.api.Assertions.fail;
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
@@ -13,6 +16,7 @@ import codes.thischwa.cf.model.PagingRequest;
|
|||||||
import codes.thischwa.cf.model.RecordEntity;
|
import codes.thischwa.cf.model.RecordEntity;
|
||||||
import codes.thischwa.cf.model.RecordType;
|
import codes.thischwa.cf.model.RecordType;
|
||||||
import codes.thischwa.cf.model.ZoneEntity;
|
import codes.thischwa.cf.model.ZoneEntity;
|
||||||
|
import java.time.Instant;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
@@ -36,6 +40,9 @@ public class CfClientTest {
|
|||||||
|
|
||||||
private final CfDnsClient client = new CfDnsClientBuilder().withEmptyResultThrowsException(true).withApiTokenAuth(API_TOKEN).build();
|
private final CfDnsClient client = new CfDnsClientBuilder().withEmptyResultThrowsException(true).withApiTokenAuth(API_TOKEN).build();
|
||||||
|
|
||||||
|
private static final String IP_PREFIX = "130.0.0.";
|
||||||
|
private static final String UPDATED_IP_PREFIX = "130.1.0.";
|
||||||
|
|
||||||
@BeforeAll
|
@BeforeAll
|
||||||
static void checkEnv() {
|
static void checkEnv() {
|
||||||
assumeTrue(API_TOKEN != null && !API_TOKEN.isBlank(), "API_TOKEN not set; skipping client tests");
|
assumeTrue(API_TOKEN != null && !API_TOKEN.isBlank(), "API_TOKEN not set; skipping client tests");
|
||||||
@@ -44,7 +51,7 @@ public class CfClientTest {
|
|||||||
@Test
|
@Test
|
||||||
void testUnknownSld() throws Exception {
|
void testUnknownSld() throws Exception {
|
||||||
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||||
assertThrows(CloudflareNotFoundException.class, () -> client.recordList(zone, "unknown", RecordType.A));
|
assertThrows(CloudflareNotFoundException.class, () -> client.recordListBySubdomain(zone, "unknown", RecordType.A));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -58,13 +65,13 @@ public class CfClientTest {
|
|||||||
RecordEntity record = RecordEntity.build(SLD_STR, RecordType.A, TTL, "127.0.0.1");
|
RecordEntity record = RecordEntity.build(SLD_STR, RecordType.A, TTL, "127.0.0.1");
|
||||||
RecordEntity createdRecord = client.recordCreate(zone, record);
|
RecordEntity createdRecord = client.recordCreate(zone, record);
|
||||||
assertNotNull(createdRecord.getId());
|
assertNotNull(createdRecord.getId());
|
||||||
assertEquals(SLD_STR, createdRecord.getSld());
|
assertEquals(SLD_STR, createdRecord.getSubdomain());
|
||||||
assertEquals(RecordType.A.getType(), createdRecord.getType());
|
assertEquals(RecordType.A.getType(), createdRecord.getType());
|
||||||
assertEquals(TTL, createdRecord.getTtl());
|
assertEquals(TTL, createdRecord.getTtl());
|
||||||
assertEquals("127.0.0.1", createdRecord.getContent());
|
assertEquals("127.0.0.1", createdRecord.getContent());
|
||||||
assertNotNull(createdRecord.getCreatedOn());
|
assertNotNull(createdRecord.getCreatedOn());
|
||||||
|
|
||||||
List<RecordEntity> records = client.recordList(zone, SLD_STR, RecordType.A);
|
List<RecordEntity> records = client.recordListBySubdomain(zone, SLD_STR, RecordType.A);
|
||||||
assertEquals(1, records.size());
|
assertEquals(1, records.size());
|
||||||
RecordEntity fetchedRecord = records.get(0);
|
RecordEntity fetchedRecord = records.get(0);
|
||||||
assertEquals(createdRecord.getId(), fetchedRecord.getId());
|
assertEquals(createdRecord.getId(), fetchedRecord.getId());
|
||||||
@@ -79,14 +86,14 @@ public class CfClientTest {
|
|||||||
RecordEntity createdRecordAAAA = client.recordCreate(zone, recordAAAA);
|
RecordEntity createdRecordAAAA = client.recordCreate(zone, recordAAAA);
|
||||||
assertNotNull(createdRecordA.getId());
|
assertNotNull(createdRecordA.getId());
|
||||||
assertNotNull(createdRecordAAAA.getId());
|
assertNotNull(createdRecordAAAA.getId());
|
||||||
assertEquals(SLD_STR, createdRecordA.getSld());
|
assertEquals(SLD_STR, createdRecordA.getSubdomain());
|
||||||
assertEquals(SLD_STR, createdRecordAAAA.getSld());
|
assertEquals(SLD_STR, createdRecordAAAA.getSubdomain());
|
||||||
assertEquals(RecordType.A.getType(), createdRecordA.getType());
|
assertEquals(RecordType.A.getType(), createdRecordA.getType());
|
||||||
assertEquals(RecordType.AAAA.getType(), createdRecordAAAA.getType());
|
assertEquals(RecordType.AAAA.getType(), createdRecordAAAA.getType());
|
||||||
|
|
||||||
client.recordDeleteTypeIfExists(zone, SLD_STR, RecordType.A, RecordType.AAAA);
|
client.recordDeleteTypeIfExists(zone, SLD_STR, RecordType.A, RecordType.AAAA);
|
||||||
assertThrows(CloudflareNotFoundException.class,
|
assertThrows(CloudflareNotFoundException.class,
|
||||||
() -> client.recordList(zone, SLD_STR, RecordType.A, RecordType.AAAA));
|
() -> client.recordListBySubdomain(zone, SLD_STR, RecordType.A, RecordType.AAAA));
|
||||||
} finally {
|
} finally {
|
||||||
// cleanup in case of failures during test
|
// cleanup in case of failures during test
|
||||||
try {
|
try {
|
||||||
@@ -114,7 +121,7 @@ public class CfClientTest {
|
|||||||
assertEquals(1, zList.size());
|
assertEquals(1, zList.size());
|
||||||
|
|
||||||
assertThrows(CloudflareNotFoundException.class,
|
assertThrows(CloudflareNotFoundException.class,
|
||||||
() -> client.recordList(zList.get(0), "not-existing"));
|
() -> client.recordListBySubdomain(zList.get(0), "not-existing"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -144,12 +151,12 @@ public class CfClientTest {
|
|||||||
// ensure clean state
|
// ensure clean state
|
||||||
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A, RecordType.AAAA);
|
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A, RecordType.AAAA);
|
||||||
|
|
||||||
// create A getRecord using recordCreate with full domain
|
// create A record using recordCreate with full domain
|
||||||
createdRe1 =
|
createdRe1 =
|
||||||
client.recordCreate(z, RecordEntity.build(domain, RecordType.A, TTL, "130.0.0.3"));
|
client.recordCreate(z, RecordEntity.build(domain, RecordType.A, TTL, "130.0.0.3"));
|
||||||
assertNotNull(createdRe1.getId());
|
assertNotNull(createdRe1.getId());
|
||||||
assertEquals(randomSld + "." + ZONE_STR, createdRe1.getName());
|
assertEquals(randomSld + "." + ZONE_STR, createdRe1.getName());
|
||||||
assertEquals(randomSld, createdRe1.getSld());
|
assertEquals(randomSld, createdRe1.getSubdomain());
|
||||||
assertEquals(RecordType.A.getType(), createdRe1.getType());
|
assertEquals(RecordType.A.getType(), createdRe1.getType());
|
||||||
assertEquals(z.getId(), createdRe1.getZoneId());
|
assertEquals(z.getId(), createdRe1.getZoneId());
|
||||||
assertEquals(TTL, createdRe1.getTtl());
|
assertEquals(TTL, createdRe1.getTtl());
|
||||||
@@ -158,15 +165,15 @@ public class CfClientTest {
|
|||||||
assertNotNull(createdRe1.getModifiedOn());
|
assertNotNull(createdRe1.getModifiedOn());
|
||||||
|
|
||||||
// verify recordList for A
|
// verify recordList for A
|
||||||
List<RecordEntity> aRecords = client.recordList(z, randomSld, RecordType.A);
|
List<RecordEntity> aRecords = client.recordListBySubdomain(z, randomSld, RecordType.A);
|
||||||
assertEquals(1, aRecords.size());
|
assertEquals(1, aRecords.size());
|
||||||
r = aRecords.get(0);
|
r = aRecords.get(0);
|
||||||
assertEquals("130.0.0.3", r.getContent());
|
assertEquals("130.0.0.3", r.getContent());
|
||||||
|
|
||||||
// create AAAA getRecord using recordCreateSld
|
// create AAAA record using recordCreateSubdomain
|
||||||
createdRe2 =
|
createdRe2 =
|
||||||
client.recordCreateSld(z, randomSld, TTL, RecordType.AAAA, "2a0a:4cc0:c0:2e4::1");
|
client.recordCreateSubdomain(z, randomSld, TTL, RecordType.AAAA, "2a0a:4cc0:c0:2e4::1");
|
||||||
List<RecordEntity> aaaaRecords = client.recordList(z, randomSld, RecordType.AAAA);
|
List<RecordEntity> aaaaRecords = client.recordListBySubdomain(z, randomSld, RecordType.AAAA);
|
||||||
assertEquals(1, aaaaRecords.size());
|
assertEquals(1, aaaaRecords.size());
|
||||||
r = aaaaRecords.get(0);
|
r = aaaaRecords.get(0);
|
||||||
assertEquals(z.getId(), r.getZoneId());
|
assertEquals(z.getId(), r.getZoneId());
|
||||||
@@ -174,7 +181,7 @@ public class CfClientTest {
|
|||||||
assertEquals(RecordType.AAAA.getType(), r.getType());
|
assertEquals(RecordType.AAAA.getType(), r.getType());
|
||||||
|
|
||||||
// test recordList
|
// test recordList
|
||||||
List<RecordEntity> rList = client.recordList(z, randomSld);
|
List<RecordEntity> rList = client.recordListBySubdomain(z, randomSld);
|
||||||
assertEquals(2, rList.size());
|
assertEquals(2, rList.size());
|
||||||
for (RecordEntity re : rList) {
|
for (RecordEntity re : rList) {
|
||||||
assertEquals(z.getId(), re.getZoneId());
|
assertEquals(z.getId(), re.getZoneId());
|
||||||
@@ -183,7 +190,7 @@ public class CfClientTest {
|
|||||||
} else if (Objects.equals(re.getType(), RecordType.AAAA.getType())) {
|
} else if (Objects.equals(re.getType(), RecordType.AAAA.getType())) {
|
||||||
assertEquals("2a0a:4cc0:c0:2e4::1", re.getContent());
|
assertEquals("2a0a:4cc0:c0:2e4::1", re.getContent());
|
||||||
} else {
|
} else {
|
||||||
fail(String.format("Unexpected getRecord type: %s", re.getType()));
|
fail(String.format("Unexpected record type: %s", re.getType()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,7 +203,7 @@ public class CfClientTest {
|
|||||||
fullList.stream().allMatch(re -> re.getType().equals(RecordType.A.getType()) || re.getType().equals(RecordType.AAAA.getType())));
|
fullList.stream().allMatch(re -> re.getType().equals(RecordType.A.getType()) || re.getType().equals(RecordType.AAAA.getType())));
|
||||||
|
|
||||||
// test recordList with types without SLD
|
// test recordList with types without SLD
|
||||||
List<RecordEntity> aList = client.recordList(z, RecordType.A);
|
List<RecordEntity> aList = client.recordListByType(z, RecordType.A);
|
||||||
assertFalse(aList.isEmpty());
|
assertFalse(aList.isEmpty());
|
||||||
assertTrue(aList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
assertTrue(aList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||||
assertTrue(aList.stream().noneMatch(re -> re.getId().equals(createdRe2.getId())));
|
assertTrue(aList.stream().noneMatch(re -> re.getId().equals(createdRe2.getId())));
|
||||||
@@ -207,29 +214,34 @@ public class CfClientTest {
|
|||||||
assertFalse(fluentList.isEmpty());
|
assertFalse(fluentList.isEmpty());
|
||||||
assertTrue(fluentList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
assertTrue(fluentList.stream().anyMatch(re -> re.getId().equals(createdRe1.getId())));
|
||||||
|
|
||||||
// update AAAA getRecord
|
// update AAAA record, the given record (incl. its timestamps) must not be modified
|
||||||
createdRe2.setContent("2a0a:4cc0:c0:2e4::2");
|
createdRe2.setContent("2a0a:4cc0:c0:2e4::2");
|
||||||
client.recordUpdate(z, createdRe2);
|
Instant createdOn = createdRe2.getCreatedOn();
|
||||||
aaaaRecords = client.recordList(z, randomSld, RecordType.AAAA);
|
RecordEntity updatedRe2 = client.recordUpdate(z, createdRe2);
|
||||||
|
assertEquals(createdOn, createdRe2.getCreatedOn());
|
||||||
|
assertNotNull(createdRe2.getModifiedOn());
|
||||||
|
assertEquals("2a0a:4cc0:c0:2e4::2", updatedRe2.getContent());
|
||||||
|
assertEquals(z.getId(), updatedRe2.getZoneId());
|
||||||
|
aaaaRecords = client.recordListBySubdomain(z, randomSld, RecordType.AAAA);
|
||||||
assertEquals(1, aaaaRecords.size());
|
assertEquals(1, aaaaRecords.size());
|
||||||
r = aaaaRecords.get(0);
|
r = aaaaRecords.get(0);
|
||||||
assertEquals("2a0a:4cc0:c0:2e4::2", r.getContent());
|
assertEquals("2a0a:4cc0:c0:2e4::2", r.getContent());
|
||||||
|
|
||||||
// verify A getRecord still intact
|
// verify A record still intact
|
||||||
aRecords = client.recordList(z, randomSld, RecordType.A);
|
aRecords = client.recordListBySubdomain(z, randomSld, RecordType.A);
|
||||||
assertEquals(1, aRecords.size());
|
assertEquals(1, aRecords.size());
|
||||||
r = aRecords.get(0);
|
r = aRecords.get(0);
|
||||||
assertEquals("130.0.0.3", r.getContent());
|
assertEquals("130.0.0.3", r.getContent());
|
||||||
|
|
||||||
// delete AAAA getRecord and verify it's gone
|
// delete AAAA record and verify it's gone
|
||||||
assertTrue(client.recordDelete(z, createdRe2));
|
assertTrue(client.recordDelete(z, createdRe2));
|
||||||
assertThrows(CloudflareNotFoundException.class,
|
assertThrows(CloudflareNotFoundException.class,
|
||||||
() -> client.recordList(z, randomSld, RecordType.AAAA));
|
() -> client.recordListBySubdomain(z, randomSld, RecordType.AAAA));
|
||||||
|
|
||||||
// delete A getRecord using helper and verify it's gone
|
// delete A record using helper and verify it's gone
|
||||||
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A);
|
client.recordDeleteTypeIfExists(z, randomSld, RecordType.A);
|
||||||
assertThrows(CloudflareNotFoundException.class,
|
assertThrows(CloudflareNotFoundException.class,
|
||||||
() -> client.recordList(z, randomSld, RecordType.A));
|
() -> client.recordListBySubdomain(z, randomSld, RecordType.A));
|
||||||
} finally {
|
} finally {
|
||||||
// cleanup in case of failures during test
|
// cleanup in case of failures during test
|
||||||
try {
|
try {
|
||||||
@@ -242,14 +254,10 @@ public class CfClientTest {
|
|||||||
void testRecordEntityInvalidType() {
|
void testRecordEntityInvalidType() {
|
||||||
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
|
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
|
||||||
() -> RecordEntity.build("id123", "example.com", "INVALID_TYPE", 60, "192.168.1.1"));
|
() -> RecordEntity.build("id123", "example.com", "INVALID_TYPE", 60, "192.168.1.1"));
|
||||||
assertTrue(exception.getMessage().contains("Invalid getRecord type: INVALID_TYPE"));
|
assertTrue(exception.getMessage().contains("Invalid record type: INVALID_TYPE"));
|
||||||
assertTrue(exception.getMessage().contains("Must be one of:"));
|
assertTrue(exception.getMessage().contains("Must be one of:"));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static final String IP_PREFIX = "130.0.0.";
|
|
||||||
private static final String UPDATED_IP_PREFIX = "130.1.0.";
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testBatch() throws Exception {
|
void testBatch() throws Exception {
|
||||||
// starting point: already existing zone 'mein-d-ns.de'
|
// starting point: already existing zone 'mein-d-ns.de'
|
||||||
@@ -303,7 +311,7 @@ public class CfClientTest {
|
|||||||
|
|
||||||
// Verify only the first 2 records
|
// Verify only the first 2 records
|
||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
List<RecordEntity> records1 = client.recordList(zone, sldNames.get(i), RecordType.A);
|
List<RecordEntity> records1 = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||||
assertEquals(1, records1.size());
|
assertEquals(1, records1.size());
|
||||||
assertEquals(IP_PREFIX + (i + 1), records1.get(0).getContent());
|
assertEquals(IP_PREFIX + (i + 1), records1.get(0).getContent());
|
||||||
}
|
}
|
||||||
@@ -313,7 +321,7 @@ public class CfClientTest {
|
|||||||
// Use first 2 records for PATCH
|
// Use first 2 records for PATCH
|
||||||
List<RecordEntity> patchRecords = new ArrayList<>();
|
List<RecordEntity> patchRecords = new ArrayList<>();
|
||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
List<RecordEntity> records = client.recordList(zone, sldNames.get(i), RecordType.A);
|
List<RecordEntity> records = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||||
RecordEntity record = records.get(0);
|
RecordEntity record = records.get(0);
|
||||||
record.setContent(UPDATED_IP_PREFIX + (i + 1));
|
record.setContent(UPDATED_IP_PREFIX + (i + 1));
|
||||||
patchRecords.add(record);
|
patchRecords.add(record);
|
||||||
@@ -323,7 +331,7 @@ public class CfClientTest {
|
|||||||
|
|
||||||
// Verify both records were updated
|
// Verify both records were updated
|
||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
List<RecordEntity> updatedRecords = client.recordList(zone, sldNames.get(i), RecordType.A);
|
List<RecordEntity> updatedRecords = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||||
assertEquals(1, updatedRecords.size());
|
assertEquals(1, updatedRecords.size());
|
||||||
assertEquals(UPDATED_IP_PREFIX + (i + 1), updatedRecords.get(0).getContent());
|
assertEquals(UPDATED_IP_PREFIX + (i + 1), updatedRecords.get(0).getContent());
|
||||||
}
|
}
|
||||||
@@ -333,7 +341,7 @@ public class CfClientTest {
|
|||||||
// Delete first 2 records
|
// Delete first 2 records
|
||||||
List<RecordEntity> deleteRecords = new ArrayList<>();
|
List<RecordEntity> deleteRecords = new ArrayList<>();
|
||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
List<RecordEntity> records = client.recordList(zone, sldNames.get(i), RecordType.A);
|
List<RecordEntity> records = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||||
deleteRecords.add(records.get(0));
|
deleteRecords.add(records.get(0));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -343,7 +351,7 @@ public class CfClientTest {
|
|||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
String sldName = sldNames.get(i);
|
String sldName = sldNames.get(i);
|
||||||
assertThrows(CloudflareNotFoundException.class,
|
assertThrows(CloudflareNotFoundException.class,
|
||||||
() -> client.recordList(zone, sldName, RecordType.A));
|
() -> client.recordListBySubdomain(zone, sldName, RecordType.A));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -359,7 +367,7 @@ public class CfClientTest {
|
|||||||
// Now use PUT to replace them
|
// Now use PUT to replace them
|
||||||
List<RecordEntity> putRecords = new ArrayList<>();
|
List<RecordEntity> putRecords = new ArrayList<>();
|
||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
List<RecordEntity> records = client.recordList(zone, sldNames.get(i), RecordType.A);
|
List<RecordEntity> records = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||||
RecordEntity record = records.get(0);
|
RecordEntity record = records.get(0);
|
||||||
record.setContent(UPDATED_IP_PREFIX + (i + 1));
|
record.setContent(UPDATED_IP_PREFIX + (i + 1));
|
||||||
putRecords.add(record);
|
putRecords.add(record);
|
||||||
@@ -368,7 +376,7 @@ public class CfClientTest {
|
|||||||
|
|
||||||
// Verify both records were updated
|
// Verify both records were updated
|
||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
List<RecordEntity> updatedRecords = client.recordList(zone, sldNames.get(i), RecordType.A);
|
List<RecordEntity> updatedRecords = client.recordListBySubdomain(zone, sldNames.get(i), RecordType.A);
|
||||||
assertEquals(1, updatedRecords.size());
|
assertEquals(1, updatedRecords.size());
|
||||||
assertEquals(UPDATED_IP_PREFIX + (i + 1), updatedRecords.get(0).getContent());
|
assertEquals(UPDATED_IP_PREFIX + (i + 1), updatedRecords.get(0).getContent());
|
||||||
}
|
}
|
||||||
@@ -376,7 +384,7 @@ public class CfClientTest {
|
|||||||
|
|
||||||
private void assertValidBatchedRecord(RecordEntity batchedRecord, RecordEntity originalRecord) {
|
private void assertValidBatchedRecord(RecordEntity batchedRecord, RecordEntity originalRecord) {
|
||||||
assertNotNull(batchedRecord.getId());
|
assertNotNull(batchedRecord.getId());
|
||||||
assertEquals(originalRecord.getSld(), batchedRecord.getSld());
|
assertEquals(originalRecord.getSubdomain(), batchedRecord.getSubdomain());
|
||||||
assertEquals(originalRecord.getType(), batchedRecord.getType());
|
assertEquals(originalRecord.getType(), batchedRecord.getType());
|
||||||
assertNotNull(batchedRecord.getCreatedOn());
|
assertNotNull(batchedRecord.getCreatedOn());
|
||||||
}
|
}
|
||||||
@@ -393,7 +401,7 @@ public class CfClientTest {
|
|||||||
.create(RecordType.A, "192.168.100.1", TTL);
|
.create(RecordType.A, "192.168.100.1", TTL);
|
||||||
|
|
||||||
assertNotNull(created.getId());
|
assertNotNull(created.getId());
|
||||||
assertEquals(fluentSld, created.getSld());
|
assertEquals(fluentSld, created.getSubdomain());
|
||||||
assertEquals("192.168.100.1", created.getContent());
|
assertEquals("192.168.100.1", created.getContent());
|
||||||
|
|
||||||
// Test fluent get
|
// Test fluent get
|
||||||
@@ -441,7 +449,7 @@ public class CfClientTest {
|
|||||||
assertNotNull(groupedRecords, "Resulting map should not be null.");
|
assertNotNull(groupedRecords, "Resulting map should not be null.");
|
||||||
assertEquals(2, groupedRecords.size(), "The grouping should result in 2 FQDN keys.");
|
assertEquals(2, groupedRecords.size(), "The grouping should result in 2 FQDN keys.");
|
||||||
assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records.");
|
assertEquals(2, groupedRecords.get("example.com.").size(), "The key 'example.com.' should have 2 records.");
|
||||||
assertEquals(1, groupedRecords.get("sub.example.com.").size(), "The key 'sub.example.com.' should have 1 getRecord.");
|
assertEquals(1, groupedRecords.get("sub.example.com.").size(), "The key 'sub.example.com.' should have 1 record.");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -518,6 +526,15 @@ public class CfClientTest {
|
|||||||
Set<String> allRecordIds = allRecords.stream().map(RecordEntity::getId).collect(Collectors.toSet());
|
Set<String> allRecordIds = allRecords.stream().map(RecordEntity::getId).collect(Collectors.toSet());
|
||||||
assertEquals(createdRecords.size(), allRecordIds.size());
|
assertEquals(createdRecords.size(), allRecordIds.size());
|
||||||
assertTrue(allRecordIds.containsAll(generatedRecordIds));
|
assertTrue(allRecordIds.containsAll(generatedRecordIds));
|
||||||
|
|
||||||
|
// Without PagingRequest all pages must be fetched, also if the page size is small
|
||||||
|
try (CfDnsClient smallPageClient = new CfDnsClient(true, CfDnsClientBuilder.DEFAULT_BASEURL,
|
||||||
|
new CfDnsClientBuilder.ApiTokenAuth(API_TOKEN), 5)) {
|
||||||
|
assertEquals(allRecordIds, smallPageClient.recordList(zone).stream()
|
||||||
|
.map(RecordEntity::getId).collect(Collectors.toSet()));
|
||||||
|
assertEquals(createdRecords.size(), smallPageClient.recordListBySubdomain(zone, pagingSld).size());
|
||||||
|
assertEquals(createdRecords.size(), smallPageClient.recordListByType(zone, RecordType.A).size());
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
try {
|
try {
|
||||||
client.recordDeleteTypeIfExists(zone, pagingSld, RecordType.A);
|
client.recordDeleteTypeIfExists(zone, pagingSld, RecordType.A);
|
||||||
@@ -525,4 +542,186 @@ public class CfClientTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testApiErrorDetails() throws Exception {
|
||||||
|
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||||
|
String sub = "invalid-" + System.currentTimeMillis();
|
||||||
|
try {
|
||||||
|
// an A record with an invalid IP is rejected by Cloudflare
|
||||||
|
CloudflareApiException e = assertThrows(CloudflareApiException.class,
|
||||||
|
() -> client.recordCreateSubdomain(zone, sub, TTL, RecordType.A, "not-an-ip"));
|
||||||
|
assertEquals(CloudflareApiException.class, e.getClass());
|
||||||
|
assertEquals(400, e.getStatusCode());
|
||||||
|
assertFalse(e.getErrors().isEmpty());
|
||||||
|
assertTrue(e.getErrors().get(0).getCode() > 0);
|
||||||
|
// the Cloudflare error message is part of the exception message, not wrapped
|
||||||
|
assertTrue(e.getMessage().contains(e.getErrors().get(0).getMessage()), e.getMessage());
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
client.recordDeleteTypeIfExists(zone, sub, RecordType.A);
|
||||||
|
} catch (Exception e) { /* ignore */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordDeleteUnknownId() throws Exception {
|
||||||
|
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||||
|
CloudflareApiException e = assertThrows(CloudflareApiException.class,
|
||||||
|
() -> client.recordDelete(zone, "0123456789abcdef0123456789abcdef"));
|
||||||
|
assertInstanceOf(CloudflareNotFoundException.class, e);
|
||||||
|
assertEquals(404, e.getStatusCode());
|
||||||
|
assertFalse(e.getErrors().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testZoneNotFound() throws Exception {
|
||||||
|
String unknownZone = "not-existing-" + System.currentTimeMillis() + ".de";
|
||||||
|
// emptyResultThrowsException = true
|
||||||
|
assertThrows(CloudflareNotFoundException.class, () -> client.zoneGet(unknownZone));
|
||||||
|
assertThrows(CloudflareNotFoundException.class, () -> client.zone(unknownZone));
|
||||||
|
|
||||||
|
// emptyResultThrowsException = false
|
||||||
|
try (CfDnsClient lenientClient = new CfDnsClientBuilder().withApiTokenAuth(API_TOKEN).build()) {
|
||||||
|
assertNull(lenientClient.zoneGet(unknownZone));
|
||||||
|
assertThrows(CloudflareNotFoundException.class, () -> lenientClient.zone(unknownZone));
|
||||||
|
assertNotNull(lenientClient.zoneGet(ZONE_STR));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testClientClose() throws Exception {
|
||||||
|
CfDnsClient closeableClient = new CfDnsClientBuilder().withApiTokenAuth(API_TOKEN).build();
|
||||||
|
// multiple requests with the same client
|
||||||
|
assertNotNull(closeableClient.zoneGet(ZONE_STR));
|
||||||
|
assertFalse(closeableClient.zoneList().isEmpty());
|
||||||
|
assertDoesNotThrow(closeableClient::close);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testMultiLevelSubdomainAndApex() throws Exception {
|
||||||
|
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||||
|
String multiLevel = "a.b-" + System.currentTimeMillis();
|
||||||
|
String apexContent = "cf-client-test-" + System.currentTimeMillis();
|
||||||
|
List<RecordEntity> created = new ArrayList<>();
|
||||||
|
try {
|
||||||
|
// multi-level subdomain
|
||||||
|
RecordEntity rec = client.recordCreateSubdomain(zone, multiLevel, TTL, RecordType.A, "130.0.0.10");
|
||||||
|
created.add(rec);
|
||||||
|
assertEquals(multiLevel + "." + ZONE_STR, rec.getName());
|
||||||
|
assertEquals(multiLevel, rec.getSubdomain());
|
||||||
|
List<RecordEntity> fetched = client.recordListBySubdomain(zone, multiLevel, RecordType.A);
|
||||||
|
assertEquals(1, fetched.size());
|
||||||
|
assertEquals(multiLevel, fetched.get(0).getSubdomain());
|
||||||
|
assertEquals(ZONE_STR, fetched.get(0).getZoneName());
|
||||||
|
|
||||||
|
// batch with a multi-level name must not cut the name
|
||||||
|
String batchName = "c.d-" + System.currentTimeMillis() + "." + ZONE_STR;
|
||||||
|
BatchEntry batchResult = client.recordBatch(zone,
|
||||||
|
List.of(RecordEntity.build(batchName, RecordType.A, TTL, "130.0.0.11")), null, null, null);
|
||||||
|
RecordEntity batched = batchResult.getPosts().get(0);
|
||||||
|
created.add(batched);
|
||||||
|
assertEquals(batchName, batched.getName());
|
||||||
|
|
||||||
|
// zone apex (TXT record with unique content, existing apex records stay untouched)
|
||||||
|
RecordEntity apex = client.recordCreateSubdomain(zone, CfDnsClient.APEX, TTL, RecordType.TXT,
|
||||||
|
"\"" + apexContent + "\"");
|
||||||
|
created.add(apex);
|
||||||
|
assertEquals(ZONE_STR, apex.getName());
|
||||||
|
assertEquals(CfDnsClient.APEX, apex.getSubdomain());
|
||||||
|
assertTrue(client.recordListBySubdomain(zone, CfDnsClient.APEX, RecordType.TXT).stream()
|
||||||
|
.anyMatch(r -> r.getId().equals(apex.getId()) && CfDnsClient.APEX.equals(r.getSubdomain())));
|
||||||
|
} finally {
|
||||||
|
deleteQuietly(zone, created);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testTypeFilter() throws Exception {
|
||||||
|
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||||
|
String sub = "types-" + System.currentTimeMillis();
|
||||||
|
List<RecordEntity> created = new ArrayList<>();
|
||||||
|
try {
|
||||||
|
created.add(client.recordCreateSubdomain(zone, sub, TTL, RecordType.A, "130.0.0.20"));
|
||||||
|
created.add(client.recordCreateSubdomain(zone, sub, TTL, RecordType.AAAA, "2001:db8::20"));
|
||||||
|
created.add(client.recordCreateSubdomain(zone, sub, TTL, RecordType.TXT, "\"type filter\""));
|
||||||
|
|
||||||
|
// one type: filtered by Cloudflare
|
||||||
|
List<RecordEntity> txt = client.recordListBySubdomain(zone, sub, RecordType.TXT);
|
||||||
|
assertEquals(1, txt.size());
|
||||||
|
assertEquals(RecordType.TXT.getType(), txt.get(0).getType());
|
||||||
|
assertTrue(client.recordListByType(zone, RecordType.TXT).stream()
|
||||||
|
.allMatch(r -> RecordType.TXT.getType().equals(r.getType())));
|
||||||
|
|
||||||
|
// multiple types: filtered by the client
|
||||||
|
List<RecordEntity> ip = client.recordListBySubdomain(zone, sub, RecordType.A, RecordType.AAAA);
|
||||||
|
assertEquals(Set.of("A", "AAAA"), ip.stream().map(RecordEntity::getType).collect(Collectors.toSet()));
|
||||||
|
|
||||||
|
// no type: all records
|
||||||
|
assertEquals(3, client.recordListBySubdomain(zone, sub).size());
|
||||||
|
} finally {
|
||||||
|
deleteQuietly(zone, created);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordAttributes() throws Exception {
|
||||||
|
ZoneEntity zone = client.zoneGet(ZONE_STR);
|
||||||
|
String sub = "attr-" + System.currentTimeMillis();
|
||||||
|
List<RecordEntity> created = new ArrayList<>();
|
||||||
|
Instant start = Instant.now().minusSeconds(60);
|
||||||
|
try {
|
||||||
|
// MX record with priority and comment
|
||||||
|
RecordEntity mx = RecordEntity.build(sub + "." + ZONE_STR, RecordType.MX, TTL, "mail." + ZONE_STR);
|
||||||
|
mx.setPriority(10);
|
||||||
|
mx.setComment("cf client test");
|
||||||
|
RecordEntity createdMx = client.recordCreate(zone, mx);
|
||||||
|
created.add(createdMx);
|
||||||
|
assertEquals(10, createdMx.getPriority());
|
||||||
|
assertEquals("cf client test", createdMx.getComment());
|
||||||
|
assertNull(mx.getId(), "the given record must not be modified");
|
||||||
|
// timestamps are Instants (UTC)
|
||||||
|
assertTrue(createdMx.getCreatedOn().isAfter(start), createdMx.getCreatedOn().toString());
|
||||||
|
assertTrue(createdMx.getCreatedOn().isBefore(Instant.now().plusSeconds(60)));
|
||||||
|
|
||||||
|
RecordEntity fetchedMx = client.recordListBySubdomain(zone, sub, RecordType.MX).get(0);
|
||||||
|
assertEquals(10, fetchedMx.getPriority());
|
||||||
|
assertEquals("cf client test", fetchedMx.getComment());
|
||||||
|
|
||||||
|
// partial update keeps the attributes which aren't sent
|
||||||
|
RecordEntity updatedMx = client.recordUpdate(zone, RecordEntity.build(fetchedMx.getId(), "mx2." + ZONE_STR));
|
||||||
|
assertEquals("mx2." + ZONE_STR, updatedMx.getContent());
|
||||||
|
assertEquals(10, updatedMx.getPriority());
|
||||||
|
assertEquals("cf client test", updatedMx.getComment());
|
||||||
|
|
||||||
|
// batch PATCH changes the priority
|
||||||
|
fetchedMx = client.recordListBySubdomain(zone, sub, RecordType.MX).get(0);
|
||||||
|
fetchedMx.setPriority(20);
|
||||||
|
client.recordBatch(zone, null, null, List.of(fetchedMx), null);
|
||||||
|
assertEquals(20, client.recordListBySubdomain(zone, sub, RecordType.MX).get(0).getPriority());
|
||||||
|
|
||||||
|
// SRV record with structured data, for SRV records the priority is part of the data
|
||||||
|
String srvName = "_sip._tcp." + sub + "." + ZONE_STR;
|
||||||
|
RecordEntity srv = RecordEntity.build(srvName, RecordType.SRV, TTL, null);
|
||||||
|
srv.setData(Map.of("priority", 10, "weight", 5, "port", 5060, "target", "sip." + ZONE_STR));
|
||||||
|
RecordEntity createdSrv = client.recordCreate(zone, srv);
|
||||||
|
created.add(createdSrv);
|
||||||
|
assertEquals(srvName, createdSrv.getName());
|
||||||
|
assertEquals(10, ((Number) createdSrv.getData().get("priority")).intValue());
|
||||||
|
assertEquals(5060, ((Number) createdSrv.getData().get("port")).intValue());
|
||||||
|
assertEquals(5, ((Number) createdSrv.getData().get("weight")).intValue());
|
||||||
|
assertEquals("sip." + ZONE_STR, createdSrv.getData().get("target"));
|
||||||
|
} finally {
|
||||||
|
deleteQuietly(zone, created);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void deleteQuietly(ZoneEntity zone, List<RecordEntity> records) {
|
||||||
|
for (RecordEntity rec : records) {
|
||||||
|
try {
|
||||||
|
client.recordDelete(zone, rec.getId());
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Couldn't delete test record {}: {}", rec.getName(), e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ import codes.thischwa.cf.model.*;
|
|||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
import org.mockito.Mock;
|
import org.mockito.Mock;
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
@@ -218,7 +219,7 @@ class CfDnsClientMockTest {
|
|||||||
CfDnsClient spyClient = spy(client);
|
CfDnsClient spyClient = spy(client);
|
||||||
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
List<RecordEntity> records = spyClient.recordList(zone, "test");
|
List<RecordEntity> records = spyClient.recordListBySubdomain(zone, "test");
|
||||||
|
|
||||||
assertNotNull(records);
|
assertNotNull(records);
|
||||||
assertEquals(1, records.size());
|
assertEquals(1, records.size());
|
||||||
@@ -239,7 +240,7 @@ class CfDnsClientMockTest {
|
|||||||
CfDnsClient spyClient = spy(client);
|
CfDnsClient spyClient = spy(client);
|
||||||
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
List<RecordEntity> records = spyClient.recordList(zone, "test", RecordType.A);
|
List<RecordEntity> records = spyClient.recordListBySubdomain(zone, "test", RecordType.A);
|
||||||
|
|
||||||
assertNotNull(records);
|
assertNotNull(records);
|
||||||
assertEquals(1, records.size());
|
assertEquals(1, records.size());
|
||||||
@@ -260,7 +261,7 @@ class CfDnsClientMockTest {
|
|||||||
CfDnsClient spyClient = spy(client);
|
CfDnsClient spyClient = spy(client);
|
||||||
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
doReturn(mockResponse).when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
List<RecordEntity> records = spyClient.recordList(zone, RecordType.A);
|
List<RecordEntity> records = spyClient.recordListByType(zone, RecordType.A);
|
||||||
|
|
||||||
assertNotNull(records);
|
assertNotNull(records);
|
||||||
assertEquals(1, records.size());
|
assertEquals(1, records.size());
|
||||||
@@ -360,7 +361,7 @@ class CfDnsClientMockTest {
|
|||||||
ZoneEntity zone = createTestZone();
|
ZoneEntity zone = createTestZone();
|
||||||
|
|
||||||
CfDnsClient spyClient = spy(client);
|
CfDnsClient spyClient = spy(client);
|
||||||
doThrow(new CloudflareNotFoundException("Not found")).when(spyClient).recordList(any(), anyString(), any());
|
doThrow(new CloudflareNotFoundException("Not found")).when(spyClient).recordListBySubdomain(any(), anyString(), any());
|
||||||
|
|
||||||
// Should not throw exception when record doesn't exist
|
// Should not throw exception when record doesn't exist
|
||||||
assertDoesNotThrow(() -> spyClient.recordDeleteTypeIfExists(zone, "test", RecordType.A));
|
assertDoesNotThrow(() -> spyClient.recordDeleteTypeIfExists(zone, "test", RecordType.A));
|
||||||
@@ -396,4 +397,338 @@ class CfDnsClientMockTest {
|
|||||||
assertEquals(1, result.getPosts().size());
|
assertEquals(1, result.getPosts().size());
|
||||||
assertEquals(TEST_ZONE_ID, result.getPosts().get(0).getZoneId());
|
assertEquals(TEST_ZONE_ID, result.getPosts().get(0).getZoneId());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ZoneMultipleResponse zoneResponse(List<ZoneEntity> zones, ResultInfo resultInfo) {
|
||||||
|
ZoneMultipleResponse resp = new ZoneMultipleResponse();
|
||||||
|
resp.setResult(zones);
|
||||||
|
resp.setResultInfo(resultInfo);
|
||||||
|
resp.setResponseResultInfo(createSuccessResultInfo());
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
private RecordMultipleResponse recordResponse(List<RecordEntity> records, ResultInfo resultInfo) {
|
||||||
|
RecordMultipleResponse resp = new RecordMultipleResponse();
|
||||||
|
resp.setResult(records);
|
||||||
|
resp.setResultInfo(resultInfo);
|
||||||
|
resp.setResponseResultInfo(createSuccessResultInfo());
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ZoneEntity zone(String id, String name) {
|
||||||
|
ZoneEntity zone = new ZoneEntity();
|
||||||
|
zone.setId(id);
|
||||||
|
zone.setName(name);
|
||||||
|
return zone;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testZoneGet_NotFound_ReturnsNull() throws Exception {
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(zoneResponse(List.of(), new ResultInfo(0)))
|
||||||
|
.when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
|
||||||
|
|
||||||
|
assertNull(spyClient.zoneGet("unknown.com"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testZoneGet_NotFound_ThrowsIfEnabled() throws Exception {
|
||||||
|
CfDnsClient throwingClient = spy(new CfDnsClientBuilder()
|
||||||
|
.withApiTokenAuth("test-token")
|
||||||
|
.withEmptyResultThrowsException(true)
|
||||||
|
.build());
|
||||||
|
doReturn(zoneResponse(List.of(), new ResultInfo(0)))
|
||||||
|
.when(throwingClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
|
||||||
|
|
||||||
|
assertThrows(CloudflareNotFoundException.class, () -> throwingClient.zoneGet("unknown.com"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testZone_NotFound_Throws() throws Exception {
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(zoneResponse(List.of(), new ResultInfo(0)))
|
||||||
|
.when(spyClient).getRequest(anyString(), eq(ZoneMultipleResponse.class));
|
||||||
|
|
||||||
|
assertThrows(CloudflareNotFoundException.class, () -> spyClient.zone("unknown.com"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testZoneList_FetchesAllPages() throws Exception {
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(zoneResponse(List.of(zone("z1", "a.com"), zone("z2", "b.com")),
|
||||||
|
new ResultInfo(1, 2, 2, 2, 3)))
|
||||||
|
.when(spyClient).getRequest(eq("/zones?page=1&per_page=" + CfDnsClient.ZONES_PER_PAGE),
|
||||||
|
eq(ZoneMultipleResponse.class));
|
||||||
|
doReturn(zoneResponse(List.of(zone("z3", "c.com")), new ResultInfo(2, 2, 2, 1, 3)))
|
||||||
|
.when(spyClient).getRequest(eq("/zones?page=2&per_page=" + CfDnsClient.ZONES_PER_PAGE),
|
||||||
|
eq(ZoneMultipleResponse.class));
|
||||||
|
|
||||||
|
List<ZoneEntity> zones = spyClient.zoneList();
|
||||||
|
|
||||||
|
assertEquals(List.of("a.com", "b.com", "c.com"), zones.stream().map(ZoneEntity::getName).toList());
|
||||||
|
verify(spyClient, times(2)).getRequest(anyString(), eq(ZoneMultipleResponse.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordListByType_FetchesAllPages() throws Exception {
|
||||||
|
ZoneEntity zone = createTestZone();
|
||||||
|
String base = "/zones/" + TEST_ZONE_ID + "/dns_records?type=A&page=%d&per_page=" + CfDnsClient.RECORDS_PER_PAGE;
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(recordResponse(List.of(RecordEntity.build("a.example.com", RecordType.A, 60, "1.1.1.1")),
|
||||||
|
new ResultInfo(1, 1, 2, 1, 2)))
|
||||||
|
.when(spyClient).getRequest(eq(String.format(base, 1)), eq(RecordMultipleResponse.class));
|
||||||
|
doReturn(recordResponse(List.of(RecordEntity.build("b.example.com", RecordType.A, 60, "2.2.2.2")),
|
||||||
|
new ResultInfo(2, 1, 2, 1, 2)))
|
||||||
|
.when(spyClient).getRequest(eq(String.format(base, 2)), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
|
List<RecordEntity> records = spyClient.recordListByType(zone, RecordType.A);
|
||||||
|
|
||||||
|
assertEquals(2, records.size());
|
||||||
|
assertEquals("b.example.com", records.get(1).getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordListBySld_FetchesAllPages() throws Exception {
|
||||||
|
ZoneEntity zone = createTestZone();
|
||||||
|
String base = "/zones/" + TEST_ZONE_ID + "/dns_records?name=test.example.com&page=%d&per_page="
|
||||||
|
+ CfDnsClient.RECORDS_PER_PAGE;
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(recordResponse(List.of(RecordEntity.build("test.example.com", RecordType.A, 60, "1.1.1.1")),
|
||||||
|
new ResultInfo(1, 1, 2, 1, 2)))
|
||||||
|
.when(spyClient).getRequest(eq(String.format(base, 1)), eq(RecordMultipleResponse.class));
|
||||||
|
doReturn(recordResponse(List.of(RecordEntity.build("test.example.com", RecordType.AAAA, 60, "::1")),
|
||||||
|
new ResultInfo(2, 1, 2, 1, 2)))
|
||||||
|
.when(spyClient).getRequest(eq(String.format(base, 2)), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
|
assertEquals(2, spyClient.recordListBySubdomain(zone, "test").size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordList_SetsZoneNameForSld() throws Exception {
|
||||||
|
ZoneEntity zone = createTestZone();
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(recordResponse(List.of(
|
||||||
|
RecordEntity.build("example.com", RecordType.A, 60, "1.1.1.1"),
|
||||||
|
RecordEntity.build("my.sub.example.com", RecordType.A, 60, "2.2.2.2")),
|
||||||
|
new ResultInfo(2)))
|
||||||
|
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
|
List<RecordEntity> records = spyClient.recordList(zone);
|
||||||
|
|
||||||
|
assertEquals(TEST_ZONE_NAME, records.get(0).getZoneName());
|
||||||
|
assertEquals("@", records.get(0).getSubdomain());
|
||||||
|
assertEquals("my.sub", records.get(1).getSubdomain());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordListByApex() throws Exception {
|
||||||
|
ZoneEntity zone = createTestZone();
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(recordResponse(List.of(), new ResultInfo(0)))
|
||||||
|
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
|
spyClient.recordListBySubdomain(zone, CfDnsClient.APEX);
|
||||||
|
|
||||||
|
verify(spyClient).getRequest(
|
||||||
|
eq("/zones/" + TEST_ZONE_ID + "/dns_records?name=example.com&page=1&per_page="
|
||||||
|
+ CfDnsClient.RECORDS_PER_PAGE),
|
||||||
|
eq(RecordMultipleResponse.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordDelete_NoResult_ReturnsFalse() throws Exception {
|
||||||
|
RecordSingleResponse mockResponse = new RecordSingleResponse();
|
||||||
|
mockResponse.setResponseResultInfo(createSuccessResultInfo());
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(mockResponse).when(spyClient).deleteRequest(anyString(), eq(RecordSingleResponse.class));
|
||||||
|
|
||||||
|
assertFalse(spyClient.recordDelete(createTestZone(), TEST_RECORD_ID));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordDelete_OtherId_ReturnsFalse() throws Exception {
|
||||||
|
RecordSingleResponse mockResponse = new RecordSingleResponse();
|
||||||
|
RecordEntity other = new RecordEntity();
|
||||||
|
other.setId("other");
|
||||||
|
mockResponse.setResult(other);
|
||||||
|
mockResponse.setResponseResultInfo(createSuccessResultInfo());
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(mockResponse).when(spyClient).deleteRequest(anyString(), eq(RecordSingleResponse.class));
|
||||||
|
|
||||||
|
assertFalse(spyClient.recordDelete(createTestZone(), TEST_RECORD_ID));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordBatch_UsesFullRecordName() throws Exception {
|
||||||
|
ZoneEntity zone = createTestZone();
|
||||||
|
RecordEntity apex = RecordEntity.build("example.com", RecordType.A, 300, "1.2.3.4");
|
||||||
|
RecordEntity multiLevel = RecordEntity.build("a.b.example.com", RecordType.A, 300, "1.2.3.5");
|
||||||
|
|
||||||
|
BatchResponse mockResponse = createBatchResponse();
|
||||||
|
mockResponse.setResult(new BatchEntry());
|
||||||
|
mockResponse.setResponseResultInfo(createSuccessResultInfo());
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(mockResponse).when(spyClient).postRequest(anyString(), any(), eq(BatchResponse.class));
|
||||||
|
|
||||||
|
spyClient.recordBatch(zone, List.of(apex, multiLevel), List.of(multiLevel), null, List.of(apex));
|
||||||
|
|
||||||
|
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(spyClient).postRequest(anyString(), payload.capture(), eq(BatchResponse.class));
|
||||||
|
BatchEntry sent = (BatchEntry) payload.getValue();
|
||||||
|
assertEquals(List.of("example.com", "a.b.example.com"),
|
||||||
|
sent.getPosts().stream().map(RecordEntity::getName).toList());
|
||||||
|
assertEquals("a.b.example.com", sent.getPuts().get(0).getName());
|
||||||
|
// deletes only need the ID
|
||||||
|
assertNull(sent.getDeletes().get(0).getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordList_NullPagingIsUnambiguousAndFetchesAll() throws Exception {
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(recordResponse(List.of(RecordEntity.build("a.example.com", RecordType.A, 60, "1.1.1.1")),
|
||||||
|
new ResultInfo(1)))
|
||||||
|
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
|
assertEquals(1, spyClient.recordList(createTestZone(), null).size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordListByType_SingleTypeIsFilteredServerSide() throws Exception {
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(recordResponse(List.of(), new ResultInfo(0)))
|
||||||
|
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
|
spyClient.recordListByType(createTestZone(), RecordType.MX);
|
||||||
|
spyClient.recordListBySubdomain(createTestZone(), "www", RecordType.TXT);
|
||||||
|
|
||||||
|
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records?type=MX&page=1&per_page="
|
||||||
|
+ CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
|
||||||
|
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID
|
||||||
|
+ "/dns_records?name=www.example.com&type=TXT&page=1&per_page="
|
||||||
|
+ CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordListByType_MultipleTypesAreFilteredClientSide() throws Exception {
|
||||||
|
RecordEntity unknownType = new RecordEntity();
|
||||||
|
unknownType.setName("x.example.com");
|
||||||
|
unknownType.setType("UNKNOWN_FUTURE_TYPE");
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(recordResponse(List.of(
|
||||||
|
RecordEntity.build("a.example.com", RecordType.A, 60, "1.1.1.1"),
|
||||||
|
RecordEntity.build("a.example.com", RecordType.AAAA, 60, "::1"),
|
||||||
|
RecordEntity.build("a.example.com", RecordType.TXT, 60, "txt"),
|
||||||
|
unknownType), new ResultInfo(4)))
|
||||||
|
.when(spyClient).getRequest(anyString(), eq(RecordMultipleResponse.class));
|
||||||
|
|
||||||
|
// an unknown record type in the response must not break the filter
|
||||||
|
List<RecordEntity> records = spyClient.recordListByType(createTestZone(), RecordType.A, RecordType.AAAA);
|
||||||
|
|
||||||
|
assertEquals(List.of("A", "AAAA"), records.stream().map(RecordEntity::getType).toList());
|
||||||
|
verify(spyClient).getRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records?page=1&per_page="
|
||||||
|
+ CfDnsClient.RECORDS_PER_PAGE), eq(RecordMultipleResponse.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RecordEntity fetchedMxRecord() {
|
||||||
|
RecordEntity rec = RecordEntity.build("example.com", RecordType.MX, 300, "mail.example.com");
|
||||||
|
rec.setId(TEST_RECORD_ID);
|
||||||
|
rec.setPriority(10);
|
||||||
|
rec.setProxied(false);
|
||||||
|
rec.setComment("primary mx");
|
||||||
|
rec.setTags(List.of("env:prod"));
|
||||||
|
rec.setZoneId(TEST_ZONE_ID);
|
||||||
|
rec.setZoneName(TEST_ZONE_NAME);
|
||||||
|
rec.setLocked(false);
|
||||||
|
rec.setProxiable(false);
|
||||||
|
rec.setCreatedOn(java.time.Instant.parse("2025-01-01T00:00:00Z"));
|
||||||
|
rec.setModifiedOn(java.time.Instant.parse("2025-01-02T00:00:00Z"));
|
||||||
|
return rec;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void assertOnlyWritableFields(RecordEntity sent) {
|
||||||
|
assertEquals("example.com", sent.getName());
|
||||||
|
assertEquals("MX", sent.getType());
|
||||||
|
assertEquals("mail.example.com", sent.getContent());
|
||||||
|
assertEquals(10, sent.getPriority());
|
||||||
|
assertEquals(false, sent.getProxied());
|
||||||
|
assertEquals("primary mx", sent.getComment());
|
||||||
|
assertEquals(List.of("env:prod"), sent.getTags());
|
||||||
|
assertNull(sent.getZoneId());
|
||||||
|
assertNull(sent.getZoneName());
|
||||||
|
assertNull(sent.getLocked());
|
||||||
|
assertNull(sent.getProxiable());
|
||||||
|
assertNull(sent.getCreatedOn());
|
||||||
|
assertNull(sent.getModifiedOn());
|
||||||
|
}
|
||||||
|
|
||||||
|
private RecordSingleResponse singleResponse(RecordEntity rec) {
|
||||||
|
RecordSingleResponse resp = new RecordSingleResponse();
|
||||||
|
resp.setResult(rec);
|
||||||
|
resp.setResponseResultInfo(createSuccessResultInfo());
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordUpdate_DoesNotModifyGivenRecordAndSendsWritableFields() throws Exception {
|
||||||
|
RecordEntity rec = fetchedMxRecord();
|
||||||
|
RecordEntity before = fetchedMxRecord();
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(singleResponse(fetchedMxRecord()))
|
||||||
|
.when(spyClient).patchRequest(anyString(), any(), eq(RecordSingleResponse.class));
|
||||||
|
|
||||||
|
spyClient.recordUpdate(createTestZone(), rec);
|
||||||
|
|
||||||
|
assertEquals(before, rec);
|
||||||
|
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(spyClient).patchRequest(eq("/zones/" + TEST_ZONE_ID + "/dns_records/" + TEST_RECORD_ID),
|
||||||
|
payload.capture(), eq(RecordSingleResponse.class));
|
||||||
|
assertOnlyWritableFields((RecordEntity) payload.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordCreate_SendsWritableFieldsWithoutId() throws Exception {
|
||||||
|
RecordEntity rec = fetchedMxRecord();
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(singleResponse(fetchedMxRecord()))
|
||||||
|
.when(spyClient).postRequest(anyString(), any(), eq(RecordSingleResponse.class));
|
||||||
|
|
||||||
|
spyClient.recordCreate(createTestZone(), rec);
|
||||||
|
|
||||||
|
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(spyClient).postRequest(anyString(), payload.capture(), eq(RecordSingleResponse.class));
|
||||||
|
RecordEntity sent = (RecordEntity) payload.getValue();
|
||||||
|
assertOnlyWritableFields(sent);
|
||||||
|
assertNull(sent.getId());
|
||||||
|
assertEquals(TEST_RECORD_ID, rec.getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordBatch_KeepsPriorityDataAndProxied() throws Exception {
|
||||||
|
RecordEntity srv = RecordEntity.build("_sip._tcp.example.com", RecordType.SRV, 300, null);
|
||||||
|
srv.setId("srv1");
|
||||||
|
srv.setPriority(10);
|
||||||
|
srv.setData(Map.of("priority", 10, "weight", 5, "port", 5060, "target", "sip.example.com"));
|
||||||
|
RecordEntity proxied = RecordEntity.build("www.example.com", RecordType.A, 1, "1.2.3.4");
|
||||||
|
proxied.setId("www1");
|
||||||
|
proxied.setProxied(true);
|
||||||
|
|
||||||
|
BatchResponse mockResponse = createBatchResponse();
|
||||||
|
mockResponse.setResult(new BatchEntry());
|
||||||
|
mockResponse.setResponseResultInfo(createSuccessResultInfo());
|
||||||
|
CfDnsClient spyClient = spy(client);
|
||||||
|
doReturn(mockResponse).when(spyClient).postRequest(anyString(), any(), eq(BatchResponse.class));
|
||||||
|
|
||||||
|
spyClient.recordBatch(createTestZone(), List.of(srv), List.of(proxied), List.of(srv), null);
|
||||||
|
|
||||||
|
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
|
||||||
|
verify(spyClient).postRequest(anyString(), payload.capture(), eq(BatchResponse.class));
|
||||||
|
BatchEntry sent = (BatchEntry) payload.getValue();
|
||||||
|
RecordEntity sentPost = sent.getPosts().get(0);
|
||||||
|
assertNull(sentPost.getId());
|
||||||
|
assertEquals(10, sentPost.getPriority());
|
||||||
|
assertEquals(5060, sentPost.getData().get("port"));
|
||||||
|
assertEquals("www1", sent.getPuts().get(0).getId());
|
||||||
|
assertEquals(true, sent.getPuts().get(0).getProxied());
|
||||||
|
assertEquals("srv1", sent.getPatches().get(0).getId());
|
||||||
|
assertEquals(10, sent.getPatches().get(0).getPriority());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -3,26 +3,29 @@ package codes.thischwa.cf;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.junit.jupiter.api.Assertions.fail;
|
import static org.junit.jupiter.api.Assertions.fail;
|
||||||
|
|
||||||
import codes.thischwa.cf.model.AbstractResponse;
|
import codes.thischwa.cf.model.AbstractResponse;
|
||||||
import codes.thischwa.cf.model.BatchResponse;
|
import codes.thischwa.cf.model.BatchResponse;
|
||||||
|
import codes.thischwa.cf.model.RecordEntity;
|
||||||
import codes.thischwa.cf.model.RecordMultipleResponse;
|
import codes.thischwa.cf.model.RecordMultipleResponse;
|
||||||
import codes.thischwa.cf.model.RecordSingleResponse;
|
import codes.thischwa.cf.model.RecordSingleResponse;
|
||||||
|
import codes.thischwa.cf.model.RecordType;
|
||||||
import codes.thischwa.cf.model.ResponseResultInfo;
|
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||||
import codes.thischwa.cf.model.ZoneMultipleResponse;
|
import codes.thischwa.cf.model.ZoneMultipleResponse;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import tools.jackson.core.JacksonException;
|
||||||
|
import tools.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
public class ObjectMapperTest {
|
public class ObjectMapperTest {
|
||||||
|
|
||||||
private final ObjectMapper mapper = JsonConf.initObjectMapper();
|
private final ObjectMapper mapper = JsonConf.initObjectMapper();
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testObjectMapper() throws IOException {
|
void testObjectMapper() {
|
||||||
ZoneMultipleResponse resp =
|
ZoneMultipleResponse resp =
|
||||||
mapper.readValue(this.getClass().getResourceAsStream("/zone-list-response.json"),
|
mapper.readValue(this.getClass().getResourceAsStream("/zone-list-response.json"),
|
||||||
ZoneMultipleResponse.class);
|
ZoneMultipleResponse.class);
|
||||||
@@ -30,7 +33,7 @@ public class ObjectMapperTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testErrorResponse() throws IOException {
|
void testErrorResponse() {
|
||||||
List<Class<? extends AbstractResponse>> respClasses =
|
List<Class<? extends AbstractResponse>> respClasses =
|
||||||
List.of(RecordSingleResponse.class, RecordMultipleResponse.class, ZoneMultipleResponse.class, BatchResponse.class);
|
List.of(RecordSingleResponse.class, RecordMultipleResponse.class, ZoneMultipleResponse.class, BatchResponse.class);
|
||||||
respClasses.forEach(this::assertErrorResponse);
|
respClasses.forEach(this::assertErrorResponse);
|
||||||
@@ -46,8 +49,39 @@ public class ObjectMapperTest {
|
|||||||
assertFalse(resultInfo.isSuccess());
|
assertFalse(resultInfo.isSuccess());
|
||||||
assertEquals(1, resultInfo.getErrors().size());
|
assertEquals(1, resultInfo.getErrors().size());
|
||||||
assertEquals(81053, resultInfo.getErrors().get(0).getCode());
|
assertEquals(81053, resultInfo.getErrors().get(0).getCode());
|
||||||
} catch (IOException e) {
|
} catch (JacksonException e) {
|
||||||
fail("fail for " + clazz + ": " + e.getMessage());
|
fail("fail for " + clazz + ": " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testSubdomainIsNotSerialized() {
|
||||||
|
RecordEntity rec = RecordEntity.build("www.example.com", RecordType.A, 60, "1.2.3.4");
|
||||||
|
rec.setZoneName("example.com");
|
||||||
|
String json = mapper.writeValueAsString(rec);
|
||||||
|
assertTrue(json.contains("\"name\":\"www.example.com\""), json);
|
||||||
|
assertFalse(json.contains("subdomain"), json);
|
||||||
|
assertFalse(json.contains("sld"), json);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testRecordFieldsAreMappedInSnakeCase() {
|
||||||
|
String json = """
|
||||||
|
{"id":"r1","name":"_sip._tcp.example.com","type":"SRV","ttl":300,"priority":10,
|
||||||
|
"comment":"sip","tags":["env:prod"],
|
||||||
|
"data":{"weight":5,"port":5060,"target":"sip.example.com"},
|
||||||
|
"created_on":"2025-01-20T08:56:34.736214Z","modified_on":"2025-01-21T08:56:34Z"}
|
||||||
|
""";
|
||||||
|
RecordEntity rec = mapper.readValue(json, RecordEntity.class);
|
||||||
|
assertEquals(10, rec.getPriority());
|
||||||
|
assertEquals("sip", rec.getComment());
|
||||||
|
assertEquals(List.of("env:prod"), rec.getTags());
|
||||||
|
assertEquals(5060, rec.getData().get("port"));
|
||||||
|
assertEquals(java.time.Instant.parse("2025-01-20T08:56:34.736214Z"), rec.getCreatedOn());
|
||||||
|
assertEquals(java.time.Instant.parse("2025-01-21T08:56:34Z"), rec.getModifiedOn());
|
||||||
|
|
||||||
|
String out = mapper.writeValueAsString(rec);
|
||||||
|
assertTrue(out.contains("\"priority\":10"), out);
|
||||||
|
assertTrue(out.contains("\"created_on\":\"2025-01-20T08:56:34.736214Z\""), out);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -11,6 +11,8 @@ import codes.thischwa.cf.model.RecordMultipleResponse;
|
|||||||
import codes.thischwa.cf.model.RecordSingleResponse;
|
import codes.thischwa.cf.model.RecordSingleResponse;
|
||||||
import codes.thischwa.cf.model.ResponseResultInfo;
|
import codes.thischwa.cf.model.ResponseResultInfo;
|
||||||
import codes.thischwa.cf.model.ResultInfo;
|
import codes.thischwa.cf.model.ResultInfo;
|
||||||
|
import codes.thischwa.cf.model.ZoneEntity;
|
||||||
|
import codes.thischwa.cf.model.ZoneMultipleResponse;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
@@ -130,4 +132,44 @@ class ResponseValidatorTest {
|
|||||||
assertDoesNotThrow(() -> validatorWithException.validate(mockSingleResponse, false));
|
assertDoesNotThrow(() -> validatorWithException.validate(mockSingleResponse, false));
|
||||||
assertDoesNotThrow(() -> validatorWithoutException.validate(mockSingleResponse, false));
|
assertDoesNotThrow(() -> validatorWithoutException.validate(mockSingleResponse, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static ZoneMultipleResponse zoneResponse(int count) {
|
||||||
|
ZoneMultipleResponse resp = new ZoneMultipleResponse();
|
||||||
|
ResponseResultInfo info = new ResponseResultInfo();
|
||||||
|
info.setSuccess(true);
|
||||||
|
resp.setResponseResultInfo(info);
|
||||||
|
List<ZoneEntity> zones = new ArrayList<>();
|
||||||
|
for (int i = 0; i < count; i++) {
|
||||||
|
zones.add(new ZoneEntity());
|
||||||
|
}
|
||||||
|
resp.setResult(zones);
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateZoneResponseEmptyWithExceptionEnabled() {
|
||||||
|
ZoneMultipleResponse resp = zoneResponse(0);
|
||||||
|
resp.setResultInfo(new ResultInfo(0));
|
||||||
|
assertThrows(CloudflareNotFoundException.class, () -> validatorWithException.validate(resp, true));
|
||||||
|
assertDoesNotThrow(() -> validatorWithoutException.validate(resp, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateZoneResponseMultipleWhenSingleExpected() {
|
||||||
|
ZoneMultipleResponse resp = zoneResponse(2);
|
||||||
|
resp.setResultInfo(new ResultInfo(2));
|
||||||
|
CloudflareApiException exception = assertThrows(CloudflareApiException.class,
|
||||||
|
() -> validatorWithoutException.validate(resp, true));
|
||||||
|
assertTrue(exception.getMessage().contains("Unexpected result count: 2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateMultipleResponseWithoutResultInfoFallsBackToResultSize() {
|
||||||
|
// no result_info -> count is derived from the result list
|
||||||
|
assertThrows(CloudflareNotFoundException.class,
|
||||||
|
() -> validatorWithException.validate(zoneResponse(0), false));
|
||||||
|
assertThrows(CloudflareApiException.class,
|
||||||
|
() -> validatorWithoutException.validate(zoneResponse(2), true));
|
||||||
|
assertDoesNotThrow(() -> validatorWithException.validate(zoneResponse(1), true));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -59,7 +59,7 @@ class FluentApiTest {
|
|||||||
RecordEntity rec2 = RecordEntity.build("www.example.com", RecordType.A, 300, "1.2.3.5");
|
RecordEntity rec2 = RecordEntity.build("www.example.com", RecordType.A, 300, "1.2.3.5");
|
||||||
List<RecordEntity> expectedRecords = List.of(rec1, rec2);
|
List<RecordEntity> expectedRecords = List.of(rec1, rec2);
|
||||||
|
|
||||||
when(mockClient.recordList(eq(testZone), any(RecordType[].class)))
|
when(mockClient.recordListByType(eq(testZone), any(RecordType[].class)))
|
||||||
.thenReturn(expectedRecords);
|
.thenReturn(expectedRecords);
|
||||||
|
|
||||||
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
|
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
|
||||||
@@ -67,7 +67,7 @@ class FluentApiTest {
|
|||||||
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertEquals(2, result.size());
|
assertEquals(2, result.size());
|
||||||
verify(mockClient, times(1)).recordList(eq(testZone), any(RecordType[].class));
|
verify(mockClient, times(1)).recordListByType(eq(testZone), any(RecordType[].class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -75,7 +75,7 @@ class FluentApiTest {
|
|||||||
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
||||||
List<RecordEntity> expectedRecords = List.of(rec1);
|
List<RecordEntity> expectedRecords = List.of(rec1);
|
||||||
|
|
||||||
when(mockClient.recordList(eq(testZone), any(RecordType[].class)))
|
when(mockClient.recordListByType(eq(testZone), any(RecordType[].class)))
|
||||||
.thenReturn(expectedRecords);
|
.thenReturn(expectedRecords);
|
||||||
|
|
||||||
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
|
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
|
||||||
@@ -83,7 +83,7 @@ class FluentApiTest {
|
|||||||
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertEquals(1, result.size());
|
assertEquals(1, result.size());
|
||||||
verify(mockClient, times(1)).recordList(eq(testZone), any(RecordType[].class));
|
verify(mockClient, times(1)).recordListByType(eq(testZone), any(RecordType[].class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -91,7 +91,7 @@ class FluentApiTest {
|
|||||||
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
||||||
List<RecordEntity> expectedRecords = List.of(rec1);
|
List<RecordEntity> expectedRecords = List.of(rec1);
|
||||||
|
|
||||||
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
|
when(mockClient.recordListBySubdomain(eq(testZone), eq(TEST_SLD), any()))
|
||||||
.thenReturn(expectedRecords);
|
.thenReturn(expectedRecords);
|
||||||
|
|
||||||
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
||||||
@@ -100,7 +100,7 @@ class FluentApiTest {
|
|||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertEquals(1, result.size());
|
assertEquals(1, result.size());
|
||||||
assertEquals("1.2.3.4", result.get(0).getContent());
|
assertEquals("1.2.3.4", result.get(0).getContent());
|
||||||
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
|
verify(mockClient, times(1)).recordListBySubdomain(eq(testZone), eq(TEST_SLD), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -109,7 +109,7 @@ class FluentApiTest {
|
|||||||
List<RecordEntity> expectedRecords = List.of(rec1);
|
List<RecordEntity> expectedRecords = List.of(rec1);
|
||||||
|
|
||||||
RecordType[] types = {RecordType.A};
|
RecordType[] types = {RecordType.A};
|
||||||
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), eq(types)))
|
when(mockClient.recordListBySubdomain(eq(testZone), eq(TEST_SLD), eq(types)))
|
||||||
.thenReturn(expectedRecords);
|
.thenReturn(expectedRecords);
|
||||||
|
|
||||||
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, types);
|
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, types);
|
||||||
@@ -117,7 +117,7 @@ class FluentApiTest {
|
|||||||
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertEquals(1, result.size());
|
assertEquals(1, result.size());
|
||||||
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), eq(types));
|
verify(mockClient, times(1)).recordListBySubdomain(eq(testZone), eq(TEST_SLD), eq(types));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -125,7 +125,7 @@ class FluentApiTest {
|
|||||||
RecordEntity createdRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
RecordEntity createdRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
||||||
createdRecord.setId(TEST_RECORD_ID);
|
createdRecord.setId(TEST_RECORD_ID);
|
||||||
|
|
||||||
when(mockClient.recordCreateSld(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4")))
|
when(mockClient.recordCreateSubdomain(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4")))
|
||||||
.thenReturn(createdRecord);
|
.thenReturn(createdRecord);
|
||||||
|
|
||||||
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
||||||
@@ -134,7 +134,7 @@ class FluentApiTest {
|
|||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertEquals(TEST_RECORD_ID, result.getId());
|
assertEquals(TEST_RECORD_ID, result.getId());
|
||||||
assertEquals("1.2.3.4", result.getContent());
|
assertEquals("1.2.3.4", result.getContent());
|
||||||
verify(mockClient, times(1)).recordCreateSld(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4"));
|
verify(mockClient, times(1)).recordCreateSubdomain(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -145,7 +145,7 @@ class FluentApiTest {
|
|||||||
RecordEntity updatedRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.5");
|
RecordEntity updatedRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.5");
|
||||||
updatedRecord.setId(TEST_RECORD_ID);
|
updatedRecord.setId(TEST_RECORD_ID);
|
||||||
|
|
||||||
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
|
when(mockClient.recordListBySubdomain(eq(testZone), eq(TEST_SLD), any()))
|
||||||
.thenReturn(List.of(existingRecord));
|
.thenReturn(List.of(existingRecord));
|
||||||
when(mockClient.recordUpdate(eq(testZone), any(RecordEntity.class)))
|
when(mockClient.recordUpdate(eq(testZone), any(RecordEntity.class)))
|
||||||
.thenReturn(updatedRecord);
|
.thenReturn(updatedRecord);
|
||||||
@@ -155,13 +155,17 @@ class FluentApiTest {
|
|||||||
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertEquals("1.2.3.5", result.getContent());
|
assertEquals("1.2.3.5", result.getContent());
|
||||||
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
|
verify(mockClient, times(1)).recordListBySubdomain(eq(testZone), eq(TEST_SLD), any());
|
||||||
verify(mockClient, times(1)).recordUpdate(eq(testZone), any(RecordEntity.class));
|
// only ID and new content are sent (partial update)
|
||||||
|
verify(mockClient, times(1)).recordUpdate(eq(testZone), argThat(rec ->
|
||||||
|
TEST_RECORD_ID.equals(rec.getId()) && "1.2.3.5".equals(rec.getContent())
|
||||||
|
&& rec.getName() == null && rec.getTtl() == null));
|
||||||
|
assertEquals("1.2.3.4", existingRecord.getContent());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void testRecordOperations_Update_NoRecordsFound() throws CloudflareApiException {
|
void testRecordOperations_Update_NoRecordsFound() throws CloudflareApiException {
|
||||||
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
|
when(mockClient.recordListBySubdomain(eq(testZone), eq(TEST_SLD), any()))
|
||||||
.thenReturn(List.of());
|
.thenReturn(List.of());
|
||||||
|
|
||||||
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
||||||
@@ -171,7 +175,7 @@ class FluentApiTest {
|
|||||||
});
|
});
|
||||||
|
|
||||||
assertTrue(exception.getMessage().contains("No recs found"));
|
assertTrue(exception.getMessage().contains("No recs found"));
|
||||||
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
|
verify(mockClient, times(1)).recordListBySubdomain(eq(testZone), eq(TEST_SLD), any());
|
||||||
verify(mockClient, never()).recordUpdate(any(), any());
|
verify(mockClient, never()).recordUpdate(any(), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,7 +184,7 @@ class FluentApiTest {
|
|||||||
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
RecordEntity rec1 = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
||||||
RecordEntity rec2 = RecordEntity.build("test.example.com", RecordType.AAAA, 300, "::1");
|
RecordEntity rec2 = RecordEntity.build("test.example.com", RecordType.AAAA, 300, "::1");
|
||||||
|
|
||||||
when(mockClient.recordList(eq(testZone), eq(TEST_SLD), any()))
|
when(mockClient.recordListBySubdomain(eq(testZone), eq(TEST_SLD), any()))
|
||||||
.thenReturn(List.of(rec1, rec2));
|
.thenReturn(List.of(rec1, rec2));
|
||||||
|
|
||||||
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
RecordOperations recordOps = new RecordOperationsImpl(mockClient, testZone, TEST_SLD, null);
|
||||||
@@ -190,7 +194,7 @@ class FluentApiTest {
|
|||||||
});
|
});
|
||||||
|
|
||||||
assertTrue(exception.getMessage().contains("Multiple recs found"));
|
assertTrue(exception.getMessage().contains("Multiple recs found"));
|
||||||
verify(mockClient, times(1)).recordList(eq(testZone), eq(TEST_SLD), any());
|
verify(mockClient, times(1)).recordListBySubdomain(eq(testZone), eq(TEST_SLD), any());
|
||||||
verify(mockClient, never()).recordUpdate(any(), any());
|
verify(mockClient, never()).recordUpdate(any(), any());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,7 +224,7 @@ class FluentApiTest {
|
|||||||
RecordEntity createdRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
RecordEntity createdRecord = RecordEntity.build("test.example.com", RecordType.A, 300, "1.2.3.4");
|
||||||
createdRecord.setId(TEST_RECORD_ID);
|
createdRecord.setId(TEST_RECORD_ID);
|
||||||
|
|
||||||
when(mockClient.recordCreateSld(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4")))
|
when(mockClient.recordCreateSubdomain(eq(testZone), eq(TEST_SLD), eq(300), eq(RecordType.A), eq("1.2.3.4")))
|
||||||
.thenReturn(createdRecord);
|
.thenReturn(createdRecord);
|
||||||
|
|
||||||
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
|
ZoneOperations zoneOps = new ZoneOperationsImpl(mockClient, testZone);
|
||||||
|
|||||||
@@ -41,19 +41,19 @@ public class RecordEntityTest {
|
|||||||
@Test
|
@Test
|
||||||
void testGetSld() {
|
void testGetSld() {
|
||||||
RecordEntity rec = new RecordEntity();
|
RecordEntity rec = new RecordEntity();
|
||||||
assertNull(rec.getSld());
|
assertNull(rec.getSubdomain());
|
||||||
|
|
||||||
rec.setName("sub.example.com");
|
rec.setName("sub.example.com");
|
||||||
assertEquals("sub", rec.getSld());
|
assertEquals("sub", rec.getSubdomain());
|
||||||
|
|
||||||
rec.setName("example.com");
|
rec.setName("example.com");
|
||||||
assertEquals("example", rec.getSld());
|
assertEquals("example", rec.getSubdomain());
|
||||||
|
|
||||||
rec.setName("host");
|
rec.setName("host");
|
||||||
assertEquals("host", rec.getSld());
|
assertEquals("host", rec.getSubdomain());
|
||||||
|
|
||||||
rec.setName(".dotstart");
|
rec.setName(".dotstart");
|
||||||
assertEquals(".dotstart", rec.getSld());
|
assertEquals(".dotstart", rec.getSubdomain());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -61,10 +61,47 @@ public class RecordEntityTest {
|
|||||||
RecordEntity rec = new RecordEntity();
|
RecordEntity rec = new RecordEntity();
|
||||||
rec.setName("sub.example.com");
|
rec.setName("sub.example.com");
|
||||||
rec.setZoneName("example.com");
|
rec.setZoneName("example.com");
|
||||||
assertEquals("sub", rec.getSld());
|
assertEquals("sub", rec.getSubdomain());
|
||||||
|
|
||||||
rec.setName("my.sub.example.com");
|
rec.setName("my.sub.example.com");
|
||||||
rec.setZoneName("example.com");
|
rec.setZoneName("example.com");
|
||||||
assertEquals("my.sub", rec.getSld());
|
assertEquals("my.sub", rec.getSubdomain());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetSldApexWithZoneName() {
|
||||||
|
RecordEntity rec = new RecordEntity();
|
||||||
|
rec.setName("example.com");
|
||||||
|
rec.setZoneName("example.com");
|
||||||
|
assertEquals("@", rec.getSubdomain());
|
||||||
|
|
||||||
|
rec.setName("Example.COM");
|
||||||
|
assertEquals("@", rec.getSubdomain());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetSldZoneNameIsNoLabelSuffix() {
|
||||||
|
// "notexample.com" ends with "example.com", but is not part of the zone
|
||||||
|
RecordEntity rec = new RecordEntity();
|
||||||
|
rec.setName("notexample.com");
|
||||||
|
rec.setZoneName("example.com");
|
||||||
|
assertEquals("notexample", rec.getSubdomain());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetSldCaseInsensitive() {
|
||||||
|
RecordEntity rec = new RecordEntity();
|
||||||
|
rec.setName("WWW.Example.com");
|
||||||
|
rec.setZoneName("example.com");
|
||||||
|
assertEquals("WWW", rec.getSubdomain());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings("removal")
|
||||||
|
void testDeprecatedGetSldDelegatesToGetSubdomain() {
|
||||||
|
RecordEntity rec = new RecordEntity();
|
||||||
|
rec.setName("my.sub.example.com");
|
||||||
|
rec.setZoneName("example.com");
|
||||||
|
assertEquals(rec.getSubdomain(), rec.getSld());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,7 @@ package codes.thischwa.cf.model;
|
|||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
import java.time.Instant;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ public class ZoneEntityTest {
|
|||||||
Set<String> ns = Set.of("ns1.cloudflare.com", "ns2.cloudflare.com");
|
Set<String> ns = Set.of("ns1.cloudflare.com", "ns2.cloudflare.com");
|
||||||
zone.setNameServers(ns);
|
zone.setNameServers(ns);
|
||||||
zone.setOriginalNameServers(ns);
|
zone.setOriginalNameServers(ns);
|
||||||
LocalDateTime now = LocalDateTime.now();
|
Instant now = Instant.now();
|
||||||
zone.setCreatedOn(now);
|
zone.setCreatedOn(now);
|
||||||
zone.setModifiedOn(now);
|
zone.setModifiedOn(now);
|
||||||
zone.setActivatedOn(now);
|
zone.setActivatedOn(now);
|
||||||
|
|||||||
Reference in new issue
Block a user