Class CfDnsClient

java.lang.Object
codes.thischwa.cf.CfDnsClient
All Implemented Interfaces:
AutoCloseable

public class CfDnsClient extends Object
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 with custom base URL:


 CfDnsClient cfDnsClient = new CfDnsClientBuilder()
     .withApiTokenAuth("your-api-token")
     .withBaseUrl("https://custom-api.example.com")
     .build();
 
  • Field Details

  • Method Details

    • groupRecordsByFqdn

      public static Map<String,List<RecordEntity>> groupRecordsByFqdn(List<RecordEntity> records)
      Groups a list of DNS records by their fully qualified domain name (FQDN).
      Parameters:
      records - A list of RecordEntity objects to be grouped by FQDN.
      Returns:
      A map where the key is the FQDN (name field) and the value is a list of RecordEntity objects that share that FQDN.
    • zone

      public ZoneOperations zone(String zoneName) throws CloudflareApiException
      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 exist
      CloudflareApiException - if the zone cannot be accessed
      IllegalArgumentException - if the name is blank or contains invalid characters
    • zoneList

      public List<ZoneEntity> zoneList() throws CloudflareApiException
      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

      public List<ZoneEntity> zoneList(PagingRequest pagingRequest) throws CloudflareApiException
      Retrieves a single page of DNS zones using the provided paging request parameters.
      Parameters:
      pagingRequest - the pagination request object containing parameters for paging and filtering zone data
      Returns:
      a list of ZoneEntity objects representing the DNS zones retrieved from the API
      Throws:
      CloudflareApiException - if there is an error during the API request or response processing
    • zoneGet

      @Nullable public @Nullable ZoneEntity zoneGet(String name) throws CloudflareApiException
      Retrieves detailed information about a specific zone by its name.
      Parameters:
      name - The name of the zone to retrieve information for.
      Returns:
      A ZoneEntity object that contains details of the specified zone, or null if 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

      public List<RecordEntity> recordList(ZoneEntity zone) throws CloudflareApiException
      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. If null, all pages are fetched.
      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"), or APEX for 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 RecordEntity objects representing the DNS records for the specified domain.
      Throws:
      CloudflareNotFoundException - if no records were found and 'emptyResultThrowsException' is enabled
      CloudflareApiException - if an error occurs while interacting with the Cloudflare API
      IllegalArgumentException - if the subdomain is blank or contains invalid characters
    • 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 RecordEntity objects representing the DNS records for the specified zone.
      Throws:
      CloudflareNotFoundException - if no records were found and 'emptyResultThrowsException' is enabled
      CloudflareApiException - 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"), or APEX for 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 or contains invalid characters
    • recordCreateSld

      @Deprecated(since="0.6.0", forRemoval=true) public RecordEntity recordCreateSld(ZoneEntity zone, String subdomain, int ttl, RecordType type, String content) throws CloudflareApiException
      Deprecated, for removal: This API element is subject to removal in a future version.
      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.
      ttl - The time-to-live (TTL) value for the DNS record in seconds.
      type - The RecordType specifying the type of the DNS record.
      content - The content of the DNS record.
      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.
    • 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 created
      name - the name of the DNS record (e.g., www.example.com)
      ttl - the time-to-live (TTL) value for the DNS record
      type - 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 RecordEntity object
      Throws:
      CloudflareApiException - if an error occurs while interacting with the Cloudflare API
    • recordCreate

      public RecordEntity recordCreate(ZoneEntity zone, RecordEntity rec) throws CloudflareApiException
      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

      public boolean recordDelete(ZoneEntity zone, RecordEntity rec) throws CloudflareApiException
      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:
      true if the DNS record was successfully deleted; false otherwise.
      Throws:
      CloudflareApiException - if there is an issue during the API communication, or the request fails for any reason.
    • recordDelete

      public boolean recordDelete(ZoneEntity zone, String id) throws CloudflareApiException
      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:
      true if the API confirms the deletion of the record with the given ID; false otherwise.
      Throws:
      CloudflareApiException - if there is an issue during the API communication or the request fails for any reason.
    • recordUpdate

      public RecordEntity recordUpdate(ZoneEntity zone, RecordEntity rec) throws CloudflareApiException
      Updates an existing DNS record in a specified Cloudflare zone (partial update, attributes which are null remain unchanged).
      Parameters:
      zone - the zone entity containing the ID of the target zone
      rec - 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
      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.
      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 types of DNS records that should be deleted if they exist.
      Throws:
      CloudflareApiException - If an error occurs during API communication.
      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 BatchEntry containing the processed records after the batch operation.
      Throws:
      CloudflareApiException - If an error occurs while communicating with the Cloudflare API.
    • close

      public void close() throws IOException
      Releases the underlying HTTP client and its connections. The client must not be used anymore afterwards.
      Specified by:
      close in interface AutoCloseable
      Throws:
      IOException - if an I/O error occurs while closing the HTTP client