com.google.api.ads.adwords.axis.v201809.cm.Keyword Java Examples

The following examples show how to use com.google.api.ads.adwords.axis.v201809.cm.Keyword. 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: KeywordCollectionTest.java    From keyword-optimizer with Apache License 2.0 6 votes vote down vote up
/**
 * Check all keyword texts are in there.
 */
@Test
public void checkDuplicateKeywords() {
  assertEquals(3, keywords.size());

  // Add the same keyword as is.
  keywords.add(new KeywordInfo(plumbing, null, null, null));
  assertEquals(3, keywords.size());

  // Add the same keyword (different object).
  Keyword plumbing2 = new Keyword();
  plumbing2.setText("plumbing");
  plumbing2.setMatchType(KeywordMatchType.EXACT);
  keywords.add(new KeywordInfo(plumbing2, null, null, null));

  assertEquals(3, keywords.size());
}
 
Example #2
Source File: AddCompleteCampaignsUsingBatchJob.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private static List<CampaignCriterionOperation> buildCampaignCriterionOperations(
    List<CampaignOperation> campaignOperations) {
  List<CampaignCriterionOperation> operations = new ArrayList<>();
  for (CampaignOperation campaignOperation : campaignOperations) {
    Keyword keyword = new Keyword();
    keyword.setMatchType(KeywordMatchType.BROAD);
    keyword.setText("venus");

    NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();
    negativeCriterion.setCampaignId(campaignOperation.getOperand().getId());
    negativeCriterion.setCriterion(keyword);

    CampaignCriterionOperation operation = new CampaignCriterionOperation();
    operation.setOperand(negativeCriterion);
    operation.setOperator(Operator.ADD);

    operations.add(operation);
  }

  return operations;
}
 
Example #3
Source File: AxisBatchJobUploadBodyProviderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Override
protected void addCampaignNegativeKeywordOperation(
    BatchJobMutateRequest request, long campaignId, String keywordText, String keywordMatchType) {
  Keyword keyword = new Keyword();
  keyword.setText(keywordText);
  keyword.setMatchType(KeywordMatchType.fromString(keywordMatchType));

  NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();
  negativeCriterion.setCampaignId(campaignId);
  negativeCriterion.setCriterion(keyword);

  CampaignCriterionOperation operation = new CampaignCriterionOperation();
  operation.setOperand(negativeCriterion);
  operation.setOperator(Operator.ADD);

  request.addOperation(operation);
}
 
Example #4
Source File: KeywordCollection.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the distinct texts of all containing {@link Keyword}s.
 */
public Set<String> getContainingKeywordTexts() {
  Set<String> keywordTexts = new HashSet<>();

  for (Keyword keyword : keywords.keySet()) {
    keywordTexts.add(keyword.getText());
  }
  return keywordTexts;
}
 
Example #5
Source File: KeywordCollectionTest.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Setup some sample keywords.
 */
@Before
public void setUp() {
  plumbing = new Keyword();
  plumbing.setText("plumbing");
  plumbing.setMatchType(KeywordMatchType.EXACT);

  plumbingBroad = new Keyword();
  plumbingBroad.setText("plumbing");
  plumbingBroad.setMatchType(KeywordMatchType.BROAD);

  plumbingSpecialist = new Keyword();
  plumbingSpecialist.setText("plumbing specialist");
  plumbingSpecialist.setMatchType(KeywordMatchType.EXACT);

  newYork = new Location();
  newYork.setId(1023191L);

  english = new Language();
  english.setId(1000L);

  maxCpc = new Money();
  maxCpc.setMicroAmount(1000000L); // 1 usd

  campaignSettings =
      CampaignConfiguration.builder()
          .withMaxCpc(maxCpc)
          .withCriterion(english)
          .withCriterion(newYork)
          .build();
  keywords = new KeywordCollection(campaignSettings);
  
  keywords = new KeywordCollection(campaignSettings);
  keywords.add(new KeywordInfo(plumbing, null, null, null));
  keywords.add(new KeywordInfo(plumbingBroad, null, null, null));
  keywords.add(new KeywordInfo(plumbingSpecialist, null, null, null));
}
 
Example #6
Source File: KeywordCollectionScoreTest.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Setup some sample keywords.
 */
