com.google.api.ads.adwords.lib.client.AdWordsSession Java Examples

The following examples show how to use com.google.api.ads.adwords.lib.client.AdWordsSession. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AddShoppingCampaignForShowcaseAds.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/** Uploads an image. */
private static long uploadImage(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, String url)
    throws IOException {
  MediaServiceInterface mediaService = adWordsServices.get(session, MediaServiceInterface.class);

  // Create image.
  Image image = new Image();
  image.setData(com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl(url));
  image.setType(MediaMediaType.IMAGE);

  Media[] media = new Media[] {image};

  // Upload image.
  Media[] result = mediaService.upload(media);

  return result[0].getMediaId();
}
 
Example #2
Source File: ManagedCustomerServiceDelegateTest.java    From aw-reporting with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws ApiException {
  managedCustomer = new ManagedCustomer();
  managedCustomer.setCustomerId(123L);
  managedCustomer.setCanManageClients(false);
  ManagedCustomerPage managedCustomerPage 
    = new ManagedCustomerPage();
  managedCustomerPage.getEntries().add(managedCustomer);
  managedCustomerPage.setTotalNumEntries(1);

  MockitoAnnotations.initMocks(this);

  when(managedCustomerServiceInterfaceMock.get(
      Mockito.<Selector>anyObject())).thenReturn(managedCustomerPage);
      
  managedCustomerDelegate = new ManagedCustomerDelegate(null, false) {
    @Override
    ManagedCustomerServiceInterface getManagedCustomerServiceInterface(
        AdWordsSession adWordsSession){
      return managedCustomerServiceInterfaceMock;
    }
  };
}
 
Example #3
Source File: AdWordsJaxWsHeaderHandler.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * @see HeaderHandler#setHeaders(Object,
 *      com.google.api.ads.common.lib.client.AdsSession,
 *      com.google.api.ads.common.lib.client.AdsServiceDescriptor)
 */
@Override
public void setHeaders(Object soapClient, AdWordsSession adWordsSession,
    AdWordsServiceDescriptor adWordsServiceDescriptor) throws AuthenticationException,
    ServiceException {
  Preconditions.checkArgument(
      soapClient instanceof BindingProvider,
      "soapClient must be BindingProvider but was: %s",
      soapClient);
  BindingProvider bindingProvider = (BindingProvider) soapClient;

  Map<String, Object> headerData = readHeaderElements(adWordsSession);
  setAuthenticationHeaders(soapClient, headerData, adWordsSession);
  soapClientHandler.setHeader(
      bindingProvider, null, null, constructSoapHeader(headerData, adWordsServiceDescriptor));
  soapClientHandler.setCompression(bindingProvider, adsLibConfiguration.isCompressionEnabled());
  soapClientHandler.setRequestTimeout(
      bindingProvider, adsLibConfiguration.getSoapRequestTimeout());
}
 
Example #4
Source File: ProductPartitionTreeImpl.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the {@link BiddingStrategyConfiguration} of an ad group.
 *
 * @param services the AdWordsServices
 * @param session the session to use for the request
 * @param adGroupId the ad group ID
 * @return the non-null BiddingStrategyConfiguration of the ad group
 */
private static BiddingStrategyConfiguration getAdGroupBiddingStrategyConfiguration(
    AdWordsServicesInterface services, AdWordsSession session, Long adGroupId)
    throws ApiException, RemoteException {
  AdGroupServiceInterface adGroupService = services.get(session, AdGroupServiceInterface.class);

  Selector selector = new SelectorBuilder()
      .fields(
          AdGroupField.Id,
          AdGroupField.BiddingStrategyType,
          AdGroupField.BiddingStrategyId,
          AdGroupField.BiddingStrategyName)
      .equalsId(adGroupId).build();

  AdGroupPage adGroupPage = adGroupService.get(selector);

  if (adGroupPage.getEntries() == null || adGroupPage.getEntries().length == 0) {
    throw new IllegalArgumentException("No ad group found with ID " + adGroupId);
  }

  AdGroup adGroup = adGroupPage.getEntries(0);

  Preconditions.checkState(adGroup.getBiddingStrategyConfiguration() != null,
      "Unexpected state - ad group ID %s has a null BiddingStrategyConfiguration", adGroupId);
  return adGroup.getBiddingStrategyConfiguration();
}
 
