Skip to content

thetradedesk/ttd-workflows-java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ttd-workflows

Developer-friendly & type-safe Java SDK specifically catered to facilitate common workflows on The Trade Desk's platform.

Summary

Workflows Service: This service provides operations for commonly used workflows on The Trade Desk's platform. In addition, this service provides generic operations for submitting:

  • GraphQL API requests
  • REST API requests

For further explanation on the entities encountered in this documentation (e.g., campaigns and ad groups), visit the Partner Portal.

Table of Contents

SDK Installation

Getting started

JDK 11 or later is required.

The samples below show how a published SDK artifact is used:

Gradle:

implementation 'com.thetradedesk:workflows:0.12.0'

Maven:

<dependency>
    <groupId>com.thetradedesk</groupId>
    <artifactId>workflows</artifactId>
    <version>0.12.0</version>
</dependency>

How to build

After cloning the git repository to your file system you can build the SDK artifact from source to the build directory by running ./gradlew build on *nix systems or gradlew.bat on Windows systems.

If you wish to build from source and publish the SDK artifact to your local Maven repository (on your filesystem) then use the following command (after cloning the git repo locally):

On *nix:

./gradlew publishToMavenLocal -Pskip.signing

On Windows:

gradlew.bat publishToMavenLocal -Pskip.signing

SDK Example Usage

Example: Submit job to retrieve third-party data

package hello.world;

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.ThirdPartyDataInput;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.GetThirdPartyDataJobResponse;

public class Main {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .server(Workflows.AvailableServers.SANDBOX)
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
                .build();

        ThirdPartyDataInput req = ThirdPartyDataInput.builder()
                .partnerId("<id>")
                .queryShape("nodes {id name}")
                .build();

        GetThirdPartyDataJobResponse res = sdk.dmp().getThirdPartyDataJob()
                .request(req)
                .call();

        if (res.standardJobSubmitResponse().isPresent()) {
            System.out.println(res.standardJobSubmitResponse().get());
        }
    }
}

(Reference)

Example: Check status for third-party data retrieval job using job ID returned from submit job

package hello.world;

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.GetJobStatusResponse;

public class Main {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .server(Workflows.AvailableServers.SANDBOX)
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
                .build();

        GetJobStatusResponse res = sdk.jobStatus().getJobStatus()
                .id(<id>)
                .call();

        if (res.standardJobStatusResponse().isPresent()) {
            System.out.println(res.standardJobStatusResponse().get());
        }
    }
}

(Reference)

Example: Create campaign with minimal configuration

package hello.world;

import java.time.OffsetDateTime;
import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.*;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.CreateCampaignResponse;

public class Main {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .server(Workflows.AvailableServers.SANDBOX)
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
                .build();

        CampaignCreateWorkflowInputWithValidation req = CampaignCreateWorkflowInputWithValidation
                .builder()
                .primaryInput(CampaignCreateWorkflowPrimaryInput.builder()
                    .name("<value>")
                    .advertiserId("<id>")
                    .seedId("<id>") // required, unless the advertiser has a default seed defined
                    .startDateInUtc(OffsetDateTime.parse("2026-07-08T10:52:56.944Z"))
                    .primaryChannel(CampaignChannelType.DOOH)
                    .primaryGoal(CampaignWorkflowROIGoalInput.builder()
                        .maximizeReach(true)
                        .build())
                    .build())
                .build();

        CreateCampaignResponse res = sdk.campaign().create()
                .request(req)
                .call();

        if (res.campaignPayload().isPresent()) {
            System.out.println(res.campaignPayload().get());
        }
    }
}

(Reference)

Example: Submit GraphQL request

package hello.world;

import java.lang.Exception;
import java.util.Map;
import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.GraphQLRequestInput;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.SubmitGraphQlRequestResponse;

public class Main {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .server(Workflows.AvailableServers.SANDBOX)
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
                .build();

        String query = """
query Advertiser($id: ID!) {
    advertiser(id: $id) {
        name
        totalCampaignChannelCount
        totalFunnelLocationCount
        useImpressionsOnlyBudgeting
        vettingStatus
        suggestedMeasurementProviderCategories
    }
}
""";

        GraphQLRequestInput req = GraphQLRequestInput.builder()
                .request(query)
                .variables(Map.ofEntries(
                        Map.entry("id", "<id>")
                        ))
                .build();

        SubmitGraphQlRequestResponse res = sdk.graphQLRequest().submitGraphQlRequest()
                .request(req)
                .call();

        if (res.object().isPresent()) {
            System.out.println(res.object().get());
        }
    }
}

(Reference)

Example: Submit bulk GraphQL query job

Note: If you submit a GraphQL bulk query job (instead of a standard GraphQL request as shown above), any paginated and nested data is fully iterated and returned in a single output file.

package hello.world;

import java.lang.Exception;
import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.GraphQlQueryJobInput;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.SubmitGraphQlQueryJobResponse;

public class Main {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .server(Workflows.AvailableServers.SANDBOX)
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
                .build();

        String query = """
query AudiencesAcrossAdvertisers {
  partner(id: "<id>") {
    id
    name
    advertisers {
      nodes {
        id
        name
        adGroups {
          nodes {
            id
            name
            audience {
              id
              name
              activeUniques {
                householdCount
                idsConnectedTvCount
                idsCount
                idsInAppCount
                idsWebCount
                lastUpdated
                personsCount
              }
            }
          }
        }
      }
    }
  }
}
""";

        GraphQlQueryJobInput req = GraphQlQueryJobInput.builder()
                .query(query)
                .build();

        SubmitGraphQlQueryJobResponse res = sdk.graphQLRequest().submitGraphQlQueryJob()
                .request(req)
                .call();

        if (res.graphQlQueryJobResponse().isPresent()) {
            System.out.println(res.graphQlQueryJobResponse().get());
        }
    }
}

(Reference)

Example: Check status for bulk GraphQL query job

package hello.world;

import java.lang.Exception;
import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.operations.GetGraphQlQueryJobStatusResponse;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;

public class Main {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .server(Workflows.AvailableServers.SANDBOX)
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
                .build();

        GetGraphQlQueryJobStatusResponse res = sdk.jobStatus().getGraphQlQueryJobStatus()
                .id("<id>")
                .call();

        if (res.graphQLQueryJobRetrievalResponse().isPresent()) {
            System.out.println(res.graphQLQueryJobRetrievalResponse().get());
        }
    }
}

(Reference)

Example: Submit REST request (GET)

package hello.world;

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.CallRestApiWorkflowInput;
import com.thetradedesk.workflows.models.components.RestApiMethodType;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.SubmitRestRequestResponse;

public class Main {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .server(Workflows.AvailableServers.SANDBOX)
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
                .build();