@Before
public void setUp() {
  alpha = new Keyword();
  alpha.setText("alpha");
  alpha.setMatchType(KeywordMatchType.EXACT);
  alphaInfo = new KeywordInfo(alpha, null, null, 3d);

  beta = new Keyword();
  beta.setText("beta");
  beta.setMatchType(KeywordMatchType.EXACT);
  betaInfo = new KeywordInfo(beta, null, null, 1d);

  betaBroad = new Keyword();
  betaBroad.setText("beta");
  betaBroad.setMatchType(KeywordMatchType.BROAD);
  betaBroadInfo = new KeywordInfo(betaBroad, null, null, 2d);

  gamma = new Keyword();
  gamma.setText("gamma");
  gamma.setMatchType(KeywordMatchType.EXACT);
  gammaInfo = new KeywordInfo(gamma, null, null, 4d);

  maxCpc = new Money();
  maxCpc.setMicroAmount(1000000L); // 1 usd

  CampaignConfiguration campaignSettings = CampaignConfiguration.builder()
      .withMaxCpc(maxCpc)
      .build();
  keywords = new KeywordCollection(campaignSettings);
  keywords.add(gammaInfo);
  keywords.add(betaInfo);
  keywords.add(alphaInfo);
  keywords.add(betaBroadInfo);
}
 
Example #7
Source File: AbstractSeedGenerator.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
@Override
public final KeywordCollection generate() throws KeywordOptimizerException {
  ImmutableMap<String, IdeaEstimate> keywordsAndEstimates = getKeywordsAndEstimates();

  KeywordCollection keywordCollection = new KeywordCollection(campaignConfiguration);

  for (Entry<String, IdeaEstimate> keywordEntry : keywordsAndEstimates.entrySet()) {
    for (KeywordMatchType matchType : matchTypes) {
      Keyword keyword = KeywordOptimizerUtil.createKeyword(keywordEntry.getKey(), matchType);
      keywordCollection.add(new KeywordInfo(keyword, keywordEntry.getValue(), null, null));
    }
  }

  return keywordCollection;
}
 
Example #8
Source File: TrafficEstimatorTest.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Setup some sample keywords.
 */
@Before
public void setUp() {
  plumbing = new Keyword();
  plumbing.setText("plumbing");
  plumbing.setMatchType(KeywordMatchType.EXACT);

  plumbingBroad = new Keyword();
  plumbingBroad.setText("plumbing");
  plumbingBroad.setMatchType(KeywordMatchType.BROAD);

  plumbingSpecialist = new Keyword();
  plumbingSpecialist.setText("plumbing specialist");
  plumbingSpecialist.setMatchType(KeywordMatchType.EXACT);

  maxCpc = new Money();
  maxCpc.setMicroAmount(1000000L); // 1 usd

  CampaignConfiguration campaignSettings = CampaignConfiguration.builder()
      .withMaxCpc(maxCpc)
      .build();
  keywords = new KeywordCollection(campaignSettings);
  keywords.add(new KeywordInfo(plumbing, null, null, null));
  keywords.add(new KeywordInfo(plumbingBroad, null, null, null));
  keywords.add(new KeywordInfo(plumbingSpecialist, null, null, null));

  minStats = new StatsEstimate();
  minStats.setClicksPerDay(10F);
  minStats.setImpressionsPerDay(1000F);

  maxStats = new StatsEstimate();
  maxStats.setClicksPerDay(20F);
  maxStats.setImpressionsPerDay(2000F);
}
 
Example #9
Source File: KeywordInfo.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link KeywordInfo} object with the given attributes.
 *
 * @param keyword the keyword itself
 * @param ideaEstimate statistics from the {@link TargetingIdeaService}
 * @param trafficEstimate the estimated traffic statistics
 * @param score the quality score
 */
public KeywordInfo(
    Keyword keyword,
    @Nullable IdeaEstimate ideaEstimate,
    @Nullable TrafficEstimate trafficEstimate,
    @Nullable Double score) {
  this.keyword = keyword;
  this.ideaEstimate = ideaEstimate;
  this.trafficEstimate = trafficEstimate;
  this.score = score;
}
 
Example #10
Source File: TisAlternativesFinder.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
@Override
public KeywordCollection derive(KeywordCollection keywords) throws KeywordOptimizerException {
  Map<String, IdeaEstimate> keywordsAndEstimates = getKeywordsAndEstimates(keywords);

  KeywordCollection alternatives = new KeywordCollection(keywords.getCampaignConfiguration());
  for (String keywordText : keywordsAndEstimates.keySet()) {
    for (KeywordMatchType matchType : keywords.getContainingMatchTypes()) {
      Keyword newKeyword = KeywordOptimizerUtil.createKeyword(keywordText, matchType);
      alternatives.add(
          new KeywordInfo(newKeyword, keywordsAndEstimates.get(keywordText), null, null));
    }
  }

  return alternatives;
}
 
Example #11
Source File: KeywordCollection.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the distinct match types of all containing {@link Keyword}s.
 */
public Set<KeywordMatchType> getContainingMatchTypes() {
  Set<KeywordMatchType> matchTypes = new HashSet<>();

  for (Keyword keyword : keywords.keySet()) {
    matchTypes.add(keyword.getMatchType());
  }

  return matchTypes;
}
 
Example #12
Source File: EvaluatorTest.java    From keyword-optimizer with Apache License 2.0 5 votes vote down vote up
/**
 * Setup some sample keywords.
 */