Example #5
Source File: AdWordsServicesWithRateLimiter.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Decide whether this RateLimiter extension is applicable to the original service / utility
 * object. If so, wrap it in a proxy object with rate-limit-aware invocation handle; if not, just
 * return the original object.
 */
private <T> T getProxyObject(
    T originalObject, AdWordsSession session, Class<T> cls, boolean isUtility) {
  // Find the retry strategy of this class type.
  ApiRetryStrategy retryStrategy =
      ApiRetryStrategyManager.getRetryStrategy(cls.getSimpleName(), isUtility);

  // If no corresponding retry strategy, just use the original object instead of a wrapping proxy.
  if (retryStrategy == null) {
    return originalObject;
  }

  InvocationHandler invocationHandler =
      new ApiInvocationHandlerWithRateLimiter(originalObject, session, retryStrategy);
  return Reflection.newProxy(cls, invocationHandler);
}
 
Example #6
Source File: CreateAdWordsSessionWithoutPropertiesFile.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private static AdWordsSession createAdWordsSession(String clientId, String clientSecret,
    String refreshToken, String developerToken, String userAgent) throws OAuthException,
    ValidationException {
  // Create a valid OAuth2 credential without using a properties file.
  Credential credential = new OfflineCredentials.Builder()
      .forApi(Api.ADWORDS)
      .withClientSecrets(clientId, clientSecret)
      .withRefreshToken(refreshToken)
      .build()
      .generateCredential();

  // Create a new AdWordsSession without using a properties file.
  return new AdWordsSession.Builder()
      .withDeveloperToken(developerToken)
      .withUserAgent(userAgent)
      .withOAuth2Credential(credential)
      // NOTE: If you are copying this as a template for use with other services you should set
      // the clientCustomerId of the AdWordsSession as shown in the commented out line below. The
      // CustomerService.getCustomers method (called in this example) is one of the few methods
      // in the AdWords API where the clientCustomerId is optional. See
      // https://developers.google.com/adwords/api/docs/guides/call-structure#request_headers
      // for details.
      // .withClientCustomerId("INSERT_CLIENT_CUSTOMER_ID_HERE")
      .build();
}
 
Example #7
Source File: ApiInvocationHandlerWithRateLimiterTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the {@link ApiInvocationHandlerWithRateLimiter} class holds an AdWordsSession
 * reference, instead of creating a copy of it.
 */
@Test
public void testCidChangeInAdWordsSession() throws ValidationException {
  AdWordsSession session = AdWordsSessionUtilTest.getTestAdWordsSessionWithoutCid();
  session.setClientCustomerId(TEST_CID1);
  Object obj = new Object();

  // Don't use ApiServicesRetryStrategy, because in ApiRateLimiterTest we need to change system
  // settings before creating its instance for the expected testing behavior!
  ApiRetryStrategy retryStrategy = ApiReportingRetryStrategy.newInstance();
  ApiInvocationHandlerWithRateLimiter awapiInvocationHandler =
      new ApiInvocationHandlerWithRateLimiter(obj, session, retryStrategy);

  assertSame(
      "Same adwords session object check.", session, awapiInvocationHandler.getAdWordsSession());
  assertTrue(
      "AdWordsSession cid1 check",
      awapiInvocationHandler.getAdWordsSession().getClientCustomerId().equals(TEST_CID1));

  session.setClientCustomerId(TEST_CID2);
  assertSame(
      "Same adwords session object check.", session, awapiInvocationHandler.getAdWordsSession());
  assertTrue(
      "AdWordsSession cid2 check",
      awapiInvocationHandler.getAdWordsSession().getClientCustomerId().equals(TEST_CID2));
}
 
