Search in sources :

Example 1 with BiddableAdGroupCriterion

use of com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion in project googleads-java-lib by googleads.

the class ProductPartitionTreeTest method testCreateUltimatelyEmptyTree.

/**
 * Tests creating a tree that in its <em>final</em> state is just an empty tree.
 */
@Test
public void testCreateUltimatelyEmptyTree() {
    ProductPartitionTree tree = ProductPartitionTree.createAdGroupTree(-1L, biddingStrategyConfig, Collections.<AdGroupCriterion>emptyList());
    ProductPartitionNode rootNode = tree.getRoot().asSubdivision();
    ProductPartitionNode brand1 = rootNode.addChild(ProductDimensions.createBrand("google")).asSubdivision();
    brand1.addChild(ProductDimensions.createOfferId("A")).asBiddableUnit().setBid(1000000L);
    brand1.addChild(ProductDimensions.createOfferId(null)).asExcludedUnit();
    ProductPartitionNode brand2 = rootNode.addChild(ProductDimensions.createBrand(null)).asExcludedUnit();
    // Now remove the two child nodes under the root and set the root back to a UNIT. This should
    // result in operations that simply create the root node.
    rootNode.removeChild(brand1.getDimension());
    rootNode.removeChild(brand2.getDimension());
    rootNode = rootNode.asBiddableUnit();
    List<AdGroupCriterionOperation> mutateOperations = tree.getMutateOperations();
    assertEquals("Number of operations is incorrect", 1, mutateOperations.size());
    AdGroupCriterionOperation operation = mutateOperations.iterator().next();
    assertEquals("Should have a single operation to ADD the root node", Operator.ADD, operation.getOperator());
    BiddableAdGroupCriterion adGroupCriterion = (BiddableAdGroupCriterion) operation.getOperand();
    assertNull("Product dimension of operation's operand should be null", ((ProductPartition) adGroupCriterion.getCriterion()).getCaseValue());
    assertTrue("Partition ID of the operand should be negative", adGroupCriterion.getCriterion().getId().longValue() < 0L);
}
Also used : AdGroupCriterionOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionOperation) BiddableAdGroupCriterion(com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion) MockHttpIntegrationTest(com.google.api.ads.common.lib.testing.MockHttpIntegrationTest) Test(org.junit.Test)

Example 2 with BiddableAdGroupCriterion

use of com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion in project googleads-java-lib by googleads.

the class ProductPartitionTreeTest method testCreateEmptyTree.

/**
 * Tests creating an empty ad group tree. In this case, all operations generated should be ADD
 * operations.
 */
@Test
public void testCreateEmptyTree() {
    ProductPartitionTree tree = ProductPartitionTree.createAdGroupTree(-1L, biddingStrategyConfig, Collections.<AdGroupCriterion>emptyList());
    assertNotNull("Even an empty tree should automatically have a root node", tree.getRoot());
    assertTrue("The root node for an empty tree should have a negative (temporary) ID", tree.getRoot().getProductPartitionId().longValue() < 0L);
    assertTrue("The root node for an empty tree should be a UNIT", tree.getRoot().isUnit());
    List<AdGroupCriterionOperation> mutateOperations = tree.getMutateOperations();
    assertEquals("Number of operations is incorrect", 1, mutateOperations.size());
    AdGroupCriterionOperation operation = mutateOperations.iterator().next();
    assertEquals("Should have a single operation to ADD the root node", Operator.ADD, operation.getOperator());
    BiddableAdGroupCriterion adGroupCriterion = (BiddableAdGroupCriterion) operation.getOperand();
    assertNull("Product dimension of operation's operand should be null", ((ProductPartition) adGroupCriterion.getCriterion()).getCaseValue());
    assertTrue("Partition ID of the operand should be negative", adGroupCriterion.getCriterion().getId().longValue() < 0L);
}
Also used : AdGroupCriterionOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionOperation) BiddableAdGroupCriterion(com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion) MockHttpIntegrationTest(com.google.api.ads.common.lib.testing.MockHttpIntegrationTest) Test(org.junit.Test)

Example 3 with BiddableAdGroupCriterion

use of com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion in project googleads-java-lib by googleads.

the class AddCompleteCampaignsUsingBatchJob method buildAdGroupCriterionOperations.