@Before
public void setUp() {
  plumbing = new Keyword();
  plumbing.setText("plumbing");
  plumbing.setMatchType(KeywordMatchType.EXACT);

  plumbingBroad = new Keyword();
  plumbingBroad.setText("plumbing");
  plumbingBroad.setMatchType(KeywordMatchType.BROAD);

  plumbingSpecialist = new Keyword();
  plumbingSpecialist.setText("plumbing specialist");
  plumbingSpecialist.setMatchType(KeywordMatchType.EXACT);

  maxCpc = new Money();
  maxCpc.setMicroAmount(1000000L); // 1 usd
  
  CampaignConfiguration campaignSettings = CampaignConfiguration.builder()
      .withMaxCpc(maxCpc)
      .build();
  keywords = new KeywordCollection(campaignSettings);
  keywords.add(new KeywordInfo(plumbing, IdeaEstimate.EMPTY_ESTIMATE, null, null));
  keywords.add(new KeywordInfo(plumbingBroad, IdeaEstimate.EMPTY_ESTIMATE, null, null));
  keywords.add(new KeywordInfo(plumbingSpecialist, IdeaEstimate.EMPTY_ESTIMATE, null, null));

  minStats = new StatsEstimate();
  minStats.setClicksPerDay(10F);
  minStats.setImpressionsPerDay(1000F);

  maxStats = new StatsEstimate();
  maxStats.setClicksPerDay(20F);
  maxStats.setImpressionsPerDay(2000F);

  clicksEvaluator =
      new EstimatorBasedEvaluator(new MockTrafficEstimator(), new ClicksScoreCalculator());

  impressionsEvaluator =
      new EstimatorBasedEvaluator(new MockTrafficEstimator(), new ImpressionsScoreCalculator());
}
 
Example #13
Source File: AddCompleteCampaignsUsingBatchJob.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #14
Source File: KeywordInfo.java    From keyword-optimizer with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the keyword.
 */
public Keyword getKeyword() {
  return keyword;
}
 
Example #15
Source File: CreateAndAttachSharedKeywordSet.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param campaignId the ID of the campaign that will use the shared set.
 * @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 SharedSetService.
  SharedSetServiceInterface sharedSetService =
      adWordsServices.get(session, SharedSetServiceInterface.class);

  // Keywords to include in the shared set.
  List<String> keywords = Arrays.asList("mars cruise", "mars hotels");

  // Create the shared negative keyword set.
  SharedSet sharedSet = new SharedSet();
  sharedSet.setName("Negative keyword list #" + System.currentTimeMillis());
  sharedSet.setType(SharedSetType.NEGATIVE_KEYWORDS);

  SharedSetOperation sharedSetOperation = new SharedSetOperation();
  sharedSetOperation.setOperator(Operator.ADD);
  sharedSetOperation.setOperand(sharedSet);

  // Add the shared set.
  sharedSet = sharedSetService.mutate(new SharedSetOperation[] {sharedSetOperation}).getValue(0);

  System.out.printf("Shared set with ID %d and name '%s' was successfully added.%n",
      sharedSet.getSharedSetId(), sharedSet.getName());

  // Add negative keywords to the shared set.
  List<SharedCriterionOperation> sharedCriterionOperations = new ArrayList<>();
  for (String keyword : keywords) {
    Keyword keywordCriterion = new Keyword();
    keywordCriterion.setText(keyword);
    keywordCriterion.setMatchType(KeywordMatchType.BROAD);

    SharedCriterion sharedCriterion = new SharedCriterion();
    sharedCriterion.setCriterion(keywordCriterion);
    sharedCriterion.setNegative(true);
    sharedCriterion.setSharedSetId(sharedSet.getSharedSetId());

    SharedCriterionOperation sharedCriterionOperation = new SharedCriterionOperation();
    sharedCriterionOperation.setOperator(Operator.ADD);
    sharedCriterionOperation.setOperand(sharedCriterion);

    sharedCriterionOperations.add(sharedCriterionOperation);
  }

  // Get the SharedCriterionService.
  SharedCriterionServiceInterface sharedCriterionService =
      adWordsServices.get(session, SharedCriterionServiceInterface.class);

  SharedCriterionReturnValue sharedCriterionReturnValue =
      sharedCriterionService.mutate(sharedCriterionOperations.toArray(
          new SharedCriterionOperation[sharedCriterionOperations.size()]));

  for (SharedCriterion addedCriterion : sharedCriterionReturnValue.getValue()) {
    System.out.printf("Added shared criterion ID %d with text '%s' to shared set with ID %d.%n",
        addedCriterion.getCriterion().getId(),
        ((Keyword) addedCriterion.getCriterion()).getText(), addedCriterion.getSharedSetId());
  }

  // Attach the negative keyword shared set to the campaign.
  CampaignSharedSetServiceInterface campaignSharedSetService =
      adWordsServices.get(session, CampaignSharedSetServiceInterface.class);

  CampaignSharedSet campaignSharedSet = new CampaignSharedSet();
  campaignSharedSet.setCampaignId(campaignId);
  campaignSharedSet.setSharedSetId(sharedSet.getSharedSetId());

  CampaignSharedSetOperation campaignSharedSetOperation = new CampaignSharedSetOperation();
  campaignSharedSetOperation.setOperator(Operator.ADD);
  campaignSharedSetOperation.setOperand(campaignSharedSet);

  campaignSharedSet = campaignSharedSetService.mutate(
      new CampaignSharedSetOperation[] {campaignSharedSetOperation}).getValue(0);

  System.out.printf("Shared set ID %d was attached to campaign ID %d.%n",
      campaignSharedSet.getSharedSetId(), campaignSharedSet.getCampaignId());
}
 