Example #8
Source File: AddCampaignGroupsAndPerformanceTargets.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/** Creates a campaign group. */
private static CampaignGroup createCampaignGroup(
    AdWordsServicesInterface adWordsServices, AdWordsSession session)
    throws RemoteException {
  // Get the CampaignGroupService.
  CampaignGroupServiceInterface campaignGroupService =
      adWordsServices.get(session, CampaignGroupServiceInterface.class);

  // Create the campaign group.
  CampaignGroup campaignGroup = new CampaignGroup();
  campaignGroup.setName("Mars campaign group #" + System.currentTimeMillis());

  // Create the operation.
  CampaignGroupOperation operation = new CampaignGroupOperation();
  operation.setOperand(campaignGroup);
  operation.setOperator(Operator.ADD);

  CampaignGroup newCampaignGroup =
      campaignGroupService.mutate(new CampaignGroupOperation[] {operation}).getValue(0);
  System.out.printf(
      "Campaign group with ID %d and name '%s' was created.%n",
      newCampaignGroup.getId(), newCampaignGroup.getName());

  return newCampaignGroup;
}
 
Example #9
Source File: AdWordsServiceClientFactoryHelper.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param adsServiceClientFactory the ads service client factory
 * @param adsServiceDescriptorFactory the ads service descriptor factory
 * @param soapClientHandler the SOAP client handler
 * @param adsLibConfiguration the lib configuration
 */
@SuppressWarnings("unchecked") /* See comments on soapClientHandler argument. */
@Inject
public AdWordsServiceClientFactoryHelper(
    AdsServiceClientFactoryInterface<AdWordsServiceClient,
                                     AdWordsSession,
                                     AdWordsServiceDescriptor> adsServiceClientFactory,
    AdsServiceDescriptorFactoryInterface<AdWordsServiceDescriptor> adsServiceDescriptorFactory,
    @SuppressWarnings("rawtypes") /* Guice binding for SoapClientHandlerInterface does not include
                                   * the type argument T because it is bound in the SOAP
                                   * toolkit-agnostic configuration module. Therefore, must use
                                   * the raw type here. */
    SoapClientHandlerInterface soapClientHandler,
    AdsLibConfiguration adsLibConfiguration) {
  super(adsServiceClientFactory, adsServiceDescriptorFactory, soapClientHandler);
  this.adsLibConfiguration = adsLibConfiguration;
}
 
Example #10
Source File: UploadMediaBundle.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @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 IOException if unable to get media data from the URL.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
    throws IOException {
  // Get the MediaService.
  MediaServiceInterface mediaService = adWordsServices.get(session, MediaServiceInterface.class);

  // Create HTML5 media.
  byte[] html5Zip =
      com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl("https://goo.gl/9Y7qI2");

  // Create a media bundle containing the zip file with all the HTML5 components.
  MediaBundle mediaBundle = new MediaBundle();
  mediaBundle.setData(html5Zip);
  mediaBundle.setType(MediaMediaType.MEDIA_BUNDLE);

  // Upload HTML5 zip.
  mediaBundle = (MediaBundle) mediaService.upload(new Media[] {mediaBundle})[0];

  // Display HTML5 zip.
  Map<MediaSize, Dimensions> dimensions = Maps.toMap(mediaBundle.getDimensions());
  System.out.printf(
      "HTML5 media with ID %d, dimensions '%dx%d', and MIME type '%s' "
      + "was uploaded.%n",
      mediaBundle.getMediaId(), dimensions.get(MediaSize.FULL).getWidth(),
      dimensions.get(MediaSize.FULL).getHeight(), mediaBundle.getMimeType());
}
 
Example #11
Source File: GetReportFields.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @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) throws RemoteException {
  // Get the ReportDefinitionService.
  ReportDefinitionServiceInterface reportDefinitionService =
      adWordsServices.get(session, ReportDefinitionServiceInterface.class);

  // Get report fields.
  ReportDefinitionField[] reportDefinitionFields =
      reportDefinitionService
          .getReportFields(ReportDefinitionReportType.KEYWORDS_PERFORMANCE_REPORT);

  // Display report fields.
  System.out.println("Available fields for report:");

  for (ReportDefinitionField reportDefinitionField : reportDefinitionFields) {
    System.out.printf("\t %s(%s) := [", reportDefinitionField.getFieldName(),
        reportDefinitionField.getFieldType());
    if (reportDefinitionField.getEnumValues() != null) {
      for (String enumValue : reportDefinitionField.getEnumValues()) {
        System.out.printf("%s, ", enumValue);
      }
    }
    System.out.println("]");
  }
}
 
