Search in sources :

Example 1 with AdGroupCriterionPage

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

the class GetKeywords method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adGroupId the ID of the ad group to use to find keywords.
 * @throws ApiException if the API request failed with one or more service errors.
 * @throws RemoteException if the API request failed due to other errors.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, Long adGroupId) throws RemoteException {
    // Get the AdGroupCriterionService.
    AdGroupCriterionServiceInterface adGroupCriterionService = adWordsServices.get(session, AdGroupCriterionServiceInterface.class);
    int offset = 0;
    boolean morePages = true;
    // Create selector.
    SelectorBuilder builder = new SelectorBuilder();
    Selector selector = builder.fields(AdGroupCriterionField.Id, AdGroupCriterionField.CriteriaType, AdGroupCriterionField.KeywordMatchType, AdGroupCriterionField.KeywordText).orderAscBy(AdGroupCriterionField.KeywordText).offset(offset).limit(PAGE_SIZE).in(AdGroupCriterionField.AdGroupId, adGroupId.toString()).in(AdGroupCriterionField.CriteriaType, "KEYWORD").build();
    while (morePages) {
        // Get all ad group criteria.
        AdGroupCriterionPage page = adGroupCriterionService.get(selector);
        // Display ad group criteria.
        if (page.getEntries() != null && page.getEntries().length > 0) {
            // Display results.
            Arrays.stream(page.getEntries()).map(adGroupCriterionResult -> (Keyword) adGroupCriterionResult.getCriterion()).forEach(keyword -> System.out.printf("Keyword with text '%s', match type '%s', criteria type '%s'," + " and ID %d was found.%n", keyword.getText(), keyword.getMatchType(), keyword.getType(), keyword.getId()));
        } else {
            System.out.println("No ad group criteria were found.");
        }
        offset += PAGE_SIZE;
        selector = builder.increaseOffsetBy(PAGE_SIZE).build();
        morePages = offset < page.getTotalNumEntries();
    }
}
Also used : OAuthException(com.google.api.ads.common.lib.exception.OAuthException) Arrays(java.util.Arrays) Parameter(com.beust.jcommander.Parameter) AdWordsServices(com.google.api.ads.adwords.axis.factory.AdWordsServices) AdGroupCriterionPage(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionPage) AdGroupCriterionServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionServiceInterface) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) Keyword(com.google.api.ads.adwords.axis.v201809.cm.Keyword) CodeSampleParams(com.google.api.ads.common.lib.utils.examples.CodeSampleParams) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) RemoteException(java.rmi.RemoteException) DEFAULT_CONFIGURATION_FILENAME(com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) Api(com.google.api.ads.common.lib.auth.OfflineCredentials.Api) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector) ArgumentNames(com.google.api.ads.adwords.lib.utils.examples.ArgumentNames) Credential(com.google.api.client.auth.oauth2.Credential) AdGroupCriterionField(com.google.api.ads.adwords.lib.selectorfields.v201809.cm.AdGroupCriterionField) AdGroupCriterionServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionServiceInterface) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) Keyword(com.google.api.ads.adwords.axis.v201809.cm.Keyword) AdGroupCriterionPage(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionPage) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector)

Example 2 with AdGroupCriterionPage

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

the class ProductPartitionTreeImpl method createAdGroupTree.

/**
 * Returns a new instance of this class by retrieving the product partitions of the
 * specified ad group. All parameters are required.
 */
static ProductPartitionTreeImpl createAdGroupTree(AdWordsServicesInterface services, AdWordsSession session, Long adGroupId) throws ApiException, RemoteException {
    // Get the AdGroupCriterionService.
    AdGroupCriterionServiceInterface criterionService = services.get(session, AdGroupCriterionServiceInterface.class);
    SelectorBuilder selectorBuilder = new SelectorBuilder().fields(REQUIRED_SELECTOR_FIELD_ENUMS.toArray(new AdGroupCriterionField[REQUIRED_SELECTOR_FIELD_ENUMS.size()])).equals(AdGroupCriterionField.AdGroupId, adGroupId.toString()).equals(AdGroupCriterionField.CriteriaType, "PRODUCT_PARTITION").in(AdGroupCriterionField.Status, UserStatus.ENABLED.getValue(), UserStatus.PAUSED.getValue()).limit(PAGE_SIZE);
    AdGroupCriterionPage adGroupCriterionPage;
    // A multimap from each product partition ID to its direct children.
    ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
    int offset = 0;
    do {
        // Get the next page of results.
        adGroupCriterionPage = criterionService.get(selectorBuilder.build());
        if (adGroupCriterionPage != null && adGroupCriterionPage.getEntries() != null) {
            for (AdGroupCriterion adGroupCriterion : adGroupCriterionPage.getEntries()) {
                ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
                parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
            }
            offset += adGroupCriterionPage.getEntries().length;
            selectorBuilder.increaseOffsetBy(PAGE_SIZE);
        }
    } while (offset < adGroupCriterionPage.getTotalNumEntries());
    // Construct the ProductPartitionTree from the parentIdMap.
    if (!parentIdMap.containsKey(null)) {
        Preconditions.checkState(parentIdMap.isEmpty(), "No root criterion found in the tree but the tree is not empty");
        return createEmptyAdGroupTree(adGroupId, getAdGroupBiddingStrategyConfiguration(services, session, adGroupId));
    }
    return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
}
Also used : AdGroupCriterionServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionServiceInterface) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) AdGroupCriterionPage(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionPage) BiddableAdGroupCriterion(com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion) AdGroupCriterion(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterion) ProductPartition(com.google.api.ads.adwords.axis.v201809.cm.ProductPartition) AdGroupCriterionField(com.google.api.ads.adwords.lib.selectorfields.v201809.cm.AdGroupCriterionField)

