Search in sources :

Example 6 with Paging

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

the class AdvancedCreateCredentialFromScratch method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param reportFile the output file for the report contents.
 * @throws DetailedReportDownloadResponseException if the report request failed with a detailed
 *     error from the reporting service.
 * @throws ReportDownloadResponseException if the report request failed with a general error from
 *     the reporting service.
 * @throws ReportException if the report request failed due to a transport layer error.
 * @throws IOException if the report's contents could not be written to {@code reportFile}.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, String reportFile) throws ReportDownloadResponseException, ReportException, IOException {
    // Get the CampaignService.
    CampaignServiceInterface campaignService = adWordsServices.get(session, CampaignServiceInterface.class);
    // Create selector to retrieve the first 100 campaigns.
    Selector selector = new Selector();
    selector.setFields(new String[] { "Id", "Name" });
    Paging paging = new Paging();
    paging.setStartIndex(0);
    paging.setNumberResults(100);
    // Get the first page of campaigns.
    CampaignPage page = campaignService.get(selector);
    System.out.printf("Found %d total campaigns.%n", page.getTotalNumEntries());
    // Display campaigns.
    if (page.getEntries() != null) {
        for (Campaign campaign : page.getEntries()) {
            System.out.printf("Campaign with name '%s' and ID %d was found.%n", campaign.getName(), campaign.getId());
        }
    } else {
        System.out.println("No campaigns were found.");
    }
    // Create selector.
    com.google.api.ads.adwords.lib.jaxb.v201809.Selector reportSelector = new com.google.api.ads.adwords.lib.jaxb.v201809.Selector();
    reportSelector.getFields().addAll(Arrays.asList("CampaignId", "AdGroupId", "Id", "CriteriaType", "Criteria", "Impressions", "Clicks", "Cost"));
    // Create report definition.
    ReportDefinition reportDefinition = new ReportDefinition();
    reportDefinition.setReportName("Criteria performance report #" + System.currentTimeMillis());
    reportDefinition.setDateRangeType(ReportDefinitionDateRangeType.YESTERDAY);
    reportDefinition.setReportType(ReportDefinitionReportType.CRITERIA_PERFORMANCE_REPORT);
    reportDefinition.setDownloadFormat(DownloadFormat.CSV);
    reportDefinition.setSelector(reportSelector);
    ReportingConfiguration reportingConfig = new ReportingConfiguration.Builder().includeZeroImpressions(false).build();
    session.setReportingConfiguration(reportingConfig);
    ReportDownloadResponse response = new ReportDownloader(session).downloadReport(reportDefinition);
    FileOutputStream fos = new FileOutputStream(new File(reportFile));
    Streams.copy(response.getInputStream(), fos);
    fos.close();
    System.out.printf("Report successfully downloaded: %s%n", reportFile);
}
Also used : Paging(com.google.api.ads.adwords.axis.v201809.cm.Paging) CampaignPage(com.google.api.ads.adwords.axis.v201809.cm.CampaignPage) CampaignServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface) ReportDownloadResponse(com.google.api.ads.adwords.lib.utils.ReportDownloadResponse) ReportDownloader(com.google.api.ads.adwords.lib.utils.v201809.ReportDownloader) Campaign(com.google.api.ads.adwords.axis.v201809.cm.Campaign) FileOutputStream(java.io.FileOutputStream) File(java.io.File) ReportDefinition(com.google.api.ads.adwords.lib.jaxb.v201809.ReportDefinition) ReportingConfiguration(com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration) Selector(com.google.api.ads.adwords.axis.v201809.cm.Selector)

Example 7 with Paging

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

the class SelectorBuilderImpl method build.

@Override
public Selector build() {
    Selector selectorCopy = new Selector();
    Set<OrderBy> orderingCopy = this.copyOrderingSet();
    Set<Predicate> predicatesCopy = this.copyPredicatesSet();
    selectorCopy.getFields().addAll(Sets.newLinkedHashSet(this.fields));
    selectorCopy.getOrdering().addAll(orderingCopy);
    selectorCopy.getPredicates().addAll(predicatesCopy);
    if (this.dateRange != null) {
        DateRange newDateRange = new DateRange();
        newDateRange.setMin(this.dateRange.getMin());
        newDateRange.setMax(this.dateRange.getMax());
        selectorCopy.setDateRange(newDateRange);
    }
    if (this.paging != null) {
        Paging newPaging = new Paging();
        newPaging.setStartIndex(this.paging.getStartIndex());
        newPaging.setNumberResults(this.paging.getNumberResults());
        selectorCopy.setPaging(newPaging);
    }
    return selectorCopy;
}
Also used : OrderBy(com.google.api.ads.adwords.jaxws.v201809.cm.OrderBy) DateRange(com.google.api.ads.adwords.jaxws.v201809.cm.DateRange) Paging(com.google.api.ads.adwords.jaxws.v201809.cm.Paging) Selector(com.google.api.ads.adwords.jaxws.v201809.cm.Selector) Predicate(com.google.api.ads.adwords.jaxws.v201809.cm.Predicate)

Example 8 with Paging

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

the class SelectorBuilderImpl method increaseOffsetBy.

@Override
public SelectorBuilderImpl increaseOffsetBy(int additionalOffset) {
    if (this.paging == null) {
        this.paging = new Paging();
    }
    Integer startIndex = this.paging.getStartIndex();
    if (startIndex == null) {
        startIndex = 0;
    }
    this.paging.setStartIndex(startIndex + additionalOffset);
    return this;
}
Also used : Paging(com.google.api.ads.adwords.jaxws.v201809.cm.Paging)

Example 9 with Paging

use of com.google.api.ads.adwords.axis.v201809.cm.Paging 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

Paging (com.google.api.ads.adwords.axis.v201809.cm.Paging)4 Selector (com.google.api.ads.adwords.axis.v201809.cm.Selector)4 Paging (com.google.api.ads.adwords.jaxws.v201809.cm.Paging)2 ArrayList (java.util.ArrayList)2 Test (org.junit.Test)2 AxisSerializer (com.google.api.ads.adwords.axis.utils.AxisSerializer)1 AdGroupCriterionPage (com.google.api.ads.adwords.axis.v201809.cm.AdGroupCriterionPage)1 Campaign (com.google.api.ads.adwords.axis.v201809.cm.Campaign)1 CampaignPage (com.google.api.ads.adwords.axis.v201809.cm.CampaignPage)1 CampaignServiceInterface (com.google.api.ads.adwords.axis.v201809.cm.CampaignServiceInterface)1 DateRange (com.google.api.ads.adwords.axis.v201809.cm.DateRange)1 Language (com.google.api.ads.adwords.axis.v201809.cm.Language)1 Money (com.google.api.ads.adwords.axis.v201809.cm.Money)1 NetworkSetting (com.google.api.ads.adwords.axis.v201809.cm.NetworkSetting)1 OrderBy (com.google.api.ads.adwords.axis.v201809.cm.OrderBy)1 Predicate (com.google.api.ads.adwords.axis.v201809.cm.Predicate)1 Attribute (com.google.api.ads.adwords.axis.v201809.o.Attribute)1 AttributeType (com.google.api.ads.adwords.axis.v201809.o.AttributeType)1 DoubleAttribute (com.google.api.ads.adwords.axis.v201809.o.DoubleAttribute)1 IntegerSetAttribute (com.google.api.ads.adwords.axis.v201809.o.IntegerSetAttribute)1