Package codes.thischwa.cf
Class CfDnsClient
java.lang.Object
codes.thischwa.cf.CfDnsClient
- All Implemented Interfaces:
AutoCloseable
CfDnsClient is a client interface to interact with Cloudflare DNS service. It allows managing DNS
records and zones within the Cloudflare system, including creating, updating, retrieving, and
deleting DNS records.
The client is thread-safe and should be reused. It holds a pool of HTTP connections, which is
released by AutoCloseable.close().
Example with API token authentication (recommended):
// Create a new CfDnsClient instance with API token
try (CfDnsClient cfDnsClient = new CfDnsClientBuilder()
.withApiTokenAuth("your-api-token")
.build()) {
// Retrieve a zone
ZoneEntity zone = cfDnsClient.zoneGet("example.com");
System.out.println("Zone ID: " + zone.getId());
// Retrieve records of a subdomain
List<RecordEntity> records = cfDnsClient.recordListBySubdomain(zone, "www");
records.forEach(record ->
System.out.println("Record Type: " + record.getType() + ", Value: " + record.getContent())
);
// Create a record for the subdomain "api"
RecordEntity created = cfDnsClient.recordCreateSubdomain(zone, "api", 60, RecordType.A, "192.168.1.10");
System.out.println("Created Record ID: " + created.getId());
}
Example with email/key authentication (legacy):
CfDnsClient cfDnsClient = new CfDnsClientBuilder()
.withEmailKeyAuth("email@example.com", "your-api-key")
.build();
Example with exception throwing enabled:
// Throws exception when results are empty
CfDnsClient cfDnsClient = new CfDnsClientBuilder()
.withApiTokenAuth("your-api-token")
.withEmptyResultThrowsException(true)
.build();
Example specifying the Cloudflare API base URL:
CfDnsClient cfDnsClient = new CfDnsClientBuilder()
.withApiTokenAuth("your-api-token")
.withBaseUrl(CfDnsClientBuilder.DEFAULT_BASEURL)
.build();
-
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionvoidclose()Releases the underlying HTTP client and its connections.static Map<String, List<RecordEntity>> groupRecordsByFqdn(List<RecordEntity> records) Groups a list of DNS records by their fully qualified domain name (FQDN).recordBatch(ZoneEntity zone, @Nullable List<RecordEntity> postRecords, @Nullable List<RecordEntity> putRecords, @Nullable List<RecordEntity> patchRecords, @Nullable List<RecordEntity> deleteRecords) Processes a batch of DNS record operations (POST, PUT, PATCH, DELETE) for a specified zone.recordCreate(ZoneEntity zone, RecordEntity rec) Creates a new DNS record in the specified zone using the Cloudflare API.recordCreate(ZoneEntity zone, String name, int ttl, RecordType type, String content) Creates a DNS record in the specified DNS zone with the provided details.recordCreateSubdomain(ZoneEntity zone, String subdomain, int ttl, RecordType type, String content) Creates a new DNS record for a given subdomain within the specified zone.booleanrecordDelete(ZoneEntity zone, RecordEntity rec) Deletes a DNS record of the specified type within a given zone on the Cloudflare API.booleanrecordDelete(ZoneEntity zone, String id) Deletes a DNS record of the specified type within a given zone on the Cloudflare API.voidrecordDeleteTypeIfExists(ZoneEntity zone, String subdomain, RecordType... recordTypes) Attempts to delete DNS records of the specified types within a given zone.recordList(ZoneEntity zone) Retrieves all DNS records for a specified zone.recordList(ZoneEntity zone, @Nullable PagingRequest pagingRequest) Retrieves DNS records for a specified zone, with optional paging support.recordListBySubdomain(ZoneEntity zone, String subdomain, @Nullable RecordType... types) Retrieves DNS records for the specified subdomain within a zone.recordListByType(ZoneEntity zone, @Nullable RecordType... types) Retrieves all DNS records of the given types for a zone.recordUpdate(ZoneEntity zone, RecordEntity rec) Updates an existing DNS record in a specified Cloudflare zone (partial update, attributes which arenullremain unchanged).Provides fluent API access to operations in a specific zone.@Nullable ZoneEntityRetrieves detailed information about a specific zone by its name.zoneList()Retrieves a list of all zones from the Cloudflare API.zoneList(PagingRequest pagingRequest) Retrieves a single page of DNS zones using the provided paging request parameters.
-
Field Details
-
APEX
Conventional name for the zone apex (the zone name itself).- See Also:
-
-
Method Details
-
groupRecordsByFqdn
Groups a list of DNS records by their fully qualified domain name (FQDN).- Parameters:
records- A list ofRecordEntityobjects to be grouped by FQDN.- Returns:
- A map where the key is the FQDN (name field) and the value is a list of
RecordEntityobjects that share that FQDN.
-
zone
Provides fluent API access to operations in a specific zone. This method returns a ZoneOperations interface that allows chaining operations on DNS records within the specified zone.Example:
client.zone("example.com") .getRecord("api") .create(RecordType.A, "192.168.1.1", 60);- Parameters:
zoneName- the name of the DNS zone (e.g., "example.com")- Returns:
- a ZoneOperations instance for chaining operations
- Throws:
CloudflareNotFoundException- if the zone doesn't existCloudflareApiException- if the zone cannot be accessedIllegalArgumentException- if the name is blank or contains invalid characters
-
zoneList
Retrieves a list of all zones from the Cloudflare API. If there are more zones than fit on one page, all pages are fetched.- Returns:
- 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.
-
zoneList
Retrieves a single page of DNS zones using the provided paging request parameters. Cloudflare requires a page size between 5 and 50 for this endpoint.- Parameters:
pagingRequest- the pagination request object containing parameters for paging and filtering zone data- Returns:
- a list of
ZoneEntityobjects representing the DNS zones retrieved from the API - Throws:
CloudflareApiException- if there is an error during the API request or response processingIllegalArgumentException- if the page size is outside the range 5 to 50
-
zoneGet
Retrieves detailed information about a specific zone by its name.- Parameters:
name- The name of the zone to retrieve information for.- Returns:
- A
ZoneEntityobject that contains details of the specified zone, ornullif the zone doesn't exist and 'emptyResultThrowsException' is disabled. - Throws:
CloudflareNotFoundException- If the zone doesn't exist and 'emptyResultThrowsException' is enabled.CloudflareApiException- If an error occurs while making the API request or processing the response.IllegalArgumentException- if the name is blank or contains invalid characters
-
recordList
Retrieves all DNS records for a specified zone. If there are more records than fit on one page, all pages are fetched.- Parameters:
zone- The zone entity containing information about the target zone.- Returns:
- 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.
-
recordList
public List<RecordEntity> recordList(ZoneEntity zone, @Nullable @Nullable PagingRequest pagingRequest) throws CloudflareApiException Retrieves DNS records for a specified zone, with optional paging support.- Parameters:
zone- The zone entity containing information about the target zone.pagingRequest- The paging request containing parameters such as page size and number. Ifnull, all pages are fetched using an internal page size of 1,000. For a specific page, Cloudflare allows a page size between 1 and 5,000,000.- Returns:
- 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.
-
recordListBySubdomain
public List<RecordEntity> recordListBySubdomain(ZoneEntity zone, String subdomain, @Nullable @Nullable RecordType... types) throws CloudflareApiException Retrieves DNS records for the specified subdomain within a zone. Optionally, filters by one or more DNS record types.- Parameters:
zone- The zone entity containing information about the domain zone.subdomain- The subdomain relative to the zone (e.g. "www" for "www.example.com"); Unicode subdomains are converted to Punycode.APEXindicates the zone apex.types- Optional DNS record types to filter the results. If none are given, records of all types are returned.- Returns:
- A list of
RecordEntityobjects representing the DNS records for the specified domain. - Throws:
CloudflareNotFoundException- if no records were found and 'emptyResultThrowsException' is enabledCloudflareApiException- if an error occurs while interacting with the Cloudflare APIIllegalArgumentException- if the subdomain is blank, contains invalid characters or cannot be converted to Punycode
-
recordListByType
public List<RecordEntity> recordListByType(ZoneEntity zone, @Nullable @Nullable RecordType... types) throws CloudflareApiException Retrieves all DNS records of the given types for a zone.- Parameters:
zone- The zone entity containing information about the domain zone.types- Optional DNS record types to filter the results. If none are given, records of all types are returned.- Returns:
- A list of
RecordEntityobjects representing the DNS records for the specified zone. - Throws:
CloudflareNotFoundException- if no records were found and 'emptyResultThrowsException' is enabledCloudflareApiException- if an error occurs while interacting with the Cloudflare API
-
recordCreateSubdomain
public RecordEntity recordCreateSubdomain(ZoneEntity zone, String subdomain, int ttl, RecordType type, String content) throws CloudflareApiException Creates a new DNS record for a given subdomain within the specified zone.- Parameters:
zone- The ZoneEntity representing the DNS zone where the record is to be created.subdomain- The subdomain relative to the zone (e.g. "api" for "api.example.com"); Unicode subdomains are converted to Punycode.APEXindicates the zone apex.ttl- The time-to-live (TTL) value for the DNS record in seconds.type- The RecordType specifying the type of the DNS record (e.g., A, AAAA, CNAME).content- The content of the DNS record (e.g., IP address for A/AAAA records, target domain for CNAME).- Returns:
- 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.IllegalArgumentException- if the subdomain is blank, contains invalid characters or cannot be converted to Punycode
-
recordCreate
public RecordEntity recordCreate(ZoneEntity zone, String name, int ttl, RecordType type, String content) throws CloudflareApiException Creates a DNS record in the specified DNS zone with the provided details.- Parameters:
zone- the DNS zone in which the record will be createdname- the name of the DNS record (e.g., www.example.com)ttl- the time-to-live (TTL) value for the DNS recordtype- the type of the DNS record (e.g., A, AAAA, CNAME)content- the content or value of the DNS record- Returns:
- the created DNS record as a
RecordEntityobject - Throws:
CloudflareApiException- if an error occurs while interacting with the Cloudflare API
-
recordCreate
Creates a new DNS record in the specified zone using the Cloudflare API.- Parameters:
zone- The zone entity where the record will be created. Contains details such as zone ID.rec- The record entity representing the DNS record to be created, including its attributes. Read-only attributes (e.g. ID, timestamps) are ignored, the given object isn't modified.- Returns:
- The created record entity as returned by the Cloudflare API.
- Throws:
CloudflareApiException- If an error occurs while interacting with the Cloudflare API.
-
recordDelete
Deletes a DNS record of the specified type within a given zone on the Cloudflare API.- Parameters:
zone- The zone entity that specifies the zone in which the record exists.rec- The record entity that represents the DNS record to be deleted.- Returns:
trueif the DNS record was successfully deleted;falseotherwise.- Throws:
CloudflareApiException- if there is an issue during the API communication, or the request fails for any reason.
-
recordDelete
Deletes a DNS record of the specified type within a given zone on the Cloudflare API.- Parameters:
zone- The zone entity that specifies the zone in which the record exists.id- The ID of the DNS record to be deleted.- Returns:
trueif the API confirms the deletion of the record with the given ID;falseotherwise.- Throws:
CloudflareApiException- if there is an issue during the API communication or the request fails for any reason.
-
recordUpdate
Updates an existing DNS record in a specified Cloudflare zone (partial update, attributes which arenullremain unchanged).- Parameters:
zone- the zone entity containing the ID of the target zonerec- the record entity containing the ID of the DNS record to be updated and its updated data. Read-only attributes (e.g. timestamps) are ignored, the given object isn't modified.- Returns:
- the updated record entity as returned by the Cloudflare API
- Throws:
CloudflareApiException- if an error occurs while interacting with the Cloudflare API
-
recordDeleteTypeIfExists
public void recordDeleteTypeIfExists(ZoneEntity zone, String subdomain, RecordType... recordTypes) throws CloudflareApiException Attempts to delete DNS records of the specified types within a given zone. If no record types are specified, all types for the subdomain are selected. If no matching record exists, this is treated as a no-op. Deletions are attempted independently; an error deleting an individual record is logged and processing continues. No per-record result is returned, so a normal return does not guarantee that every selected record was deleted.- Parameters:
zone- The DNS zone entity in which the record exists.subdomain- The subdomain relative to the zone for which the records are being checked.recordTypes- The DNS record types to delete; if empty ornull, all types are selected.- Throws:
CloudflareApiException- If an error occurs while retrieving the records to delete.IllegalArgumentException- if the subdomain is blank or contains invalid characters
-
recordBatch
public BatchEntry recordBatch(ZoneEntity zone, @Nullable @Nullable List<RecordEntity> postRecords, @Nullable @Nullable List<RecordEntity> putRecords, @Nullable @Nullable List<RecordEntity> patchRecords, @Nullable @Nullable List<RecordEntity> deleteRecords) throws CloudflareApiException 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, and returns a result containing processed batch entries.- Parameters:
zone- The zone entity to which the records belong.postRecords- A list of DNS records to be created (POST). This parameter is nullable.putRecords- A list of DNS records to be fully replaced (PUT). This parameter is nullable.patchRecords- A list of DNS records to be partially updated (PATCH). This parameter is nullable.deleteRecords- A list of DNS records to be deleted (DELETE), only the IDs are used. This parameter is nullable.- Returns:
- The resulting
BatchEntrycontaining the processed records after the batch operation. - Throws:
CloudflareApiException- If an error occurs while communicating with the Cloudflare API.
-
close
Releases the underlying HTTP client and its connections. The client must not be used anymore afterwards.- Specified by:
closein interfaceAutoCloseable- Throws:
IOException- if an I/O error occurs while closing the HTTP client
-