Example #12
Source File: AdvancedCreateCredentialFromScratch.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private static AdWordsSession createAdWordsSession(String userId, DataStoreFactory storeFactory)
    throws IOException, ValidationException, ConfigurationLoadException {
  // Create a GoogleCredential with minimal information.
  GoogleAuthorizationCodeFlow authorizationFlow = new GoogleAuthorizationCodeFlow.Builder(
      new NetHttpTransport(),
      new JacksonFactory(),
      CLIENT_ID,
      CLIENT_SECRET,
      Arrays.asList(SCOPE))
      .setDataStoreFactory(storeFactory)
      .build();

  // Load the credential.
  Credential credential = authorizationFlow.loadCredential(userId);

  // Construct an AdWordsSession using the default ads.properties file to set the session's
  // developer token, client customer ID, etc., but use the credentials created above.
  return new AdWordsSession.Builder()
      .fromFile()
      .withOAuth2Credential(credential)
      .build();
}
 
Example #13
Source File: RemoveCampaign.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param campaignId the ID of the campaign to remove.
 * @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 campaignId)
    throws RemoteException {
  // Get the CampaignService.
  CampaignServiceInterface campaignService =
      adWordsServices.get(session, CampaignServiceInterface.class);

  // Create campaign with REMOVED status.
  Campaign campaign = new Campaign();
  campaign.setId(campaignId);
  campaign.setStatus(CampaignStatus.REMOVED);

  // Create operations.
  CampaignOperation operation = new CampaignOperation();
  operation.setOperand(campaign);
  operation.setOperator(Operator.SET);

  CampaignOperation[] operations = new CampaignOperation[] {operation};

  // Remove campaign.
  CampaignReturnValue result = campaignService.mutate(operations);

  // Display campaigns.
  for (Campaign campaignResult : result.getValue()) {
    System.out.printf("Campaign with name '%s' and ID %d was removed.%n",
        campaignResult.getName(), campaignResult.getId());
  }
}
 
Example #14
Source File: AdWordsJaxWsHeaderHandlerTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetAuthenticationHeaders() throws Exception {
  Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod());
  Object soapClient = new Object();
  Map<String, Object> headerElements = new HashMap<String, Object>();
  AdWordsSession adWordsSession = new AdWordsSession.Builder().withOAuth2Credential(credential)
      .withDeveloperToken("developerToken").withUserAgent(USER_AGENT).build();

  headerHandler.setAuthenticationHeaders(soapClient, headerElements, adWordsSession);

  verify(authorizationHeaderHandler).setAuthorization(soapClient, adWordsSession);
}
 
Example #15
Source File: AdWordsAxisSoapIntegrationTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testGoldenSoap_oauth2_offlineCredentials() throws Exception {
  testHttpServer.setMockResponseBodies(Lists.newArrayList(
      AuthResponseProvider.getTestOAuthResponse("TEST_ACCESS_TOKEN_1", 1L, "newRefreshToken1"),
      AuthResponseProvider.getTestOAuthResponse("TEST_ACCESS_TOKEN_2", 3600L, "newRefreshToken2"),
      SoapResponseXmlProvider.getTestSoapResponse(API_VERSION)));

  OfflineCredentials offlineCredentials =
      new OfflineCredentials.Builder()
          .forApi(OfflineCredentials.Api.ADWORDS)
          .withTokenUrlServer(testHttpServer.getServerUrl())
          .fromFile(AdWordsAxisSoapIntegrationTest.class.getResource("props/ads-test.properties"))
          .build();
  
  Credential credential = offlineCredentials.generateCredential();

  assertTrue(testHttpServer.getLastRequestBody().contains("grant_type=refresh_token"));
  assertTrue(testHttpServer.getLastRequestBody().contains("refresh_token=refreshToken"));
  assertTrue(testHttpServer.getLastRequestBody().contains("client_id=clientId"));
  assertTrue(testHttpServer.getLastRequestBody().contains("client_secret=clientSecret"));

  // Make sure the old token expires - the session builder should issue a request
  // for another access token.
  Thread.sleep(1000);

  assertEquals("TEST_ACCESS_TOKEN_1", credential.getAccessToken());

  AdWordsSession session = new AdWordsSession.Builder()
      .withUserAgent("TEST_APP")
      .withOAuth2Credential(credential)
      .withEndpoint(testHttpServer.getServerUrl())
      .withDeveloperToken("TEST_DEVELOPER_TOKEN")
      .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID")
      .build();

  testBudgetServiceMutateRequest(session);

  assertEquals("Bearer TEST_ACCESS_TOKEN_2", testHttpServer.getLastAuthorizationHttpHeader());
}
 