private static List<AdGroupCriterionOperation> buildAdGroupCriterionOperations(List<AdGroupOperation> adGroupOperations) {
    List<AdGroupCriterionOperation> adGroupCriteriaOperations = new ArrayList<>();
    // Create AdGroupCriterionOperations to add keywords.
    for (AdGroupOperation adGroupOperation : adGroupOperations) {
        long newAdGroupId = adGroupOperation.getOperand().getId();
        for (int i = 0; i < NUMBER_OF_KEYWORDS_TO_ADD; i++) {
            // Create Keyword.
            String text = String.format("mars%d", i);
            // Make 50% of keywords invalid to demonstrate error handling.
            if (i % 2 == 0) {
                text = text + "!!!";
            }
            Keyword keyword = new Keyword();
            keyword.setText(text);
            keyword.setMatchType(KeywordMatchType.BROAD);
            // Create BiddableAdGroupCriterion.
            BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();
            biddableAdGroupCriterion.setAdGroupId(newAdGroupId);
            biddableAdGroupCriterion.setCriterion(keyword);
            // Create AdGroupCriterionOperation.
            AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
            operation.setOperand(biddableAdGroupCriterion);
            operation.setOperator(Operator.ADD);
            // Add to list.
            adGroupCriteriaOperations.add(operation);
        }
    }
    return adGroupCriteriaOperations;
}
Also used : AdGroupCriterionOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionOperation) Keyword(com.google.api.ads.adwords.axis.v201809.cm.Keyword) BiddableAdGroupCriterion(com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion) ArrayList(java.util.ArrayList) AdGroupOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupOperation)

Example 4 with BiddableAdGroupCriterion

use of com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion in project googleads-java-lib by googleads.