        CallRestApiWorkflowInput req = CallRestApiWorkflowInput.builder()
                .methodType(RestApiMethodType.GET)
                .endpoint("campaign/<id>")
                .build();

        SubmitRestRequestResponse res = sdk.restRequest().submitRestRequest()
                .request(req)
                .call();

        if (res.object().isPresent()) {
            System.out.println(res.object());
        }
    }
}

(Reference)

Example: Submit REST request (PUT/POST)

NOTE: PUT/POST syntax is equivalent to GET, with the additional .dataBody method called.

package hello.world;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.CallRestApiWorkflowInput;
import com.thetradedesk.workflows.models.components.RestApiMethodType;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.SubmitRestRequestResponse;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"));

        Map<String, Object> dataBodyMap = new HashMap<>();
        dataBodyMap.put("adGroupId", "<id>");
        dataBodyMap.put("description", "updated by Java SDK: " + now);

        ObjectMapper mapper = new ObjectMapper();
        String dataBodyJson = mapper.writeValueAsString(dataBodyMap);

        Workflows sdk = Workflows.builder()
                .server(Workflows.AvailableServers.SANDBOX)
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
                .build();

        CallRestApiWorkflowInput req = CallRestApiWorkflowInput.builder()
                .methodType(RestApiMethodType.PUT)
                .endpoint("adgroup")
                .dataBody(dataBodyJson)
                .build();

        SubmitRestRequestResponse res = sdk.restRequest().submitRestRequest()
                .request(req)
                .call();

        if (res.object().isPresent()) {
            System.out.println(res.object());
        }
    }
}

Asynchronous Support

The SDK provides comprehensive asynchronous support using Java's CompletableFuture<T> and Reactive Streams Publisher<T> APIs. This design makes no assumptions about your choice of reactive toolkit, allowing seamless integration with any reactive library.

Why Use Async?

Asynchronous operations provide several key benefits:

  • Non-blocking I/O: Your threads stay free for other work while operations are in flight
  • Better resource utilization: Handle more concurrent operations with fewer threads
  • Improved scalability: Build highly responsive applications that can handle thousands of concurrent requests
  • Reactive integration: Works seamlessly with reactive streams and backpressure handling
Reactive Library Integration

The SDK returns Reactive Streams Publisher<T> instances for operations dealing with streams involving multiple I/O interactions. We use Reactive Streams instead of JDK Flow API to provide broader compatibility with the reactive ecosystem, as most reactive libraries natively support Reactive Streams.

Why Reactive Streams over JDK Flow?

  • Broader ecosystem compatibility: Most reactive libraries (Project Reactor, RxJava, Akka Streams, etc.) natively support Reactive Streams
  • Industry standard: Reactive Streams is the de facto standard for reactive programming in Java
  • Better interoperability: Seamless integration without additional adapters for most use cases

Integration with Popular Libraries:

  • Project Reactor: Use Flux.from(publisher) to convert to Reactor types
  • RxJava: Use Flowable.fromPublisher(publisher) for RxJava integration
  • Akka Streams: Use Source.fromPublisher(publisher) for Akka Streams integration
  • Vert.x: Use ReadStream.fromPublisher(vertx, publisher) for Vert.x reactive streams
  • Mutiny: Use Multi.createFrom().publisher(publisher) for Quarkus Mutiny integration

For JDK Flow API Integration: If you need JDK Flow API compatibility (e.g., for Quarkus/Mutiny 2), you can use adapters:

// Convert Reactive Streams Publisher to Flow Publisher
Flow.Publisher<T> flowPublisher = FlowAdapters.toFlowPublisher(reactiveStreamsPublisher);

// Convert Flow Publisher to Reactive Streams Publisher
Publisher<T> reactiveStreamsPublisher = FlowAdapters.toPublisher(flowPublisher);

For standard single-response operations, the SDK returns CompletableFuture<T> for straightforward async execution.

Supported Operations

Async support is available for:

  • Server-sent Events: Stream real-time events with Reactive Streams Publisher<T>
  • JSONL Streaming: Process streaming JSON lines asynchronously
  • Pagination: Iterate through paginated results using callAsPublisher() and callAsPublisherUnwrapped()
  • File Uploads: Upload files asynchronously with progress tracking
  • File Downloads: Download files asynchronously with streaming support
  • Standard Operations: All regular API calls return CompletableFuture<T> for async execution

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme Environment Variable
ttdAuth apiKey API key WORKFLOWS_TTD_AUTH

To authenticate with the API the ttdAuth parameter must be set when initializing the SDK client instance. For example:

package hello.world;

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.*;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.CreateAdGroupResponse;
import java.lang.Exception;
import java.util.List;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;

public class Application {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
            .build();