Example #16
Source File: SetBidModifier.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param campaignId the ID of the campaign.
 * @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 campaignId)
    throws RemoteException {
  // Get the CampaignCriterionService.
  CampaignCriterionServiceInterface campaignCriterionService =
      adWordsServices.get(session, CampaignCriterionServiceInterface.class);

  // Create mobile platform. The ID can be found in the documentation.
  // https://developers.google.com/adwords/api/docs/appendix/platforms
  Platform mobile = new Platform();
  mobile.setId(30001L);

  // Create criterion with modified bid.
  CampaignCriterion campaignCriterion = new CampaignCriterion();
  campaignCriterion.setCampaignId(campaignId);
  campaignCriterion.setCriterion(mobile);
  campaignCriterion.setBidModifier(BID_MODIFIER);

  // Create SET operation.
  CampaignCriterionOperation operation = new CampaignCriterionOperation();
  operation.setOperand(campaignCriterion);
  operation.setOperator(Operator.SET);

  // Update campaign criterion.
  CampaignCriterionReturnValue result =
      campaignCriterionService.mutate(new CampaignCriterionOperation[] {operation});
  for (CampaignCriterion campaignCriterionResult : result.getValue()) {
    System.out.printf("Campaign criterion with campaign ID %d, criterion ID %d, "
        + "and type '%s' was modified with bid %.4f.%n",
        campaignCriterionResult.getCampaignId(),
        campaignCriterionResult.getCriterion().getId(),
        campaignCriterionResult.getCriterion().getType(),
        campaignCriterionResult.getBidModifier());
  }
}
 
Example #17
Source File: UpdateExpandedTextAd.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adId the ID of the ad to update.
 * @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 adId)
    throws RemoteException {
  // Get the AdService.
  AdServiceInterface adService = adWordsServices.get(session, AdServiceInterface.class);

  // Creates an expanded text ad using the provided ad ID.
  ExpandedTextAd expandedTextAd = new ExpandedTextAd();
  expandedTextAd.setId(adId);
  // Updates some properties of the expanded text ad.
  expandedTextAd.setHeadlinePart1("Cruise to Pluto #" + System.currentTimeMillis());
  expandedTextAd.setHeadlinePart2("Tickets on sale now");
  expandedTextAd.setDescription("Best space cruise ever.");
  expandedTextAd.setFinalUrls(new String[] {"http://www.example.com/"});
  expandedTextAd.setFinalMobileUrls(new String[] {"http://www.example.com/mobile"});

  // Creates ad group ad operation and adds it to the list.
  AdOperation operation = new AdOperation();
  operation.setOperator(Operator.SET);
  operation.setOperand(expandedTextAd);

  // Updates the ad on the server.
  ExpandedTextAd updatedAd =
      (ExpandedTextAd) adService.mutate(new AdOperation[] {operation}).getValue(0);

  // Prints out some information.
  System.out.printf("Expanded text ad with ID %d was updated.%n", updatedAd.getId());
  System.out.printf(
      "Headline part 1 is '%s'.%nHeadline part 2 is '%s'.%nDescription is '%s'.%n",
      updatedAd.getHeadlinePart1(), updatedAd.getHeadlinePart2(), updatedAd.getDescription());
  System.out.printf(
      "Final URL is '%s'.%nFinal mobile URL is '%s'.%n",
      updatedAd.getFinalUrls()[0], updatedAd.getFinalMobileUrls()[0]);
}
 
Example #18
Source File: CreateAccount.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @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) throws RemoteException {
  // Get the CampaignService.
  ManagedCustomerServiceInterface managedCustomerService =
      adWordsServices.get(session, ManagedCustomerServiceInterface.class);

  // Create account.
  ManagedCustomer customer = new ManagedCustomer();
  customer.setName("Customer created with ManagedCustomerService on " + new DateTime());
  customer.setCurrencyCode("EUR");
  customer.setDateTimeZone("Europe/London");

  // Create operations.
  ManagedCustomerOperation operation = new ManagedCustomerOperation();
  operation.setOperand(customer);
  operation.setOperator(Operator.ADD);

  ManagedCustomerOperation[] operations = new ManagedCustomerOperation[] {operation};

  // Add account.
  ManagedCustomerReturnValue result = managedCustomerService.mutate(operations);

  // Display accounts.
  for (ManagedCustomer customerResult : result.getValue()) {
    System.out.printf("Account with customer ID %d was created.%n",
        customerResult.getCustomerId());
  }
}
 