the class AddKeywordsUsingIncrementalBatchJob method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adGroupId the ID of the ad group where keywords will be added.
 * @throws BatchJobException if uploading operations or downloading results failed.
 * @throws ApiException if the API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 * @throws InterruptedException if the thread was interrupted while sleeping between retries.
 * @throws TimeoutException if the job did not complete after job status was polled {@link
 *     #MAX_POLL_ATTEMPTS} times.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, Long adGroupId) throws RemoteException, BatchJobException, InterruptedException, TimeoutException {
    // Get the BatchJobService.
    BatchJobServiceInterface batchJobService = adWordsServices.get(session, BatchJobServiceInterface.class);
    BatchJobOperation addOp = new BatchJobOperation();
    addOp.setOperator(Operator.ADD);
    addOp.setOperand(new BatchJob());
    BatchJob batchJob = batchJobService.mutate(new BatchJobOperation[] { addOp }).getValue(0);
    System.out.printf("Created BatchJob with ID %d, status '%s' and upload URL %s.%n", batchJob.getId(), batchJob.getStatus(), batchJob.getUploadUrl().getUrl());
    // Create a BatchJobHelper for uploading operations.
    BatchJobHelper batchJobHelper = adWordsServices.getUtility(session, BatchJobHelper.class);
    BatchJobUploadStatus batchJobUploadStatus = new BatchJobUploadStatus(0, URI.create(batchJob.getUploadUrl().getUrl()));
    List<AdGroupCriterionOperation> operations = new ArrayList<>();
    // incrementally.
    for (int i = 0; i < NUMBER_OF_KEYWORDS_TO_ADD; i++) {
        // Create Keyword.
        String text = String.format("mars%d", i);
        // Make 10% of keywords invalid to demonstrate error handling.
        if (i % 10 == 0) {
            text = text + "!!!";
        }
        Keyword keyword = new Keyword();
        keyword.setText(text);
        keyword.setMatchType(KeywordMatchType.BROAD);
        // Create BiddableAdGroupCriterion.
        BiddableAdGroupCriterion bagc = new BiddableAdGroupCriterion();
        bagc.setAdGroupId(adGroupId);
        bagc.setCriterion(keyword);
        // Create AdGroupCriterionOperation.
        AdGroupCriterionOperation agco = new AdGroupCriterionOperation();
        agco.setOperand(bagc);
        agco.setOperator(Operator.ADD);
        // Add to the list of operations.
        operations.add(agco);
        // If the current list of operations has reached KEYWORDS_PER_UPLOAD or this is the last
        // operation, upload the current list of operations.
        boolean isLastOperation = i == NUMBER_OF_KEYWORDS_TO_ADD - 1;
        if (operations.size() == KEYWORDS_PER_UPLOAD || isLastOperation) {
            BatchJobUploadResponse uploadResponse = batchJobHelper.uploadIncrementalBatchJobOperations(operations, isLastOperation, batchJobUploadStatus);
            System.out.printf("Uploaded %d operations for batch job with ID %d.%n", operations.size(), batchJob.getId());
            // Set the batch job upload status and clear the operations list in preparation for the
            // next upload.
            batchJobUploadStatus = uploadResponse.getBatchJobUploadStatus();
            operations.clear();
        }
    }
    // Poll for completion of the batch job using an exponential back off.
    int pollAttempts = 0;
    boolean isPending;
    boolean wasCancelRequested = false;
    Selector selector = new SelectorBuilder().fields(BatchJobField.Id, BatchJobField.Status, BatchJobField.DownloadUrl, BatchJobField.ProcessingErrors, BatchJobField.ProgressStats).equalsId(batchJob.getId()).build();
    do {
        long sleepSeconds = (long) Math.scalb(30, pollAttempts);
        System.out.printf("Sleeping %d seconds...%n", sleepSeconds);
        Thread.sleep(sleepSeconds * 1000);
        batchJob = batchJobService.get(selector).getEntries(0);
        System.out.printf("Batch job ID %d has status '%s'.%n", batchJob.getId(), batchJob.getStatus());
        pollAttempts++;
        isPending = PENDING_STATUSES.contains(batchJob.getStatus());
        // times.
        if (isPending && !wasCancelRequested && pollAttempts == MAX_POLL_ATTEMPTS) {
            batchJob.setStatus(BatchJobStatus.CANCELING);
            BatchJobOperation batchJobSetOperation = new BatchJobOperation();
            batchJobSetOperation.setOperand(batchJob);
            batchJobSetOperation.setOperator(Operator.SET);
            // Only request cancellation once per job.
            wasCancelRequested = true;
            try {
                batchJob = batchJobService.mutate(new BatchJobOperation[] { batchJobSetOperation }).getValue(0);
                System.out.printf("Requested cancellation of batch job with ID %d.%n", batchJob.getId());
            } catch (ApiException e) {
                if (e.getErrors() != null && e.getErrors().length > 0 && e.getErrors(0) instanceof BatchJobError) {
                    BatchJobError batchJobError = (BatchJobError) e.getErrors(0);
                    if (BatchJobErrorReason.INVALID_STATE_CHANGE.equals(batchJobError.getReason())) {
                        System.out.printf("Attempt to cancel batch job with ID %d was rejected because the job already " + "completed or was canceled.", batchJob.getId());
                        continue;
                    }
                }
                throw e;
            } finally {
                // Reset the poll attempt counter to wait for cancellation.
                pollAttempts = 0;
            }
        }
    } while (isPending && pollAttempts < MAX_POLL_ATTEMPTS);
    if (isPending) {
        throw new TimeoutException("Job is still in pending state after polling " + MAX_POLL_ATTEMPTS + " times.");
    }
    if (batchJob.getProcessingErrors() != null) {
        int errorIndex = 0;
        for (BatchJobProcessingError processingError : batchJob.getProcessingErrors()) {
            System.out.printf("  Processing error [%d]: errorType=%s, trigger=%s, errorString=%s, fieldPath=%s" + ", reason=%s%n", errorIndex++, processingError.getApiErrorType(), processingError.getTrigger(), processingError.getErrorString(), processingError.getFieldPath(), processingError.getReason());
        }
    } else {
        System.out.println("No processing errors found.");
    }
    if (batchJob.getDownloadUrl() != null && batchJob.getDownloadUrl().getUrl() != null) {
        BatchJobMutateResponse mutateResponse = batchJobHelper.downloadBatchJobMutateResponse(batchJob.getDownloadUrl().getUrl());
        System.out.printf("Downloaded results from %s:%n", batchJob.getDownloadUrl().getUrl());
        for (MutateResult mutateResult : mutateResponse.getMutateResults()) {
            String outcome = mutateResult.getErrorList() == null ? "SUCCESS" : "FAILURE";
            System.out.printf("  Operation [%d] - %s%n", mutateResult.getIndex(), outcome);
        }
    } else {
        System.out.println("No results available for download.");
    }
}
Also used : Keyword(com.google.api.ads.adwords.axis.v201809.cm.Keyword) BatchJobProcessingError(com.google.api.ads.adwords.axis.v201809.cm.BatchJobProcessingError) ArrayList(java.util.ArrayList) BatchJobServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.BatchJobServiceInterface) BatchJobOperation(com.google.api.ads.adwords.axis.v201809.cm.BatchJobOperation) BatchJobUploadStatus(com.google.api.ads.adwords.lib.utils.BatchJobUploadStatus) BatchJobMutateResponse(com.google.api.ads.adwords.axis.utils.v201809.batchjob.BatchJobMutateResponse) AdGroupCriterionOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionOperation) BatchJobUploadResponse(com.google.api.ads.adwords.lib.utils.BatchJobUploadResponse) BatchJobHelper(com.google.api.ads.adwords.axis.utils.v201809.batchjob.BatchJobHelper) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) BiddableAdGroupCriterion(com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion) BatchJobError(com.google.api.ads.adwords.axis.v201809.cm.BatchJobError) MutateResult(com.google.api.ads.adwords.axis.utils.v201809.batchjob.MutateResult) BatchJob(com.google.api.ads.adwords.axis.v201809.cm.BatchJob) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) TimeoutException(java.util.concurrent.TimeoutException)

Example 5 with BiddableAdGroupCriterion

use of com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion in project googleads-java-lib by googleads.

the class AddDynamicSearchAdsCampaign method addWebPageCriteria.

/**
 * Adds a web page criteria to target Dynamic Search Ads.
 */