        AdGroupCreateWorkflowInputWithValidation req = AdGroupCreateWorkflowInputWithValidation.builder()
                .primaryInput(AdGroupCreateWorkflowPrimaryInput.builder()
                    .name("<value>")
                    .channel(AdGroupChannel.DISPLAY)
                    .funnelLocation(AdGroupFunnelLocation.CONSIDERATION)
                    .isEnabled(false)
                    .description("twine from gosh poor safely editor astride vice lost and")
                    .budget(AdGroupWorkflowBudgetInput.builder()
                        .allocationType(AllocationType.MAXIMUM)
                        .budgetInAdvertiserCurrency(3786.02)
                        .budgetInImpressions(783190L)
                        .dailyTargetInAdvertiserCurrency(9747.02)
                        .dailyTargetInImpressions(985999L)
                        .build())
                    .baseBidCPMInAdvertiserCurrency(3785.04)
                    .maxBidCPMInAdvertiserCurrency(7447.3)
                    .audienceTargeting(AdGroupWorkflowAudienceTargetingInput.builder()
                        .audienceId("<id>")
                        .audienceAcceleratorExclusionsEnabled(true)
                        .audienceBoosterEnabled(true)
                        .audienceExcluderEnabled(true)
                        .audiencePredictorEnabled(false)
                        .crossDeviceVendorListForAudience(List.of(
                            107263))
                        .recencyExclusionWindowInMinutes(90062)
                        .targetTrackableUsersEnabled(true)
                        .useMcIdAsPrimary(true)
                        .build())
                    .roiGoal(AdGroupWorkflowROIGoalInput.builder()
                        .maximizeReach(true)
                        .maximizeLtvIncrementalReach(false)
                        .cpcInAdvertiserCurrency(2280.31)
                        .ctrInPercent(JsonNullable.of(null))
                        .nielsenOTPInPercent(5175.21)
                        .cpaInAdvertiserCurrency(2544.37)
                        .returnOnAdSpendPercent(8201.47)
                        .vcrInPercent(4846.08)
                        .viewabilityInPercent(JsonNullable.of(null))
                        .vcpmInAdvertiserCurrency(4649.53)
                        .cpcvInAdvertiserCurrency(313.95)
                        .miaozhenOTPInPercent(4704.1)
                        .build())
                    .creativeIds(JsonNullable.of(null))
                    .associatedBidLists(List.of(
                        AdGroupWorkflowAssociateBidListInput.builder()
                            .bidListId("<id>")
                            .isEnabled(false)
                            .isDefaultForDimension(true)
                            .build()))
                    .marketType(MarketType.PRIVATE_MARKET_ONLY)
                    .programmaticGuaranteedPrivateContractId("<id>")
                    .includeDefaultsFromCampaign(false)
                    .build())
                .campaignId("<id>")
                .advancedInput(AdGroupWorkflowAdvancedInput.builder()
                    .koaOptimizationSettings(AdGroupWorkflowKoaOptimizationSettingsInput.builder()
                        .areFutureKoaFeaturesEnabled(false)
                        .predictiveClearingEnabled(false)
                        .build())
                    .comscoreSettings(AdGroupWorkflowComscoreSettingsInput.builder()
                        .isEnabled(false)
                        .populationId(JsonNullable.of(null))
                        .demographicMemberIds(List.of(
                            959580,
                            236376))
                        .mobileDemographicMemberIds(List.of(
                            664689,
                            827980,
                            21321))
                        .build())
                    .contractTargeting(AdGroupWorkflowContractTargetingInput.builder()
                        .allowOpenMarketBiddingWhenTargetingContracts(true)
                        .build())
                    .dimensionalBiddingAutoOptimizationSettings(List.of(
                        List.of(),
                        List.of()))
                    .isUseClicksAsConversionsEnabled(false)
                    .isUseSecondaryConversionsEnabled(false)
                    .nielsenTrackingAttributes(AdGroupWorkflowNielsenTrackingAttributesInput.builder()
                        .gender(TargetingGenderInput.MALE)
                        .startAge(TargetingStartAgeInput.TWENTY_FIVE)
                        .endAge(TargetingEndAgeInput.SEVENTEEN)
                        .countries(List.of(
                            "<value 1>",
                            "<value 2>",
                            "<value 3>"))
                        .enhancedReportingOption(EnhancedNielsenReportingOptionsInput.SITE)
                        .build())
                    .newFrequencyConfigs(List.of(
                        AdGroupWorkflowNewFrequencyConfigInput.builder()
                            .counterName(Optional.empty())
                            .frequencyCap(375286)
                            .frequencyGoal(534735)
                            .resetIntervalInMinutes(788122)
                            .build()))
                    .flights(List.of(
                        AdGroupWorkflowFlightInput.builder()
                            .campaignFlightId(874887L)
                            .allocationType(AllocationType.MAXIMUM)
                            .budgetInAdvertiserCurrency(4070.96)
                            .budgetInImpressions(901477L)
                            .dailyTargetInAdvertiserCurrency(5847.35)
                            .dailyTargetInImpressions(257517L)
                            .build()))
                    .callerSource("<value>")
                    .build())
                .validateInputOnly(true)
                .build();

        CreateAdGroupResponse res = sdk.adGroup().createAdGroup()
                .request(req)
                .call();

        if (res.adGroupPayload().isPresent()) {
            // handle response
        }
    }
}

Available Resources and Operations

Available methods

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, you can provide a RetryConfig object through the retryConfig builder method:

package hello.world;

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.*;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.CreateAdGroupResponse;
import com.thetradedesk.workflows.utils.BackoffStrategy;
import com.thetradedesk.workflows.utils.RetryConfig;
import java.lang.Exception;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.openapitools.jackson.nullable.JsonNullable;

public class Application {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
            .build();

        AdGroupCreateWorkflowInputWithValidation req = AdGroupCreateWorkflowInputWithValidation.builder()
                .primaryInput(AdGroupCreateWorkflowPrimaryInput.builder()
                    .name("<value>")
                    .channel(AdGroupChannel.DISPLAY)
                    .funnelLocation(AdGroupFunnelLocation.CONSIDERATION)
                    .isEnabled(false)
                    .description("twine from gosh poor safely editor astride vice lost and")
                    .budget(AdGroupWorkflowBudgetInput.builder()
                        .allocationType(AllocationType.MAXIMUM)
                        .budgetInAdvertiserCurrency(3786.02)
                        .budgetInImpressions(783190L)
                        .dailyTargetInAdvertiserCurrency(9747.02)
                        .dailyTargetInImpressions(985999L)
                        .build())
                    .baseBidCPMInAdvertiserCurrency(3785.04)
                    .maxBidCPMInAdvertiserCurrency(7447.3)
                    .audienceTargeting(AdGroupWorkflowAudienceTargetingInput.builder()
                        .audienceId("<id>")
                        .audienceAcceleratorExclusionsEnabled(true)
                        .audienceBoosterEnabled(true)
                        .audienceExcluderEnabled(true)
                        .audiencePredictorEnabled(false)
                        .crossDeviceVendorListForAudience(List.of(
                            107263))
                        .recencyExclusionWindowInMinutes(90062)
                        .targetTrackableUsersEnabled(true)
                        .useMcIdAsPrimary(true)
                        .build())
                    .roiGoal(AdGroupWorkflowROIGoalInput.builder()
                        .maximizeReach(true)
                        .maximizeLtvIncrementalReach(false)
                        .cpcInAdvertiserCurrency(2280.31)
                        .ctrInPercent(JsonNullable.of(null))
                        .nielsenOTPInPercent(5175.21)
                        .cpaInAdvertiserCurrency(2544.37)
                        .returnOnAdSpendPercent(8201.47)
                        .vcrInPercent(4846.08)
                        .viewabilityInPercent(JsonNullable.of(null))
                        .vcpmInAdvertiserCurrency(4649.53)
                        .cpcvInAdvertiserCurrency(313.95)
                        .miaozhenOTPInPercent(4704.1)
                        .build())
                    .creativeIds(JsonNullable.of(null))
                    .associatedBidLists(List.of(
                        AdGroupWorkflowAssociateBidListInput.builder()
                            .bidListId("<id>")
                            .isEnabled(false)
                            .isDefaultForDimension(true)
                            .build()))
                    .marketType(MarketType.PRIVATE_MARKET_ONLY)
                    .programmaticGuaranteedPrivateContractId("<id>")
                    .includeDefaultsFromCampaign(false)
                    .build())
                .campaignId("<id>")
                .advancedInput(AdGroupWorkflowAdvancedInput.builder()
                    .koaOptimizationSettings(AdGroupWorkflowKoaOptimizationSettingsInput.builder()
                        .areFutureKoaFeaturesEnabled(false)
                        .predictiveClearingEnabled(false)
                        .build())
                    .comscoreSettings(AdGroupWorkflowComscoreSettingsInput.builder()
                        .isEnabled(false)
                        .populationId(JsonNullable.of(null))
                        .demographicMemberIds(List.of(
                            959580,
                            236376))
                        .mobileDemographicMemberIds(List.of(
                            664689,
                            827980,
                            21321))
                        .build())
                    .contractTargeting(AdGroupWorkflowContractTargetingInput.builder()
                        .allowOpenMarketBiddingWhenTargetingContracts(true)
                        .build())
                    .dimensionalBiddingAutoOptimizationSettings(List.of(
                        List.of(),
                        List.of()))
                    .isUseClicksAsConversionsEnabled(false)
                    .isUseSecondaryConversionsEnabled(false)
                    .nielsenTrackingAttributes(AdGroupWorkflowNielsenTrackingAttributesInput.builder()
                        .gender(TargetingGenderInput.MALE)
                        .startAge(TargetingStartAgeInput.TWENTY_FIVE)
                        .endAge(TargetingEndAgeInput.SEVENTEEN)
                        .countries(List.of(
                            "<value 1>",
                            "<value 2>",
                            "<value 3>"))
                        .enhancedReportingOption(EnhancedNielsenReportingOptionsInput.SITE)
                        .build())
                    .newFrequencyConfigs(List.of(
                        AdGroupWorkflowNewFrequencyConfigInput.builder()
                            .counterName(Optional.empty())
                            .frequencyCap(375286)
                            .frequencyGoal(534735)
                            .resetIntervalInMinutes(788122)
                            .build()))
                    .flights(List.of(
                        AdGroupWorkflowFlightInput.builder()
                            .campaignFlightId(874887L)
                            .allocationType(AllocationType.MAXIMUM)
                            .budgetInAdvertiserCurrency(4070.96)
                            .budgetInImpressions(901477L)
                            .dailyTargetInAdvertiserCurrency(5847.35)
                            .dailyTargetInImpressions(257517L)
                            .build()))
                    .callerSource("<value>")
                    .build())
                .validateInputOnly(true)
                .build();