Example #16
Source File: AddKeywords.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adGroupId the ID of the ad group where the keywords will be created.
 * @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 UnsupportedEncodingException if encoding the final URL failed.
 */
public static void runExample(
    AdWordsServicesInterface adWordsServices, AdWordsSession session, long adGroupId)
    throws RemoteException, UnsupportedEncodingException {
  // Get the AdGroupCriterionService.
  AdGroupCriterionServiceInterface adGroupCriterionService =
      adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

  // Create keywords.
  Keyword keyword1 = new Keyword();
  keyword1.setText("mars cruise");
  keyword1.setMatchType(KeywordMatchType.BROAD);
  Keyword keyword2 = new Keyword();
  keyword2.setText("space hotel");
  keyword2.setMatchType(KeywordMatchType.EXACT);

  // Create biddable ad group criterion.
  BiddableAdGroupCriterion keywordBiddableAdGroupCriterion1 = new BiddableAdGroupCriterion();
  keywordBiddableAdGroupCriterion1.setAdGroupId(adGroupId);
  keywordBiddableAdGroupCriterion1.setCriterion(keyword1);

  // You can optionally provide these field(s).
  keywordBiddableAdGroupCriterion1.setUserStatus(UserStatus.PAUSED);

  String encodedFinalUrl = String.format("http://example.com/mars/cruise/?kw=%s",
      URLEncoder.encode(keyword1.getText(), UTF_8.name()));
  keywordBiddableAdGroupCriterion1.setFinalUrls(new UrlList(new String[] {encodedFinalUrl}));
  
  BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
  CpcBid bid = new CpcBid();
  bid.setBid(new Money(null, 10000000L));
  biddingStrategyConfiguration.setBids(new Bids[] {bid});
  keywordBiddableAdGroupCriterion1.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

  NegativeAdGroupCriterion keywordNegativeAdGroupCriterion2 = new NegativeAdGroupCriterion();
  keywordNegativeAdGroupCriterion2.setAdGroupId(adGroupId);
  keywordNegativeAdGroupCriterion2.setCriterion(keyword2);

  // Create operations.
  AdGroupCriterionOperation keywordAdGroupCriterionOperation1 = new AdGroupCriterionOperation();
  keywordAdGroupCriterionOperation1.setOperand(keywordBiddableAdGroupCriterion1);
  keywordAdGroupCriterionOperation1.setOperator(Operator.ADD);
  AdGroupCriterionOperation keywordAdGroupCriterionOperation2 = new AdGroupCriterionOperation();
  keywordAdGroupCriterionOperation2.setOperand(keywordNegativeAdGroupCriterion2);
  keywordAdGroupCriterionOperation2.setOperator(Operator.ADD);

  AdGroupCriterionOperation[] operations =
      new AdGroupCriterionOperation[] {keywordAdGroupCriterionOperation1,
          keywordAdGroupCriterionOperation2};

  // Add keywords.
  AdGroupCriterionReturnValue result = adGroupCriterionService.mutate(operations);

  // Display results.
  for (AdGroupCriterion adGroupCriterionResult : result.getValue()) {
    System.out.printf("Keyword ad group criterion with ad group ID %d, criterion ID %d, "
        + "text '%s', and match type '%s' was added.%n", adGroupCriterionResult.getAdGroupId(),
        adGroupCriterionResult.getCriterion().getId(),
        ((Keyword) adGroupCriterionResult.getCriterion()).getText(),
        ((Keyword) adGroupCriterionResult.getCriterion()).getMatchType());
  }
}
 
Example #17
Source File: GetKeywords.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
  }
}
 