Example #19
Source File: UploadImageAsset.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @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 IOException if unable to get media data from the URL.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
    throws IOException {
  // Get the AssetService.
  AssetServiceInterface assetService = adWordsServices.get(session, AssetServiceInterface.class);

  // Create the image asset.
  ImageAsset image = new ImageAsset();
  // Optional: Provide a unique friendly name to identify your asset. If you specify the assetName
  // field, then both the asset name and the image being uploaded should be unique, and should not
  // match another ACTIVE asset in this customer account.
  // image.setAssetName("Jupiter Trip #" + System.currentTimeMillis());
  image.setImageData(
      com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl("https://goo.gl/3b9Wfh"));

  // Create the operation.
  AssetOperation operation = new AssetOperation();
  operation.setOperator(Operator.ADD);
  operation.setOperand(image);

  // Create the asset.
  AssetReturnValue result = assetService.mutate(new AssetOperation[] {operation});

  // Display the results.
  if (result != null && result.getValue() != null && result.getValue().length > 0) {
    Asset newAsset = result.getValue(0);
    System.out.printf(
        "Image asset with ID %d and name '%s' was created.%n",
        newAsset.getAssetId(), newAsset.getAssetName());
  } else {
    System.out.println("No image asset was created.");
  }
}
 
Example #20
Source File: AdWordsJaxWsSoapTimeoutIntegrationTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that the request timeout in ads.properties is enforced.
 */
@Test
public void testRequestTimeoutEnforced() throws Exception {
  testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION));
  testHttpServer.setDelay(200L);
  
  GoogleCredential credential = new GoogleCredential.Builder().setTransport(
      new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build();
  credential.setAccessToken("TEST_ACCESS_TOKEN");

  AdWordsSession session = new AdWordsSession.Builder()
      .withUserAgent("TEST_APP")
      .withOAuth2Credential(credential)
      .withEndpoint(testHttpServer.getServerUrl())
      .withDeveloperToken("TEST_DEVELOPER_TOKEN")
      .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID")
      .build();

  BudgetServiceInterface budgetService =
      new AdWordsServices().get(session, BudgetServiceInterface.class);
  
  Budget budget = new Budget();
  budget.setName("Test Budget Name");
  Money money = new Money();
  money.setMicroAmount(50000000L);
  budget.setAmount(money);
  budget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

  BudgetOperation operation = new BudgetOperation();
  operation.setOperand(budget);
  operation.setOperator(Operator.ADD);
  
  thrown.expect(WebServiceException.class);
  thrown.expectMessage("Read timed out");
  budgetService.mutate(Lists.newArrayList(operation));
}
 
Example #21
Source File: CreateAdWordsSessionWithoutPropertiesFile.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
    throws RemoteException {
  CustomerServiceInterface customerService =
      adWordsServices.get(session, CustomerServiceInterface.class);
  // Sends a getCustomers request, which will return all customers to which the session's OAuth
  // credentials have direct access.
  System.out.println("You are logged in as a user with access to the following customers:");
  for (Customer customer : customerService.getCustomers()) {
    System.out.printf("  %s%n", customer.getCustomerId());
  }
}
 
Example #22
Source File: GetCampaigns.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @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) throws RemoteException {
  // Get the CampaignService.
  CampaignServiceInterface campaignService =
      adWordsServices.get(session, CampaignServiceInterface.class);

  int offset = 0;

  // Create selector.
  SelectorBuilder builder = new SelectorBuilder();
  Selector selector = builder
      .fields(CampaignField.Id, CampaignField.Name)
      .orderAscBy(CampaignField.Name)
      .offset(offset)
      .limit(PAGE_SIZE)
      .build();

  CampaignPage page;
  do {
    // Get all campaigns.
    page = campaignService.get(selector);

    // 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.");
    }

    offset += PAGE_SIZE;
    selector = builder.increaseOffsetBy(PAGE_SIZE).build();
  } while (offset < page.getTotalNumEntries());
}
 