        CreateAdGroupResponse res = sdk.adGroup().createAdGroup()
                .request(req)
                .retryConfig(RetryConfig.builder()
                    .backoff(BackoffStrategy.builder()
                        .initialInterval(1L, TimeUnit.MILLISECONDS)
                        .maxInterval(50L, TimeUnit.MILLISECONDS)
                        .maxElapsedTime(1000L, TimeUnit.MILLISECONDS)
                        .baseFactor(1.1)
                        .jitterFactor(0.15)
                        .retryConnectError(false)
                        .build())
                    .build())
                .call();

        if (res.adGroupPayload().isPresent()) {
            // handle response
        }
    }
}

If you'd like to override the default retry strategy for all operations that support retries, you can provide a configuration at SDK initialization:

package hello.world;

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.*;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.CreateAdGroupResponse;
import com.thetradedesk.workflows.utils.BackoffStrategy;
import com.thetradedesk.workflows.utils.RetryConfig;
import java.lang.Exception;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.openapitools.jackson.nullable.JsonNullable;

public class Application {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .retryConfig(RetryConfig.builder()
                    .backoff(BackoffStrategy.builder()
                        .initialInterval(1L, TimeUnit.MILLISECONDS)
                        .maxInterval(50L, TimeUnit.MILLISECONDS)
                        .maxElapsedTime(1000L, TimeUnit.MILLISECONDS)
                        .baseFactor(1.1)
                        .jitterFactor(0.15)
                        .retryConnectError(false)
                        .build())
                    .build())
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
            .build();

        AdGroupCreateWorkflowInputWithValidation req = AdGroupCreateWorkflowInputWithValidation.builder()
                .primaryInput(AdGroupCreateWorkflowPrimaryInput.builder()
                    .name("<value>")
                    .channel(AdGroupChannel.DISPLAY)
                    .funnelLocation(AdGroupFunnelLocation.CONSIDERATION)
                    .isEnabled(false)
                    .description("twine from gosh poor safely editor astride vice lost and")
                    .budget(AdGroupWorkflowBudgetInput.builder()
                        .allocationType(AllocationType.MAXIMUM)
                        .budgetInAdvertiserCurrency(3786.02)
                        .budgetInImpressions(783190L)
                        .dailyTargetInAdvertiserCurrency(9747.02)
                        .dailyTargetInImpressions(985999L)
                        .build())
                    .baseBidCPMInAdvertiserCurrency(3785.04)
                    .maxBidCPMInAdvertiserCurrency(7447.3)
                    .audienceTargeting(AdGroupWorkflowAudienceTargetingInput.builder()
                        .audienceId("<id>")
                        .audienceAcceleratorExclusionsEnabled(true)
                        .audienceBoosterEnabled(true)
                        .audienceExcluderEnabled(true)
                        .audiencePredictorEnabled(false)
                        .crossDeviceVendorListForAudience(List.of(
                            107263))
                        .recencyExclusionWindowInMinutes(90062)
                        .targetTrackableUsersEnabled(true)
                        .useMcIdAsPrimary(true)
                        .build())
                    .roiGoal(AdGroupWorkflowROIGoalInput.builder()
                        .maximizeReach(true)
                        .maximizeLtvIncrementalReach(false)
                        .cpcInAdvertiserCurrency(2280.31)
                        .ctrInPercent(JsonNullable.of(null))
                        .nielsenOTPInPercent(5175.21)
                        .cpaInAdvertiserCurrency(2544.37)
                        .returnOnAdSpendPercent(8201.47)
                        .vcrInPercent(4846.08)
                        .viewabilityInPercent(JsonNullable.of(null))
                        .vcpmInAdvertiserCurrency(4649.53)
                        .cpcvInAdvertiserCurrency(313.95)
                        .miaozhenOTPInPercent(4704.1)
                        .build())
                    .creativeIds(JsonNullable.of(null))
                    .associatedBidLists(List.of(
                        AdGroupWorkflowAssociateBidListInput.builder()
                            .bidListId("<id>")
                            .isEnabled(false)
                            .isDefaultForDimension(true)
                            .build()))
                    .marketType(MarketType.PRIVATE_MARKET_ONLY)
                    .programmaticGuaranteedPrivateContractId("<id>")
                    .includeDefaultsFromCampaign(false)
                    .build())
                .campaignId("<id>")
                .advancedInput(AdGroupWorkflowAdvancedInput.builder()
                    .koaOptimizationSettings(AdGroupWorkflowKoaOptimizationSettingsInput.builder()
                        .areFutureKoaFeaturesEnabled(false)
                        .predictiveClearingEnabled(false)
                        .build())
                    .comscoreSettings(AdGroupWorkflowComscoreSettingsInput.builder()
                        .isEnabled(false)
                        .populationId(JsonNullable.of(null))
                        .demographicMemberIds(List.of(
                            959580,
                            236376))
                        .mobileDemographicMemberIds(List.of(
                            664689,
                            827980,
                            21321))
                        .build())
                    .contractTargeting(AdGroupWorkflowContractTargetingInput.builder()
                        .allowOpenMarketBiddingWhenTargetingContracts(true)
                        .build())
                    .dimensionalBiddingAutoOptimizationSettings(List.of(
                        List.of(),
                        List.of()))
                    .isUseClicksAsConversionsEnabled(false)
                    .isUseSecondaryConversionsEnabled(false)
                    .nielsenTrackingAttributes(AdGroupWorkflowNielsenTrackingAttributesInput.builder()
                        .gender(TargetingGenderInput.MALE)
                        .startAge(TargetingStartAgeInput.TWENTY_FIVE)
                        .endAge(TargetingEndAgeInput.SEVENTEEN)
                        .countries(List.of(
                            "<value 1>",
                            "<value 2>",
                            "<value 3>"))
                        .enhancedReportingOption(EnhancedNielsenReportingOptionsInput.SITE)
                        .build())
                    .newFrequencyConfigs(List.of(
                        AdGroupWorkflowNewFrequencyConfigInput.builder()
                            .counterName(Optional.empty())
                            .frequencyCap(375286)
                            .frequencyGoal(534735)
                            .resetIntervalInMinutes(788122)
                            .build()))
                    .flights(List.of(
                        AdGroupWorkflowFlightInput.builder()
                            .campaignFlightId(874887L)
                            .allocationType(AllocationType.MAXIMUM)
                            .budgetInAdvertiserCurrency(4070.96)
                            .budgetInImpressions(901477L)
                            .dailyTargetInAdvertiserCurrency(5847.35)
                            .dailyTargetInImpressions(257517L)
                            .build()))
                    .callerSource("<value>")
                    .build())
                .validateInputOnly(true)
                .build();