Example #18
Source File: HandlePartialFailures.java    From googleads-java-lib with Apache License 2.0 4 votes vote down vote up
/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adGroupId the ID of the ad group.
 * @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 {
  // Enable partial failure.
  session.setPartialFailure(true);

  // Get the AdGroupCriterionService.
  AdGroupCriterionServiceInterface adGroupCriterionService =
      adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

  List<AdGroupCriterionOperation> operations = new ArrayList<>();

  // Create keywords.
  String[] keywords =
      new String[] {"mars cruise", "inv@lid cruise", "venus cruise", "b(a)d keyword cruise"};
  for (String keywordText : keywords) {
    // Create keyword
    Keyword keyword = new Keyword();
    keyword.setText(keywordText);
    keyword.setMatchType(KeywordMatchType.BROAD);

    // Create biddable ad group criterion.
    BiddableAdGroupCriterion keywordBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
    keywordBiddableAdGroupCriterion.setAdGroupId(adGroupId);
    keywordBiddableAdGroupCriterion.setCriterion(keyword);

    // Create operation.
    AdGroupCriterionOperation keywordAdGroupCriterionOperation = new AdGroupCriterionOperation();
    keywordAdGroupCriterionOperation.setOperand(keywordBiddableAdGroupCriterion);
    keywordAdGroupCriterionOperation.setOperator(Operator.ADD);
    operations.add(keywordAdGroupCriterionOperation);
  }

  // Add ad group criteria.
  AdGroupCriterionReturnValue result =
      adGroupCriterionService.mutate(operations.toArray(new AdGroupCriterionOperation[] {}));

  // Display results.
  Arrays.stream(result.getValue())
      .filter(adGroupCriterionResult -> adGroupCriterionResult.getCriterion() != null)
      .forEach(
          adGroupCriterionResult ->
              System.out.printf(
                  "Ad group criterion with ad group ID %d, and criterion ID %d, "
                      + "and keyword '%s' was added.%n",
                  adGroupCriterionResult.getAdGroupId(),
                  adGroupCriterionResult.getCriterion().getId(),
                  ((Keyword) adGroupCriterionResult.getCriterion()).getText()));

  for (ApiError apiError : result.getPartialFailureErrors()) {
    // Get the index of the failed operation from the error's field path elements.
    FieldPathElement[] fieldPathElements = apiError.getFieldPathElements();
    FieldPathElement firstFieldPathElement = null;
    if (fieldPathElements != null && fieldPathElements.length > 0) {
      firstFieldPathElement = fieldPathElements[0];
    }
    if (firstFieldPathElement != null
        && "operations".equals(firstFieldPathElement.getField())
        && firstFieldPathElement.getIndex() != null) {
      int operationIndex = firstFieldPathElement.getIndex();
      AdGroupCriterion adGroupCriterion = operations.get(operationIndex).getOperand();
      System.out.printf(
          "Ad group criterion with ad group ID %d and keyword '%s' "
              + "triggered a failure for the following reason: %s.%n",
          adGroupCriterion.getAdGroupId(),
          ((Keyword) adGroupCriterion.getCriterion()).getText(),
          apiError.getErrorString());
    } else {
      System.out.printf(
          "A failure has occurred for the following reason: %s%n", apiError.getErrorString());
    }
  }
}
 
Example #19
Source File: CreateCompleteCampaignBothApisPhase3.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates keywords ad group criteria.
 *
 * @param adWordsServices the Google AdWords services interface.
 * @param session the client session.
 * @param adGroup the ad group for the new criteria.
 * @param keywordsToAdd the keywords to add to the text ads.
 * @throws RemoteException if the API request failed due to other errors.
 * @throws UnsupportedEncodingException if encoding the final URL failed.
 */
private AdGroupCriterion[] createKeywords(
  AdWordsServicesInterface adWordsServices,
  AdWordsSession session,
  AdGroup adGroup,
  List<String> keywordsToAdd)
  throws RemoteException, UnsupportedEncodingException {
  // Gets the AdGroupCriterionService.
  AdGroupCriterionServiceInterface adGroupCriterionService =
    adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

  List<AdGroupCriterionOperation> operations = new ArrayList<>();

  for (String keywordToAdd : keywordsToAdd) {
    // Creates the keyword.
    Keyword keyword = new Keyword();
    keyword.setText(keywordToAdd);
    keyword.setMatchType(KeywordMatchType.EXACT);

    // Creates biddable ad group criterion.
    BiddableAdGroupCriterion keywordBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
    keywordBiddableAdGroupCriterion.setAdGroupId(adGroup.getId().getValue());
    keywordBiddableAdGroupCriterion.setCriterion(keyword);

    // You can optionally provide these field(s).
    keywordBiddableAdGroupCriterion.setUserStatus(UserStatus.PAUSED);

    String encodedFinalUrl =
      String.format(
        "http://example.com/mars/cruise/?kw=%s",
        URLEncoder.encode(keyword.getText(), UTF_8.name()));
    keywordBiddableAdGroupCriterion.setFinalUrls(new UrlList(new String[] {encodedFinalUrl}));

    // Creates the operation.
    AdGroupCriterionOperation keywordAdGroupCriterionOperation = new AdGroupCriterionOperation();
    keywordAdGroupCriterionOperation.setOperand(keywordBiddableAdGroupCriterion);
    keywordAdGroupCriterionOperation.setOperator(Operator.ADD);

    operations.add(keywordAdGroupCriterionOperation);
  }

  // Adds the keywords.
  AdGroupCriterionReturnValue result =
    adGroupCriterionService.mutate(operations.toArray(new AdGroupCriterionOperation[0]));

  // Displays the results.
  for (AdGroupCriterion adGroupCriterionResult : result.getValue()) {
    System.out.printf(
      "Keyword ad group criterion with ad group ID %d, criterion ID %d, "
        + "text '%s', and match type '%s' was added.%n",
      adGroupCriterionResult.getAdGroupId(),
      adGroupCriterionResult.getCriterion().getId(),
      ((Keyword) adGroupCriterionResult.getCriterion()).getText(),
      ((Keyword) adGroupCriterionResult.getCriterion()).getMatchType());
  }
  return result.getValue();
}
 