private static void addWebPageCriteria(AdWordsServicesInterface adWordsServices, AdWordsSession session, AdGroup adGroup) throws ApiException, RemoteException {
    // Get the AdGroupCriterionService.
    AdGroupCriterionServiceInterface adGroupCriterionService = adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
    // Create a webpage criterion for special offers.
    WebpageParameter param = new WebpageParameter();
    param.setCriterionName("Special offers");
    WebpageCondition urlCondition = new WebpageCondition();
    urlCondition.setOperand(WebpageConditionOperand.URL);
    urlCondition.setArgument("/specialoffers");
    WebpageCondition titleCondition = new WebpageCondition();
    titleCondition.setOperand(WebpageConditionOperand.PAGE_TITLE);
    titleCondition.setArgument("Special Offer");
    param.setConditions(new WebpageCondition[] { urlCondition, titleCondition });
    Webpage webpage = new Webpage();
    webpage.setParameter(param);
    // Create biddable ad group criterion.
    BiddableAdGroupCriterion biddableAdGroupCriterion = new BiddableAdGroupCriterion();
    biddableAdGroupCriterion.setAdGroupId(adGroup.getId());
    biddableAdGroupCriterion.setCriterion(webpage);
    biddableAdGroupCriterion.setUserStatus(UserStatus.PAUSED);
    // Optional: set a custom bid.
    BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
    CpcBid bid = new CpcBid();
    bid.setBid(new Money());
    bid.getBid().setMicroAmount(10000000L);
    biddingStrategyConfiguration.setBids(new Bids[] { bid });
    biddableAdGroupCriterion.setBiddingStrategyConfiguration(biddingStrategyConfiguration);
    // Create operations.
    AdGroupCriterionOperation operation = new AdGroupCriterionOperation();
    operation.setOperator(Operator.ADD);
    operation.setOperand(biddableAdGroupCriterion);
    // Create the criterion.
    AdGroupCriterion newAdGroupCriterion = adGroupCriterionService.mutate(new AdGroupCriterionOperation[] { operation }).getValue(0);
    System.out.printf("Webpage criterion with ID %d was added to ad group ID %d.%n", newAdGroupCriterion.getCriterion().getId(), newAdGroupCriterion.getAdGroupId());
}
Also used : Money(com.google.api.ads.adwords.axis.v201809.cm.Money) AdGroupCriterionOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionOperation) Webpage(com.google.api.ads.adwords.axis.v201809.cm.Webpage) AdGroupCriterionServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionServiceInterface) BiddableAdGroupCriterion(com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion) BiddingStrategyConfiguration(com.google.api.ads.adwords.axis.v201809.cm.BiddingStrategyConfiguration) BiddableAdGroupCriterion(com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion) AdGroupCriterion(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterion) CpcBid(com.google.api.ads.adwords.axis.v201809.cm.CpcBid) WebpageParameter(com.google.api.ads.adwords.axis.v201809.cm.WebpageParameter) WebpageCondition(com.google.api.ads.adwords.axis.v201809.cm.WebpageCondition)

Aggregations

BiddableAdGroupCriterion (com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion)18 AdGroupCriterion (com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterion)11 AdGroupCriterionOperation (com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionOperation)11 Money (com.google.api.ads.adwords.axis.v201809.cm.Money)9 CpcBid (com.google.api.ads.adwords.axis.v201809.cm.CpcBid)8 AdGroupCriterionServiceInterface (com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionServiceInterface)7 BiddingStrategyConfiguration (com.google.api.ads.adwords.axis.v201809.cm.BiddingStrategyConfiguration)7 Test (org.junit.Test)7 NegativeAdGroupCriterion (com.google.api.ads.adwords.axis.v201809.cm.NegativeAdGroupCriterion)5 ProductPartition (com.google.api.ads.adwords.axis.v201809.cm.ProductPartition)5 AdGroupCriterionReturnValue (com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionReturnValue)4 Bids (com.google.api.ads.adwords.axis.v201809.cm.Bids)4 Keyword (com.google.api.ads.adwords.axis.v201809.cm.Keyword)4 BatchJobMutateResponse (com.google.api.ads.adwords.jaxws.utils.v201809.batchjob.BatchJobMutateResponse)3 BiddableAdGroupCriterion (com.google.api.ads.adwords.jaxws.v201809.cm.BiddableAdGroupCriterion)3 MockHttpIntegrationTest (com.google.api.ads.common.lib.testing.MockHttpIntegrationTest)3 ArrayList (java.util.ArrayList)3 ApiException (com.google.api.ads.adwords.axis.v201809.cm.ApiException)2 Criterion (com.google.api.ads.adwords.axis.v201809.cm.Criterion)2 Webpage (com.google.api.ads.adwords.axis.v201809.cm.Webpage)2