        CreateAdGroupResponse res = sdk.adGroup().createAdGroup()
                .request(req)
                .call();

        if (res.adGroupPayload().isPresent()) {
            // handle response
        }
    }
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.

WorkflowsError is the base class for all HTTP error responses. It has the following properties:

Method Type Description
message() String Error message
code() int HTTP response status code eg 404
headers Map<String, List<String>> HTTP response headers
body() byte[] HTTP body as a byte array. Can be empty array if no body is returned.
bodyAsString() String HTTP body as a UTF-8 string. Can be empty string if no body is returned.
rawResponse() HttpResponse<?> Raw HTTP response (body already read and not available for re-read)

Example

package hello.world;

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.*;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.errors.WorkflowsError;
import com.thetradedesk.workflows.models.operations.CreateAdGroupResponse;
import java.io.UncheckedIOException;
import java.lang.Exception;
import java.lang.String;
import java.util.List;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;

public class Application {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
            .build();
        try {

            AdGroupCreateWorkflowInputWithValidation req = AdGroupCreateWorkflowInputWithValidation.builder()
                    .primaryInput(AdGroupCreateWorkflowPrimaryInput.builder()
                        .name("<value>")
                        .channel(AdGroupChannel.DISPLAY)
                        .funnelLocation(AdGroupFunnelLocation.CONSIDERATION)
                        .isEnabled(false)
                        .description("twine from gosh poor safely editor astride vice lost and")
                        .budget(AdGroupWorkflowBudgetInput.builder()
                            .allocationType(AllocationType.MAXIMUM)
                            .budgetInAdvertiserCurrency(3786.02)
                            .budgetInImpressions(783190L)
                            .dailyTargetInAdvertiserCurrency(9747.02)
                            .dailyTargetInImpressions(985999L)
                            .build())
                        .baseBidCPMInAdvertiserCurrency(3785.04)
                        .maxBidCPMInAdvertiserCurrency(7447.3)
                        .audienceTargeting(AdGroupWorkflowAudienceTargetingInput.builder()
                            .audienceId("<id>")
                            .audienceAcceleratorExclusionsEnabled(true)
                            .audienceBoosterEnabled(true)
                            .audienceExcluderEnabled(true)
                            .audiencePredictorEnabled(false)
                            .crossDeviceVendorListForAudience(List.of(
                                107263))
                            .recencyExclusionWindowInMinutes(90062)
                            .targetTrackableUsersEnabled(true)
                            .useMcIdAsPrimary(true)
                            .build())
                        .roiGoal(AdGroupWorkflowROIGoalInput.builder()
                            .maximizeReach(true)
                            .maximizeLtvIncrementalReach(false)
                            .cpcInAdvertiserCurrency(2280.31)
                            .ctrInPercent(JsonNullable.of(null))
                            .nielsenOTPInPercent(5175.21)
                            .cpaInAdvertiserCurrency(2544.37)
                            .returnOnAdSpendPercent(8201.47)
                            .vcrInPercent(4846.08)
                            .viewabilityInPercent(JsonNullable.of(null))
                            .vcpmInAdvertiserCurrency(4649.53)
                            .cpcvInAdvertiserCurrency(313.95)
                            .miaozhenOTPInPercent(4704.1)
                            .build())
                        .creativeIds(JsonNullable.of(null))
                        .associatedBidLists(List.of(
                            AdGroupWorkflowAssociateBidListInput.builder()
                                .bidListId("<id>")
                                .isEnabled(false)
                                .isDefaultForDimension(true)
                                .build()))
                        .marketType(MarketType.PRIVATE_MARKET_ONLY)
                        .programmaticGuaranteedPrivateContractId("<id>")
                        .includeDefaultsFromCampaign(false)
                        .build())
                    .campaignId("<id>")
                    .advancedInput(AdGroupWorkflowAdvancedInput.builder()
                        .koaOptimizationSettings(AdGroupWorkflowKoaOptimizationSettingsInput.builder()
                            .areFutureKoaFeaturesEnabled(false)
                            .predictiveClearingEnabled(false)
                            .build())
                        .comscoreSettings(AdGroupWorkflowComscoreSettingsInput.builder()
                            .isEnabled(false)
                            .populationId(JsonNullable.of(null))
                            .demographicMemberIds(List.of(
                                959580,
                                236376))
                            .mobileDemographicMemberIds(List.of(
                                664689,
                                827980,
                                21321))
                            .build())
                        .contractTargeting(AdGroupWorkflowContractTargetingInput.builder()
                            .allowOpenMarketBiddingWhenTargetingContracts(true)
                            .build())
                        .dimensionalBiddingAutoOptimizationSettings(List.of(
                            List.of(),
                            List.of()))
                        .isUseClicksAsConversionsEnabled(false)
                        .isUseSecondaryConversionsEnabled(false)
                        .nielsenTrackingAttributes(AdGroupWorkflowNielsenTrackingAttributesInput.builder()
                            .gender(TargetingGenderInput.MALE)
                            .startAge(TargetingStartAgeInput.TWENTY_FIVE)
                            .endAge(TargetingEndAgeInput.SEVENTEEN)
                            .countries(List.of(
                                "<value 1>",
                                "<value 2>",
                                "<value 3>"))
                            .enhancedReportingOption(EnhancedNielsenReportingOptionsInput.SITE)
                            .build())
                        .newFrequencyConfigs(List.of(
                            AdGroupWorkflowNewFrequencyConfigInput.builder()
                                .counterName(Optional.empty())
                                .frequencyCap(375286)
                                .frequencyGoal(534735)
                                .resetIntervalInMinutes(788122)
                                .build()))
                        .flights(List.of(
                            AdGroupWorkflowFlightInput.builder()
                                .campaignFlightId(874887L)
                                .allocationType(AllocationType.MAXIMUM)
                                .budgetInAdvertiserCurrency(4070.96)
                                .budgetInImpressions(901477L)
                                .dailyTargetInAdvertiserCurrency(5847.35)
                                .dailyTargetInImpressions(257517L)
                                .build()))
                        .callerSource("<value>")
                        .build())
                    .validateInputOnly(true)
                    .build();

            CreateAdGroupResponse res = sdk.adGroup().createAdGroup()
                    .request(req)
                    .call();

            if (res.adGroupPayload().isPresent()) {
                // handle response
            }
        } catch (WorkflowsError ex) { // all SDK exceptions inherit from WorkflowsError

            // ex.ToString() provides a detailed error message including
            // HTTP status code, headers, and error payload (if any)
            System.out.println(ex);

            // Base exception fields
            var rawResponse = ex.rawResponse();
            var headers = ex.headers();
            var contentType = headers.first("Content-Type");
            int statusCode = ex.code();
            Optional<byte[]> responseBody = ex.body();

            // different error subclasses may be thrown 
            // depending on the service call
            if (ex instanceof ProblemDetailsException) {
                var e = (ProblemDetailsException) ex;
                // Check error data fields
                e.data().ifPresent(payload -> {
                      JsonNullable<String> type = payload.type();
                      JsonNullable<String> title = payload.title();
                      // ...
                });
            }

            // An underlying cause may be provided. If the error payload 
            // cannot be deserialized then the deserialization exception 
            // will be set as the cause.
            if (ex.getCause() != null) {
                var cause = ex.getCause();
            }
        } catch (UncheckedIOException ex) {
            // handle IO error (connection, timeout, etc)
        }    }
}