Example #20
Source File: KeywordCollection.java    From keyword-optimizer with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the set of contained {@link Keyword}s.
 */
public Set<Keyword> getKeywords() {
  return keywords.keySet();
}
 
Example #21
Source File: CreateCompleteCampaignBothApisPhase4.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates keywords ad group criteria.
 *
 * @param adWordsServices the Google AdWords services interface.
 * @param session the client session.
 * @param adGroup the ad group for the new criteria.
 * @param keywordsToAdd the keywords to add to the text ads.
 * @throws RemoteException if the API request failed due to other errors.
 * @throws UnsupportedEncodingException if encoding the final URL failed.
 */
private AdGroupCriterion[] createKeywords(
  AdWordsServicesInterface adWordsServices,
  AdWordsSession session,
  AdGroup adGroup,
  List<String> keywordsToAdd)
  throws RemoteException, UnsupportedEncodingException {
  // Gets the AdGroupCriterionService.
  AdGroupCriterionServiceInterface adGroupCriterionService =
    adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

  List<AdGroupCriterionOperation> operations = new ArrayList<>();

  for (String keywordToAdd : keywordsToAdd) {
    // Creates the keyword.
    Keyword keyword = new Keyword();
    keyword.setText(keywordToAdd);
    keyword.setMatchType(KeywordMatchType.EXACT);

    // Creates biddable ad group criterion.
    BiddableAdGroupCriterion keywordBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
    keywordBiddableAdGroupCriterion.setAdGroupId(adGroup.getId().getValue());
    keywordBiddableAdGroupCriterion.setCriterion(keyword);

    // You can optionally provide these field(s).
    keywordBiddableAdGroupCriterion.setUserStatus(UserStatus.PAUSED);

    String encodedFinalUrl =
      String.format(
        "http://example.com/mars/cruise/?kw=%s",
        URLEncoder.encode(keyword.getText(), UTF_8.name()));
    keywordBiddableAdGroupCriterion.setFinalUrls(new UrlList(new String[] {encodedFinalUrl}));

    // Creates the operation.
    AdGroupCriterionOperation keywordAdGroupCriterionOperation = new AdGroupCriterionOperation();
    keywordAdGroupCriterionOperation.setOperand(keywordBiddableAdGroupCriterion);
    keywordAdGroupCriterionOperation.setOperator(Operator.ADD);

    operations.add(keywordAdGroupCriterionOperation);
  }

  // Adds the keywords.
  AdGroupCriterionReturnValue result =
    adGroupCriterionService.mutate(operations.toArray(new AdGroupCriterionOperation[0]));

  // Displays the results.
  for (AdGroupCriterion adGroupCriterionResult : result.getValue()) {
    System.out.printf(
      "Keyword ad group criterion with ad group ID %d, criterion ID %d, "
        + "text '%s', and match type '%s' was added.%n",
      adGroupCriterionResult.getAdGroupId(),
      adGroupCriterionResult.getCriterion().getId(),
      ((Keyword) adGroupCriterionResult.getCriterion()).getText(),
      ((Keyword) adGroupCriterionResult.getCriterion()).getMatchType());
  }
  return result.getValue();
}
 
Example #22
Source File: CreateCompleteCampaignAdWordsApiOnly.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates keywords ad group criteria.
 *
 * @param adWordsServices the Google AdWords services interface.
 * @param session the client session.
 * @param adGroup the ad group for the new criteria.
 * @param keywordsToAdd the keywords to add to the text ads.
 * @throws RemoteException if the API request failed due to other errors.
 * @throws UnsupportedEncodingException if encoding the final URL failed.
 */