Example 3 with AdGroupCriterionPage

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

the class ProductPartitionTreeTest method testCreateTreeUsingService.

/**
 * Tests that the factory method that retrieves the tree using API services builds
 * the correct tree and passes the correct paging arguments.
 */
@Test
public void testCreateTreeUsingService() throws Exception {
    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
    AdWordsSession session = new AdWordsSession.Builder().withClientCustomerId("123-456-7890").withOAuth2Credential(new Credential(BearerToken.authorizationHeaderAccessMethod())).withDeveloperToken("devtoken").withUserAgent("test").withEndpoint(testHttpServer.getServerUrl()).build();
    // Extract the API version from this test's package.
    List<String> packageComponents = Lists.newArrayList(Splitter.on('.').split(getClass().getPackage().getName()));
    final String apiVersion = packageComponents.get(packageComponents.size() - 2);
    final int pageSize = 100;
    final int numberOfCriteria = (pageSize * 5) + 1;
    // Construct a list of CriterionDescriptors that will build a tree of the form:
    // root
    // OfferId = null EXCLUDED
    // OfferId = 1 BIDDABLE
    // OfferId = 2 BIDDABLE
    // ...
    // OfferId = numberOfCriteria BIDDABLE
    List<CriterionDescriptor> descriptors = Lists.newArrayList();
    long partitionId = 1L;
    final long rootPartitionId = partitionId;
    descriptors.add(new CriterionDescriptor(false, false, null, null, partitionId++, null));
    descriptors.add(new CriterionDescriptor(true, true, ProductDimensions.createOfferId(null), null, partitionId++, rootPartitionId));
    for (int i = 1; i <= (numberOfCriteria - 2); i++) {
        CriterionDescriptor descriptor = new CriterionDescriptor(true, false, ProductDimensions.createOfferId(Integer.toString(i)), 10000000L, partitionId++, rootPartitionId, i == 2 ? "http://wwww.example.com/tracking?{lpurl}" : null);
        descriptor.customParams.put("param1", "value1");
        descriptor.customParams.put("param2", "value2");
        descriptors.add(descriptor);
    }
    // Split the descriptor list into batches of size pageSize.
    List<List<CriterionDescriptor>> descriptorBatches = Lists.partition(descriptors, pageSize);
    List<String> responseBodies = Lists.newArrayList();
    for (List<CriterionDescriptor> descriptorBatch : descriptorBatches) {
        // For this batch of descriptors, manually construct the AdGroupCriterionPage
        // to return. This is required because AdWordsServices is a final class, so this test
        // cannot mock its behavior.
        AdGroupCriterionPage mockPage = new AdGroupCriterionPage();
        mockPage.setTotalNumEntries(numberOfCriteria);
        mockPage.setEntries(new AdGroupCriterion[descriptorBatch.size()]);
        int i = 0;
        for (CriterionDescriptor descriptor : descriptorBatch) {
            mockPage.setEntries(i++, descriptor.createCriterion());
        }
        // Serialize the page.
        StringWriter writer = new StringWriter();
        SerializationContext serializationContext = new SerializationContext(writer) {

            /**
             * Override the serialize method called by the Axis serializer and force it to
             * pass {@code includeNull = false}.
             */
            @SuppressWarnings("rawtypes")
            @Override
            public void serialize(QName elemQName, Attributes attributes, Object value, QName xmlType, Class javaType) throws IOException {
                super.serialize(elemQName, attributes, value, xmlType, javaType, false, null);
            }
        };
        serializationContext.setSendDecl(false);
        new AxisSerializer().serialize(mockPage, serializationContext);
        // Wrap the serialized page in a SOAP envelope.
        StringBuilder response = new StringBuilder();
        response.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Header/><soap:Body>");
        response.append(String.format("<getResponse xmlns=\"https://adwords.google.com/api/adwords/cm/%s\">", apiVersion));
        // Replace the element name AdGroupCriterionPage with the expected name rval in the
        // serialized page.
        response.append(writer.toString().replaceAll("AdGroupCriterionPage", "rval"));
        response.append("</getResponse></soap:Body></soap:Envelope>");
        responseBodies.add(response.toString());
    }
    // Set the test server to return the response bodies constructed above.
    testHttpServer.setMockResponseBodies(responseBodies);
    // Build the tree.
    ProductPartitionTree tree = ProductPartitionTree.createAdGroupTree(adWordsServices, session, 9999L);
    // First, confirm that the paging elements were correct in each request's selector.
    int requestNumber = 0;
    for (String requestBody : testHttpServer.getAllRequestBodies()) {
        int expectedOffset = requestNumber * pageSize;
        assertThat("numberResults paging element is missing or incorrect in request", requestBody, Matchers.containsString("numberResults>" + pageSize + "</"));
        if (requestNumber == 0) {
            assertThat("startIndex paging element unexpectedly found in the first request", requestBody, Matchers.not(Matchers.containsString("startIndex>")));
        } else {
            assertThat("startIndex paging element is missing or incorrect in request", requestBody, Matchers.containsString("startIndex>" + expectedOffset + "</"));
        }
        requestNumber++;
    }
    // Confirm that the tree returned by the factory method matches the expected tree.
    descriptors.get(0).assertDescriptorEquals(new CriterionDescriptor(tree.getRoot()));
    // Get a map of all of the child descriptors for the root node.
    Map<Long, CriterionDescriptor> descriptorMap = buildDescriptorMap(descriptors).get(rootPartitionId);
    // Confirm each ProductPartitionNode under the root node has a matching entry in the descriptor
    // map.
    int childrenFound = 0;
    for (ProductPartitionNode childNode : tree.getRoot().getChildren()) {
        CriterionDescriptor nodeDescriptor = new CriterionDescriptor(childNode);
        nodeDescriptor.assertDescriptorEquals(descriptorMap.get(nodeDescriptor.partitionId));
        childrenFound++;
    }
    assertEquals("Did not find an entry in the response for every expected child node", descriptorMap.size(), childrenFound);
}
Also used : SerializationContext(org.apache.axis.encoding.SerializationContext) Attributes(org.xml.sax.Attributes) StringWriter(java.io.StringWriter) List(java.util.List) ArrayList(java.util.ArrayList) Credential(com.google.api.client.auth.oauth2.Credential) QName(javax.xml.namespace.QName) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) AdGroupCriterionPage(com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionPage) AxisSerializer(com.google.api.ads.adwords.axis.utils.AxisSerializer) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) MockHttpIntegrationTest(com.google.api.ads.common.lib.testing.MockHttpIntegrationTest) Test(org.junit.Test)