Error Classes

Primary errors:

Less common errors (6)

Network errors:

  • java.io.IOException (always wrapped by java.io.UncheckedIOException). Commonly encountered subclasses of IOException include java.net.ConnectException, java.net.SocketTimeoutException, EOFException (there are many more subclasses in the JDK platform).

Inherit from WorkflowsError:

Server Selection

Select Server by Name

You can override the default server globally using the .server(AvailableServers server) builder method when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:

Name Server Description
prod https://api.thetradedesk.com/workflows The production environment.
sandbox https://ext-api.sb.thetradedesk.com/workflows The sandbox environment for testing.

Example

package hello.world;

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.*;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.CreateAdGroupResponse;
import java.lang.Exception;
import java.util.List;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;

public class Application {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .server(Workflows.AvailableServers.PROD)
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
            .build();

        AdGroupCreateWorkflowInputWithValidation req = AdGroupCreateWorkflowInputWithValidation.builder()
                .primaryInput(AdGroupCreateWorkflowPrimaryInput.builder()
                    .name("<value>")
                    .channel(AdGroupChannel.DISPLAY)
                    .funnelLocation(AdGroupFunnelLocation.CONSIDERATION)
                    .isEnabled(false)
                    .description("twine from gosh poor safely editor astride vice lost and")
                    .budget(AdGroupWorkflowBudgetInput.builder()
                        .allocationType(AllocationType.MAXIMUM)
                        .budgetInAdvertiserCurrency(3786.02)
                        .budgetInImpressions(783190L)
                        .dailyTargetInAdvertiserCurrency(9747.02)
                        .dailyTargetInImpressions(985999L)
                        .build())
                    .baseBidCPMInAdvertiserCurrency(3785.04)
                    .maxBidCPMInAdvertiserCurrency(7447.3)
                    .audienceTargeting(AdGroupWorkflowAudienceTargetingInput.builder()
                        .audienceId("<id>")
                        .audienceAcceleratorExclusionsEnabled(true)
                        .audienceBoosterEnabled(true)
                        .audienceExcluderEnabled(true)
                        .audiencePredictorEnabled(false)
                        .crossDeviceVendorListForAudience(List.of(
                            107263))
                        .recencyExclusionWindowInMinutes(90062)
                        .targetTrackableUsersEnabled(true)
                        .useMcIdAsPrimary(true)
                        .build())
                    .roiGoal(AdGroupWorkflowROIGoalInput.builder()
                        .maximizeReach(true)
                        .maximizeLtvIncrementalReach(false)
                        .cpcInAdvertiserCurrency(2280.31)
                        .ctrInPercent(JsonNullable.of(null))
                        .nielsenOTPInPercent(5175.21)
                        .cpaInAdvertiserCurrency(2544.37)
                        .returnOnAdSpendPercent(8201.47)
                        .vcrInPercent(4846.08)
                        .viewabilityInPercent(JsonNullable.of(null))
                        .vcpmInAdvertiserCurrency(4649.53)
                        .cpcvInAdvertiserCurrency(313.95)
                        .miaozhenOTPInPercent(4704.1)
                        .build())
                    .creativeIds(JsonNullable.of(null))
                    .associatedBidLists(List.of(
                        AdGroupWorkflowAssociateBidListInput.builder()
                            .bidListId("<id>")
                            .isEnabled(false)
                            .isDefaultForDimension(true)
                            .build()))
                    .marketType(MarketType.PRIVATE_MARKET_ONLY)
                    .programmaticGuaranteedPrivateContractId("<id>")
                    .includeDefaultsFromCampaign(false)
                    .build())
                .campaignId("<id>")
                .advancedInput(AdGroupWorkflowAdvancedInput.builder()
                    .koaOptimizationSettings(AdGroupWorkflowKoaOptimizationSettingsInput.builder()
                        .areFutureKoaFeaturesEnabled(false)
                        .predictiveClearingEnabled(false)
                        .build())
                    .comscoreSettings(AdGroupWorkflowComscoreSettingsInput.builder()
                        .isEnabled(false)
                        .populationId(JsonNullable.of(null))
                        .demographicMemberIds(List.of(
                            959580,
                            236376))
                        .mobileDemographicMemberIds(List.of(
                            664689,
                            827980,
                            21321))
                        .build())
                    .contractTargeting(AdGroupWorkflowContractTargetingInput.builder()
                        .allowOpenMarketBiddingWhenTargetingContracts(true)
                        .build())
                    .dimensionalBiddingAutoOptimizationSettings(List.of(
                        List.of(),
                        List.of()))
                    .isUseClicksAsConversionsEnabled(false)
                    .isUseSecondaryConversionsEnabled(false)
                    .nielsenTrackingAttributes(AdGroupWorkflowNielsenTrackingAttributesInput.builder()
                        .gender(TargetingGenderInput.MALE)
                        .startAge(TargetingStartAgeInput.TWENTY_FIVE)
                        .endAge(TargetingEndAgeInput.SEVENTEEN)
                        .countries(List.of(
                            "<value 1>",
                            "<value 2>",
                            "<value 3>"))
                        .enhancedReportingOption(EnhancedNielsenReportingOptionsInput.SITE)
                        .build())
                    .newFrequencyConfigs(List.of(
                        AdGroupWorkflowNewFrequencyConfigInput.builder()
                            .counterName(Optional.empty())
                            .frequencyCap(375286)
                            .frequencyGoal(534735)
                            .resetIntervalInMinutes(788122)
                            .build()))
                    .flights(List.of(
                        AdGroupWorkflowFlightInput.builder()
                            .campaignFlightId(874887L)
                            .allocationType(AllocationType.MAXIMUM)
                            .budgetInAdvertiserCurrency(4070.96)
                            .budgetInImpressions(901477L)
                            .dailyTargetInAdvertiserCurrency(5847.35)
                            .dailyTargetInImpressions(257517L)
                            .build()))
                    .callerSource("<value>")
                    .build())
                .validateInputOnly(true)
                .build();