private AdGroupCriterion[] createKeywords(
    AdWordsServicesInterface adWordsServices,
    AdWordsSession session,
    AdGroup adGroup,
    List<String> keywordsToAdd)
    throws RemoteException, UnsupportedEncodingException {
  // Gets the AdGroupCriterionService.
  AdGroupCriterionServiceInterface adGroupCriterionService =
      adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

  List<AdGroupCriterionOperation> operations = new ArrayList<>();

  for (String keywordToAdd : keywordsToAdd) {
    // Creates the keyword.
    Keyword keyword = new Keyword();
    keyword.setText(keywordToAdd);
    keyword.setMatchType(KeywordMatchType.EXACT);

    // Creates the biddable ad group criterion.
    BiddableAdGroupCriterion keywordBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
    keywordBiddableAdGroupCriterion.setAdGroupId(adGroup.getId());
    keywordBiddableAdGroupCriterion.setCriterion(keyword);

    // You can optionally provide these field(s).
    keywordBiddableAdGroupCriterion.setUserStatus(UserStatus.PAUSED);

    String encodedFinalUrl =
        String.format(
            "http://example.com/mars/cruise/?kw=%s",
            URLEncoder.encode(keyword.getText(), UTF_8.name()));
    keywordBiddableAdGroupCriterion.setFinalUrls(new UrlList(new String[] {encodedFinalUrl}));

    // Creates the operation.
    AdGroupCriterionOperation keywordAdGroupCriterionOperation = new AdGroupCriterionOperation();
    keywordAdGroupCriterionOperation.setOperand(keywordBiddableAdGroupCriterion);
    keywordAdGroupCriterionOperation.setOperator(Operator.ADD);

    operations.add(keywordAdGroupCriterionOperation);
  }

  // Adds the keywords.
  AdGroupCriterionReturnValue result =
    adGroupCriterionService.mutate(operations.toArray(new AdGroupCriterionOperation[0]));

  // Displays the results.
  for (AdGroupCriterion adGroupCriterionResult : result.getValue()) {
    System.out.printf(
        "Keyword ad group criterion with ad group ID %d, criterion ID %d, "
            + "text '%s', and match type '%s' was added.%n",
        adGroupCriterionResult.getAdGroupId(),
        adGroupCriterionResult.getCriterion().getId(),
        ((Keyword) adGroupCriterionResult.getCriterion()).getText(),
        ((Keyword) adGroupCriterionResult.getCriterion()).getMatchType());
  }
  return result.getValue();
}
 
Example #23
Source File: CreateCompleteCampaignBothApisPhase1.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates keywords ad group criteria.
 *
 * @param adWordsServices the Google AdWords services interface.
 * @param session the client session.
 * @param adGroup the ad group for the new criteria.
 * @param keywordsToAdd the keywords to add to the text ads.
 * @throws RemoteException if the API request failed due to other errors.
 * @throws UnsupportedEncodingException if encoding the final URL failed.
 */
private AdGroupCriterion[] createKeywords(
  AdWordsServicesInterface adWordsServices,
  AdWordsSession session,
  AdGroup adGroup,
  List<String> keywordsToAdd)
  throws RemoteException, UnsupportedEncodingException {
  // Gets the AdGroupCriterionService.
  AdGroupCriterionServiceInterface adGroupCriterionService =
    adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

  List<AdGroupCriterionOperation> operations = new ArrayList<>();

  for (String keywordToAdd : keywordsToAdd) {
    // Creates the keyword.
    Keyword keyword = new Keyword();
    keyword.setText(keywordToAdd);
    keyword.setMatchType(KeywordMatchType.EXACT);

    // Creates the biddable ad group criterion.
    BiddableAdGroupCriterion keywordBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
    keywordBiddableAdGroupCriterion.setAdGroupId(adGroup.getId());
    keywordBiddableAdGroupCriterion.setCriterion(keyword);

    // You can optionally provide these field(s).
    keywordBiddableAdGroupCriterion.setUserStatus(UserStatus.PAUSED);

    String encodedFinalUrl =
      String.format(
        "http://example.com/mars/cruise/?kw=%s",
        URLEncoder.encode(keyword.getText(), UTF_8.name()));
    keywordBiddableAdGroupCriterion.setFinalUrls(new UrlList(new String[] {encodedFinalUrl}));

    // Creates the operation.
    AdGroupCriterionOperation keywordAdGroupCriterionOperation = new AdGroupCriterionOperation();
    keywordAdGroupCriterionOperation.setOperand(keywordBiddableAdGroupCriterion);
    keywordAdGroupCriterionOperation.setOperator(Operator.ADD);

    operations.add(keywordAdGroupCriterionOperation);
  }

  // Adds the keywords.
  AdGroupCriterionReturnValue result =
    adGroupCriterionService.mutate(operations.toArray(new AdGroupCriterionOperation[0]));

  // Displays the results.
  for (AdGroupCriterion adGroupCriterionResult : result.getValue()) {
    System.out.printf(
      "Keyword ad group criterion with ad group ID %d, criterion ID %d, "
        + "text '%s', and match type '%s' was added.%n",
      adGroupCriterionResult.getAdGroupId(),
      adGroupCriterionResult.getCriterion().getId(),
      ((Keyword) adGroupCriterionResult.getCriterion()).getText(),
      ((Keyword) adGroupCriterionResult.getCriterion()).getMatchType());
  }
  return result.getValue();
}
 