Aggregations

AdGroupCriterionPage (com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionPage)3 SelectorBuilder (com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder)2 AdGroupCriterionServiceInterface (com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionServiceInterface)2 AdWordsSession (com.google.api.ads.adwords.lib.client.AdWordsSession)2 AdWordsServicesInterface (com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface)2 AdGroupCriterionField (com.google.api.ads.adwords.lib.selectorfields.v201809.cm.AdGroupCriterionField)2 Credential (com.google.api.client.auth.oauth2.Credential)2 Parameter (com.beust.jcommander.Parameter)1 AdWordsServices (com.google.api.ads.adwords.axis.factory.AdWordsServices)1 AxisSerializer (com.google.api.ads.adwords.axis.utils.AxisSerializer)1 AdGroupCriterion (com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterion)1 ApiError (com.google.api.ads.adwords.axis.v201809.cm.ApiError)1 ApiException (com.google.api.ads.adwords.axis.v201809.cm.ApiException)1 BiddableAdGroupCriterion (com.google.api.ads.adwords.axis.v201809.cm.BiddableAdGroupCriterion)1 Keyword (com.google.api.ads.adwords.axis.v201809.cm.Keyword)1 ProductPartition (com.google.api.ads.adwords.axis.v201809.cm.ProductPartition)1 Selector (com.google.api.ads.adwords.axis.v201809.cm.Selector)1 ArgumentNames (com.google.api.ads.adwords.lib.utils.examples.ArgumentNames)1 OfflineCredentials (com.google.api.ads.common.lib.auth.OfflineCredentials)1 Api (com.google.api.ads.common.lib.auth.OfflineCredentials.Api)1