        CreateAdGroupResponse res = sdk.adGroup().createAdGroup()
                .request(req)
                .call();

        if (res.adGroupPayload().isPresent()) {
            // handle response
        }
    }
}

Override Server URL Per-Client

The default server can also be overridden globally using the .serverURL(String serverUrl) builder method when initializing the SDK client instance. For example:

package hello.world;

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.models.components.*;
import com.thetradedesk.workflows.models.errors.ProblemDetailsException;
import com.thetradedesk.workflows.models.operations.CreateAdGroupResponse;
import java.lang.Exception;
import java.util.List;
import java.util.Optional;
import org.openapitools.jackson.nullable.JsonNullable;

public class Application {

    public static void main(String[] args) throws ProblemDetailsException, Exception {

        Workflows sdk = Workflows.builder()
                .serverURL("https://api.thetradedesk.com/workflows")
                .ttdAuth(System.getenv().getOrDefault("WORKFLOWS_TTD_AUTH", ""))
            .build();

        AdGroupCreateWorkflowInputWithValidation req = AdGroupCreateWorkflowInputWithValidation.builder()
                .primaryInput(AdGroupCreateWorkflowPrimaryInput.builder()
                    .name("<value>")
                    .channel(AdGroupChannel.DISPLAY)
                    .funnelLocation(AdGroupFunnelLocation.CONSIDERATION)
                    .isEnabled(false)
                    .description("twine from gosh poor safely editor astride vice lost and")
                    .budget(AdGroupWorkflowBudgetInput.builder()
                        .allocationType(AllocationType.MAXIMUM)
                        .budgetInAdvertiserCurrency(3786.02)
                        .budgetInImpressions(783190L)
                        .dailyTargetInAdvertiserCurrency(9747.02)
                        .dailyTargetInImpressions(985999L)
                        .build())
                    .baseBidCPMInAdvertiserCurrency(3785.04)
                    .maxBidCPMInAdvertiserCurrency(7447.3)
                    .audienceTargeting(AdGroupWorkflowAudienceTargetingInput.builder()
                        .audienceId("<id>")
                        .audienceAcceleratorExclusionsEnabled(true)
                        .audienceBoosterEnabled(true)
                        .audienceExcluderEnabled(true)
                        .audiencePredictorEnabled(false)
                        .crossDeviceVendorListForAudience(List.of(
                            107263))
                        .recencyExclusionWindowInMinutes(90062)
                        .targetTrackableUsersEnabled(true)
                        .useMcIdAsPrimary(true)
                        .build())
                    .roiGoal(AdGroupWorkflowROIGoalInput.builder()
                        .maximizeReach(true)
                        .maximizeLtvIncrementalReach(false)
                        .cpcInAdvertiserCurrency(2280.31)
                        .ctrInPercent(JsonNullable.of(null))
                        .nielsenOTPInPercent(5175.21)
                        .cpaInAdvertiserCurrency(2544.37)
                        .returnOnAdSpendPercent(8201.47)
                        .vcrInPercent(4846.08)
                        .viewabilityInPercent(JsonNullable.of(null))
                        .vcpmInAdvertiserCurrency(4649.53)
                        .cpcvInAdvertiserCurrency(313.95)
                        .miaozhenOTPInPercent(4704.1)
                        .build())
                    .creativeIds(JsonNullable.of(null))
                    .associatedBidLists(List.of(
                        AdGroupWorkflowAssociateBidListInput.builder()
                            .bidListId("<id>")
                            .isEnabled(false)
                            .isDefaultForDimension(true)
                            .build()))
                    .marketType(MarketType.PRIVATE_MARKET_ONLY)
                    .programmaticGuaranteedPrivateContractId("<id>")
                    .includeDefaultsFromCampaign(false)
                    .build())
                .campaignId("<id>")
                .advancedInput(AdGroupWorkflowAdvancedInput.builder()
                    .koaOptimizationSettings(AdGroupWorkflowKoaOptimizationSettingsInput.builder()
                        .areFutureKoaFeaturesEnabled(false)
                        .predictiveClearingEnabled(false)
                        .build())
                    .comscoreSettings(AdGroupWorkflowComscoreSettingsInput.builder()
                        .isEnabled(false)
                        .populationId(JsonNullable.of(null))
                        .demographicMemberIds(List.of(
                            959580,
                            236376))
                        .mobileDemographicMemberIds(List.of(
                            664689,
                            827980,
                            21321))
                        .build())
                    .contractTargeting(AdGroupWorkflowContractTargetingInput.builder()
                        .allowOpenMarketBiddingWhenTargetingContracts(true)
                        .build())
                    .dimensionalBiddingAutoOptimizationSettings(List.of(
                        List.of(),
                        List.of()))
                    .isUseClicksAsConversionsEnabled(false)
                    .isUseSecondaryConversionsEnabled(false)
                    .nielsenTrackingAttributes(AdGroupWorkflowNielsenTrackingAttributesInput.builder()
                        .gender(TargetingGenderInput.MALE)
                        .startAge(TargetingStartAgeInput.TWENTY_FIVE)
                        .endAge(TargetingEndAgeInput.SEVENTEEN)
                        .countries(List.of(
                            "<value 1>",
                            "<value 2>",
                            "<value 3>"))
                        .enhancedReportingOption(EnhancedNielsenReportingOptionsInput.SITE)
                        .build())
                    .newFrequencyConfigs(List.of(
                        AdGroupWorkflowNewFrequencyConfigInput.builder()
                            .counterName(Optional.empty())
                            .frequencyCap(375286)
                            .frequencyGoal(534735)
                            .resetIntervalInMinutes(788122)
                            .build()))
                    .flights(List.of(
                        AdGroupWorkflowFlightInput.builder()
                            .campaignFlightId(874887L)
                            .allocationType(AllocationType.MAXIMUM)
                            .budgetInAdvertiserCurrency(4070.96)
                            .budgetInImpressions(901477L)
                            .dailyTargetInAdvertiserCurrency(5847.35)
                            .dailyTargetInImpressions(257517L)
                            .build()))
                    .callerSource("<value>")
                    .build())
                .validateInputOnly(true)
                .build();

        CreateAdGroupResponse res = sdk.adGroup().createAdGroup()
                .request(req)
                .call();

        if (res.adGroupPayload().isPresent()) {
            // handle response
        }
    }
}