Example #24
Source File: CreateCompleteCampaignBothApisPhase2.java    From google-ads-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates keywords ad group criteria.
 *
 * @param adWordsServices the Google AdWords services interface.
 * @param session the client session.
 * @param adGroup the ad group for the new criteria.
 * @param keywordsToAdd the keywords to add to the text ads.
 * @throws RemoteException if the API request failed due to other errors.
 * @throws UnsupportedEncodingException if encoding the final URL failed.
 */
private AdGroupCriterion[] createKeywords(
  AdWordsServicesInterface adWordsServices,
  AdWordsSession session,
  AdGroup adGroup,
  List<String> keywordsToAdd)
  throws RemoteException, UnsupportedEncodingException {
  // Gets the AdGroupCriterionService.
  AdGroupCriterionServiceInterface adGroupCriterionService =
    adWordsServices.get(session, AdGroupCriterionServiceInterface.class);

  List<AdGroupCriterionOperation> operations = new ArrayList<>();

  for (String keywordToAdd : keywordsToAdd) {
    // Creates the keyword.
    Keyword keyword = new Keyword();
    keyword.setText(keywordToAdd);
    keyword.setMatchType(KeywordMatchType.EXACT);

    // Creates the biddable ad group criterion.
    BiddableAdGroupCriterion keywordBiddableAdGroupCriterion = new BiddableAdGroupCriterion();
    keywordBiddableAdGroupCriterion.setAdGroupId(adGroup.getId());
    keywordBiddableAdGroupCriterion.setCriterion(keyword);

    // You can optionally provide these field(s).
    keywordBiddableAdGroupCriterion.setUserStatus(UserStatus.PAUSED);

    String encodedFinalUrl =
      String.format(
        "http://example.com/mars/cruise/?kw=%s",
        URLEncoder.encode(keyword.getText(), UTF_8.name()));
    keywordBiddableAdGroupCriterion.setFinalUrls(new UrlList(new String[] {encodedFinalUrl}));

    // Creates the operation.
    AdGroupCriterionOperation keywordAdGroupCriterionOperation = new AdGroupCriterionOperation();
    keywordAdGroupCriterionOperation.setOperand(keywordBiddableAdGroupCriterion);
    keywordAdGroupCriterionOperation.setOperator(Operator.ADD);

    operations.add(keywordAdGroupCriterionOperation);
  }

  // Adds the keyword.
  AdGroupCriterionReturnValue result =
    adGroupCriterionService.mutate(operations.toArray(new AdGroupCriterionOperation[0]));

  // Displays the results.
  for (AdGroupCriterion adGroupCriterionResult : result.getValue()) {
    System.out.printf(
      "Keyword ad group criterion with ad group ID %d, criterion ID %d, "
        + "text '%s', and match type '%s' was added.%n",
      adGroupCriterionResult.getAdGroupId(),
      adGroupCriterionResult.getCriterion().getId(),
      ((Keyword) adGroupCriterionResult.getCriterion()).getText(),
      ((Keyword) adGroupCriterionResult.getCriterion()).getMatchType());
  }
  return result.getValue();
}
 
Example #25
Source File: KeywordOptimizerUtil.java    From keyword-optimizer with Apache License 2.0 3 votes vote down vote up
/**
 * Convenience method for creating a new keyword.
 *
 * @param text the keyword text
 * @param matchType the match type (BROAD, PHRASE, EXACT)
 * @return the newly created {@link Keyword}
 */
public static Keyword createKeyword(String text, KeywordMatchType matchType) {
  Keyword keyword = new Keyword();
  keyword.setMatchType(matchType);
  keyword.setText(text);
  return keyword;
}
 
Example #26
Source File: KeywordCollection.java    From keyword-optimizer with Apache License 2.0 2 votes vote down vote up
/**
 * Returns whether information about a given keyword exists in this collection.
 *
 * @param keyword they {@link Keyword} to be checked
 */
public boolean contains(Keyword keyword) {
  return keywords.containsKey(keyword);
}
 
Example #27
Source File: KeywordOptimizerUtil.java    From keyword-optimizer with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a string representation of the given {@link Keyword}. Please note, as not all classes
 * belong to the project itself, toString methods are bundled here.
 * 
 * @param keyword the keyword
 * @return a string representation of the keyword
 */
public static String toString(Keyword keyword) {
  return keyword.getText() + "[" + keyword.getMatchType().getValue() + "]";
}