Example #23
Source File: AlertProcessor.java    From adwords-alerting with Apache License 2.0 5 votes vote down vote up
/**
 * Uses the API to retrieve the managed accounts, and extract their IDs.
 *
 * @param session the adwords session
 * @return the client customer IDs for all the managed accounts
 */
private Set<Long> retrieveClientCustomerIds(AdWordsSession session)
    throws AlertProcessingException {
  try {
    LOGGER.info("Client customer IDs being recovered from the API. This may take a while...");
    return new ManagedCustomerDelegate(session).getClientCustomerIds();
  } catch (ApiException e) {
    throw new AlertProcessingException(
        "Encountered API error while getting client customer IDs.", e);
  }
}
 
Example #24
Source File: AddShoppingCampaignForShowcaseAds.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Creates a Showcase ad. */
private static AdGroupAd createShowcaseAd(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, AdGroup adGroup)
    throws IOException {
  // Create the Showcase ad.
  AdGroupAdServiceInterface adGroupAdService =
      adWordsServices.get(session, AdGroupAdServiceInterface.class);
  ShowcaseAd showcaseAd = new ShowcaseAd();
  showcaseAd.setName("Showcase ad #" + System.currentTimeMillis());
  showcaseAd.setFinalUrls(new String[] {"http://example.com/showcase"});
  showcaseAd.setDisplayUrl("example.com");

  // Required: Set the ad's expanded image.
  Image expandedImage = new Image();
  expandedImage.setMediaId(uploadImage(adWordsServices, session, "https://goo.gl/IfVlpF"));
  showcaseAd.setExpandedImage(expandedImage);

  // Optional: Set the collapsed image.
  Image collapsedImage = new Image();
  collapsedImage.setMediaId(uploadImage(adWordsServices, session, "https://goo.gl/NqTxAE"));
  showcaseAd.setCollapsedImage(collapsedImage);

  // Create ad group ad.
  AdGroupAd adGroupAd = new AdGroupAd();
  adGroupAd.setAdGroupId(adGroup.getId());
  adGroupAd.setAd(showcaseAd);

  // Create operation.
  AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation();
  adGroupAdOperation.setOperand(adGroupAd);
  adGroupAdOperation.setOperator(Operator.ADD);

  // Make the mutate request.
  AdGroupAdReturnValue adGroupAdAddResult =
      adGroupAdService.mutate(new AdGroupAdOperation[] {adGroupAdOperation});

  return adGroupAdAddResult.getValue(0);
}
 
Example #25
Source File: AdWordsSessionUtilTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testCidWithoutDash() throws ValidationException {
  AdWordsSession session = getTestAdWordsSessionWithoutCid();
  session.setClientCustomerId(CID_WITHOUT_DASH);
  assertEquals(
      "Valid cid without dash test failed.",
      CID_VALID,
      AdWordsSessionUtil.getClientCustomerId(session));
}
 
Example #26
Source File: AddCampaignLabels.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param campaignIds the IDs of the campaigns to which the label will be added.
 * @param labelId the ID of the label to attach to campaigns.
 * @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,
    List<Long> campaignIds, Long labelId) throws RemoteException {
  // Get the CampaignService.
  CampaignServiceInterface campaignService =
      adWordsServices.get(session, CampaignServiceInterface.class);

  // Create label operations.
  List<CampaignLabelOperation> operations = new ArrayList<>(
      campaignIds.size());
  for (Long campaignId : campaignIds) {
    CampaignLabel campaignLabel = new CampaignLabel();
    campaignLabel.setCampaignId(campaignId);
    campaignLabel.setLabelId(labelId);

    CampaignLabelOperation operation = new CampaignLabelOperation();
    operation.setOperand(campaignLabel);
    operation.setOperator(Operator.ADD);

    operations.add(operation);
  }

  // Display campaign labels.
  for (CampaignLabel campaignLabelResult : campaignService.mutateLabel(
      operations.toArray(new CampaignLabelOperation[operations.size()])).getValue()) {
    System.out.printf("Campaign label for campaign ID %d and label ID %d was added.%n",
        campaignLabelResult.getCampaignId(), campaignLabelResult.getLabelId());
  }
}
 