Custom HTTP Client

The Java SDK makes API calls using an HTTPClient that wraps the native HttpClient. This client provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The HTTPClient interface allows you to either use the default SpeakeasyHTTPClient that comes with the SDK, or provide your own custom implementation with customized configuration such as custom executors, SSL context, connection pools, and other HTTP client settings.

The interface provides synchronous (send) methods and asynchronous (sendAsync) methods. The sendAsync method is used to power the async SDK methods and returns a CompletableFuture<HttpResponse<Blob>> for non-blocking operations.

The following example shows how to add a custom header and handle errors:

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.utils.HTTPClient;
import com.thetradedesk.workflows.utils.SpeakeasyHTTPClient;
import com.thetradedesk.workflows.utils.Utils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.time.Duration;

public class Application {
    public static void main(String[] args) {
        // Create a custom HTTP client with hooks
        HTTPClient httpClient = new HTTPClient() {
            private final HTTPClient defaultClient = new SpeakeasyHTTPClient();
            
            @Override
            public HttpResponse<InputStream> send(HttpRequest request) throws IOException, URISyntaxException, InterruptedException {
                // Add custom header and timeout using Utils.copy()
                HttpRequest modifiedRequest = Utils.copy(request)
                    .header("x-custom-header", "custom value")
                    .timeout(Duration.ofSeconds(30))
                    .build();
                    
                try {
                    HttpResponse<InputStream> response = defaultClient.send(modifiedRequest);
                    // Log successful response
                    System.out.println("Request successful: " + response.statusCode());
                    return response;
                } catch (Exception error) {
                    // Log error
                    System.err.println("Request failed: " + error.getMessage());
                    throw error;
                }
            }
        };

        Workflows sdk = Workflows.builder()
            .client(httpClient)
            .build();
    }
}
Custom HTTP Client Configuration

You can also provide a completely custom HTTP client with your own configuration:

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.utils.HTTPClient;
import com.thetradedesk.workflows.utils.Blob;
import com.thetradedesk.workflows.utils.ResponseWithBody;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.CompletableFuture;

public class Application {
    public static void main(String[] args) {
        // Custom HTTP client with custom configuration
        HTTPClient customHttpClient = new HTTPClient() {
            private final HttpClient client = HttpClient.newBuilder()
                .executor(Executors.newFixedThreadPool(10))
                .connectTimeout(Duration.ofSeconds(30))
                // .sslContext(customSslContext) // Add custom SSL context if needed
                .build();

            @Override
            public HttpResponse<InputStream> send(HttpRequest request) throws IOException, URISyntaxException, InterruptedException {
                return client.send(request, HttpResponse.BodyHandlers.ofInputStream());
            }

            @Override
            public CompletableFuture<HttpResponse<Blob>> sendAsync(HttpRequest request) {
                // Convert response to HttpResponse<Blob> for async operations
                return client.sendAsync(request, HttpResponse.BodyHandlers.ofPublisher())
                    .thenApply(resp -> new ResponseWithBody<>(resp, Blob::from));
            }
        };

        Workflows sdk = Workflows.builder()
            .client(customHttpClient)
            .build();
    }
}

You can also enable debug logging on the default SpeakeasyHTTPClient:

import com.thetradedesk.workflows.Workflows;
import com.thetradedesk.workflows.utils.SpeakeasyHTTPClient;

public class Application {
    public static void main(String[] args) {
        SpeakeasyHTTPClient httpClient = new SpeakeasyHTTPClient();
        httpClient.enableDebugLogging(true);

        Workflows sdk = Workflows.builder()
            .client(httpClient)
            .build();
    }
}

Debugging

Debug

You can setup your SDK to emit debug logs for SDK requests and responses.

For request and response logging (especially json bodies), call enableHTTPDebugLogging(boolean) on the SDK builder like so:

SDK.builder()
    .enableHTTPDebugLogging(true)
    .build();

Example output:

Sending request: http://localhost:35123/bearer#global GET
Request headers: {Accept=[application/json], Authorization=[******], Client-Level-Header=[added by client], Idempotency-Key=[some-key], x-speakeasy-user-agent=[speakeasy-sdk/java 0.0.1 internal 0.1.0 org.openapis.openapi]}
Received response: (GET http://localhost:35123/bearer#global) 200
Response headers: {access-control-allow-credentials=[true], access-control-allow-origin=[*], connection=[keep-alive], content-length=[50], content-type=[application/json], date=[Wed, 09 Apr 2025 01:43:29 GMT], server=[gunicorn/19.9.0]}
Response body:
{
  "authenticated": true, 
  "token": "global"
}

WARNING: This should only used for temporary debugging purposes. Leaving this option on in a production system could expose credentials/secrets in logs. Authorization headers are redacted by default and there is the ability to specify redacted header names via SpeakeasyHTTPClient.setRedactedHeaders.

NOTE: This is a convenience method that calls HTTPClient.enableDebugLogging(). The SpeakeasyHTTPClient honors this setting. If you are using a custom HTTP client, it is up to the custom client to honor this setting.

Another option is to set the System property -Djdk.httpclient.HttpClient.log=all. However, this second option does not log bodies.

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy

About

No description, website, or topics provided.

Resources

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 6

Languages