Example #27
Source File: BaseAdWordsServices.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Override
public <UtilityT> UtilityT getUtility(AdWordsSession session, Class<UtilityT> utilityClass) {
  Preconditions.checkNotNull(session, "Null session");
  Preconditions.checkNotNull(utilityClass, "Null utility class");
  if (utilityClass.getAnnotation(SessionUtility.class) == null) {
    throw new IllegalArgumentException(
        utilityClass + " is not annotated with " + SessionUtility.class);
  }
  Injector childInjector = injector.createChildInjector(new AdWordsSessionModule(session));
  return childInjector.getInstance(utilityClass);
}
 
Example #28
Source File: AddDynamicSearchAdsCampaign.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @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)
    throws RemoteException {
  Budget budget = createBudget(adWordsServices, session);

  Campaign campaign = createCampaign(adWordsServices, session, budget);
  AdGroup adGroup = createAdGroup(adWordsServices, session, campaign);
  createExpandedDSA(adWordsServices, session, adGroup);
  addWebPageCriteria(adWordsServices, session, adGroup);
}
 
Example #29
Source File: AdHocReportDownloadHelperTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that the helper will throw a {@link ConnectException} wrapped in a
 * {@link ReportException} when the endpoint is for an unused port on localhost.
 */
@Test
public void testDownloadReportWithBadEndpoint_fails() throws Throwable {
  int port = TestPortFinder.getInstance().checkOutUnusedPort();

  try {
    // Construct the session to use an endpoint that is NOT in use on localhost.
    AdWordsSession sessionWithBadEndpoint =
        new AdWordsSession.Builder()
            .withUserAgent("TEST_APP")
            .withOAuth2Credential(credential)
            .withEndpoint("https://localhost:" + port)
            .withDeveloperToken("TEST_DEVELOPER_TOKEN")
            .withClientCustomerId("TEST_CLIENT_CUSTOMER_ID")
            .build();
    helper =
        new GenericAdWordsServices()
            .getBootstrapper()
            .getInstanceOf(sessionWithBadEndpoint, AdHocReportDownloadHelper.class);
    // Set up the ReportRequest so it will pass basic validation.
    when(reportRequest.getRequestType()).thenReturn(RequestType.AWQL);
    String awqlString = "SELECT BadField1 FROM NOT_A_REPORT DURING NOT_A_TIME_PERIOD";
    when(reportRequest.getReportRequestString()).thenReturn(awqlString);
    // The cause should be a ConnectException (see expected annotation) since the endpoint
    // port is not in use.
    thrown.expect(ReportException.class);
    thrown.expectCause(Matchers.<Exception>instanceOf(ConnectException.class));
    downloadReport(); 
  } finally {
    TestPortFinder.getInstance().releaseUnusedPort(port);
  }
}
 
Example #30
Source File: AddSmartShoppingAd.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Smart Shopping ad group by setting the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS.
 */
private static AdGroup createSmartShoppingAdGroup(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, long campaignId)
    throws RemoteException {
  // Get the AdGroupService.
  AdGroupServiceInterface adGroupService =
      adWordsServices.get(session, AdGroupServiceInterface.class);

  // Create ad group.
  AdGroup adGroup = new AdGroup();
  adGroup.setCampaignId(campaignId);
  adGroup.setName("Smart Shopping ad group #" + System.currentTimeMillis());

  // Set the ad group type to SHOPPING_GOAL_OPTIMIZED_ADS.
  adGroup.setAdGroupType(AdGroupType.SHOPPING_GOAL_OPTIMIZED_ADS);

  // Create operation.
  AdGroupOperation adGroupOperation = new AdGroupOperation();
  adGroupOperation.setOperand(adGroup);
  adGroupOperation.setOperator(Operator.ADD);

  // Make the mutate request.
  AdGroupReturnValue adGroupAddResult =
      adGroupService.mutate(new AdGroupOperation[] {adGroupOperation});

  // Display result.
  adGroup = adGroupAddResult.getValue(0);
  System.out.printf(
      "Smart Shopping ad group with name '%s' and ID %d was added.%n",
      adGroup.getName(), adGroup.getId());

  return adGroup;
}