Search in sources :

Example 6 with AdWordsSession

use of com.google.api.ads.adwords.lib.client.AdWordsSession in project googleads-java-lib by googleads.

the class AddGmailAd method main.

public static void main(String[] args) {
    AdWordsSession session;
    try {
        // Generate a refreshable OAuth2 credential.
        Credential oAuth2Credential = new OfflineCredentials.Builder().forApi(Api.ADWORDS).fromFile().build().generateCredential();
        // Construct an AdWordsSession.
        session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
    } catch (ConfigurationLoadException cle) {
        System.err.printf("Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle);
        return;
    } catch (ValidationException ve) {
        System.err.printf("Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve);
        return;
    } catch (OAuthException oe) {
        System.err.printf("Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe);
        return;
    }
    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
    AddGmailAdParams params = new AddGmailAdParams();
    if (!params.parseArguments(args)) {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the code here. See the parameter class definition above for descriptions.
        params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
    }
    try {
        runExample(adWordsServices, session, params.adGroupId);
    } catch (ApiException apiException) {
        // ApiException is the base class for most exceptions thrown by an API request. Instances
        // of this exception have a message and a collection of ApiErrors that indicate the
        // type and underlying cause of the exception. Every exception object in the adwords.axis
        // packages will return a meaningful value from toString
        // 
        // ApiException extends RemoteException, so this catch block must appear before the
        // catch block for RemoteException.
        System.err.println("Request failed due to ApiException. Underlying ApiErrors:");
        if (apiException.getErrors() != null) {
            int i = 0;
            for (ApiError apiError : apiException.getErrors()) {
                System.err.printf("  Error %d: %s%n", i++, apiError);
            }
        }
    } catch (RemoteException re) {
        System.err.printf("Request failed unexpectedly due to RemoteException: %s%n", re);
    } catch (IOException ioe) {
        System.err.printf("Example failed due to IOException: %s%n", ioe);
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) IOException(java.io.IOException) RemoteException(java.rmi.RemoteException) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException)

Example 7 with AdWordsSession

use of com.google.api.ads.adwords.lib.client.AdWordsSession in project googleads-java-lib by googleads.

the class AddMultiAssetResponsiveDisplayAd method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adGroupId the ID of the ad group where the ad 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 IOException if unable to retrieve an image from a URL.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, long adGroupId) throws IOException {
    // Get the AdGroupAdService.
    AdGroupAdServiceInterface adGroupAdService = adWordsServices.get(session, AdGroupAdServiceInterface.class);
    List<AdGroupAdOperation> operations = new ArrayList<>();
    MultiAssetResponsiveDisplayAd ad = new MultiAssetResponsiveDisplayAd();
    List<AssetLink> headlines = new ArrayList<>();
    headlines.add(createAssetLinkForText("Travel to Mars"));
    headlines.add(createAssetLinkForText("Travel to Jupiter"));
    headlines.add(createAssetLinkForText("Travel to Pluto"));
    headlines.add(createAssetLinkForText("Experience the Stars"));
    ad.setHeadlines(headlines.toArray(new AssetLink[0]));
    List<AssetLink> descriptions = new ArrayList<>();
    descriptions.add(createAssetLinkForText("Visit the planet in a luxury spaceship."));
    descriptions.add(createAssetLinkForText("See the planet in style."));
    ad.setDescriptions(descriptions.toArray(new AssetLink[0]));
    ad.setBusinessName("Galactic Luxury Cruises");
    ad.setLongHeadline(createAssetLinkForText("Visit the planet in a luxury spaceship."));
    // This ad format does not allow the creation of an image asset by setting the asset.imageData
    // field. An image asset must first be created using the AssetService, and asset.assetId must be
    // populated when creating the ad.
    ad.setMarketingImages(new AssetLink[] { createAssetLinkForImageAsset(uploadImageAsset(adWordsServices, session, "https://goo.gl/3b9Wfh")) });
    ad.setSquareMarketingImages(new AssetLink[] { createAssetLinkForImageAsset(uploadImageAsset(adWordsServices, session, "https://goo.gl/mtt54n")) });
    ad.setFinalUrls(new String[] { "http://www.example.com" });
    // Optional: set call to action text.
    ad.setCallToActionText("Shop Now");
    // Set color settings using hexadecimal values. Set allowFlexibleColor to false if you want
    // your ads to render by always using your colors strictly.
    ad.setMainColor("#0000ff");
    ad.setAccentColor("#ffff00");
    ad.setAllowFlexibleColor(false);
    // Set the format setting that the ad will be served in.
    ad.setFormatSetting(DisplayAdFormatSetting.NON_NATIVE);
    // Optional: Set dynamic display ad settings, composed of landscape logo image, promotion text,
    // and price prefix.
    ad.setDynamicSettingsPricePrefix("as low as");
    ad.setDynamicSettingsPromoText("Free shipping!");
    ad.setLogoImages(new AssetLink[] { createAssetLinkForImageAsset(uploadImageAsset(adWordsServices, session, "https://goo.gl/mtt54n")) });
    // Create ad group ad.
    AdGroupAd adGroupAd = new AdGroupAd();
    adGroupAd.setAdGroupId(adGroupId);
    adGroupAd.setAd(ad);
    // Optional: set the status.
    adGroupAd.setStatus(AdGroupAdStatus.PAUSED);
    // Create the operation.
    AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation();
    adGroupAdOperation.setOperand(adGroupAd);
    adGroupAdOperation.setOperator(Operator.ADD);
    operations.add(adGroupAdOperation);
    // Add ad.
    AdGroupAdReturnValue result = adGroupAdService.mutate(operations.toArray(new AdGroupAdOperation[operations.size()]));
    Arrays.stream(result.getValue()).map(adGroupAdResult -> (MultiAssetResponsiveDisplayAd) adGroupAdResult.getAd()).forEach(newAd -> System.out.printf("New responsive display ad with ID %d and long headline '%s' was added.%n", newAd.getId(), ((TextAsset) newAd.getLongHeadline().getAsset()).getAssetText()));
}
Also used : Arrays(java.util.Arrays) Parameter(com.beust.jcommander.Parameter) ArrayList(java.util.ArrayList) AssetLink(com.google.api.ads.adwords.axis.v201809.cm.AssetLink) AssetServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AssetServiceInterface) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) AssetOperation(com.google.api.ads.adwords.axis.v201809.cm.AssetOperation) ImageAsset(com.google.api.ads.adwords.axis.v201809.cm.ImageAsset) ArgumentNames(com.google.api.ads.adwords.lib.utils.examples.ArgumentNames) Credential(com.google.api.client.auth.oauth2.Credential) AdGroupAdReturnValue(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdReturnValue) AdGroupAdStatus(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdStatus) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) DisplayAdFormatSetting(com.google.api.ads.adwords.axis.v201809.cm.DisplayAdFormatSetting) AdWordsServices(com.google.api.ads.adwords.axis.factory.AdWordsServices) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) IOException(java.io.IOException) Operator(com.google.api.ads.adwords.axis.v201809.cm.Operator) CodeSampleParams(com.google.api.ads.common.lib.utils.examples.CodeSampleParams) RemoteException(java.rmi.RemoteException) DEFAULT_CONFIGURATION_FILENAME(com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME) AdGroupAd(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd) List(java.util.List) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) MultiAssetResponsiveDisplayAd(com.google.api.ads.adwords.axis.v201809.cm.MultiAssetResponsiveDisplayAd) AdGroupAdOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdOperation) Api(com.google.api.ads.common.lib.auth.OfflineCredentials.Api) TextAsset(com.google.api.ads.adwords.axis.v201809.cm.TextAsset) AdGroupAdServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface) TextAsset(com.google.api.ads.adwords.axis.v201809.cm.TextAsset) AdGroupAd(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd) MultiAssetResponsiveDisplayAd(com.google.api.ads.adwords.axis.v201809.cm.MultiAssetResponsiveDisplayAd) AdGroupAdReturnValue(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdReturnValue) AdGroupAdServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface) ArrayList(java.util.ArrayList) AdGroupAdOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdOperation) AssetLink(com.google.api.ads.adwords.axis.v201809.cm.AssetLink)

Example 8 with AdWordsSession

use of com.google.api.ads.adwords.lib.client.AdWordsSession in project googleads-java-lib by googleads.

the class AddShoppingDynamicRemarketingCampaign method main.

public static void main(String[] args) {
    final AdWordsServicesInterface services = AdWordsServices.getInstance();
    AdWordsSession session;
    try {
        Credential oAuth2Credential;
        oAuth2Credential = new OfflineCredentials.Builder().forApi(OfflineCredentials.Api.ADWORDS).fromFile().build().generateCredential();
        session = new Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
    } catch (ConfigurationLoadException cle) {
        System.err.printf("Failed to load configuration from the %s file%n", DEFAULT_CONFIGURATION_FILENAME);
        return;
    } catch (ValidationException ve) {
        System.err.printf("Invalid configuration in the %s file%n", DEFAULT_CONFIGURATION_FILENAME);
        return;
    } catch (OAuthException oe) {
        System.err.printf("Failed to create OAuth credentials. Check OAuth settings in the %s file%n", DEFAULT_CONFIGURATION_FILENAME);
        return;
    }
    final AddShoppingDynamicRemarketingCampaignParams params = new AddShoppingDynamicRemarketingCampaignParams();
    if (!params.parseArguments(args)) {
        params.merchantId = Long.parseLong("INSERT_MERCHANT_ID");
        params.budgetId = Long.parseLong("INSERT_BUDGET_ID");
        params.userListId = Long.parseLong("INSERT_USER_LIST_ID");
    }
    try {
        runExample(services, session, params.merchantId, params.budgetId, params.userListId);
    } catch (ApiException apiException) {
        // ApiException is the base class for most exceptions thrown by an API request. Instances
        // of this exception have a message and a collection of ApiErrors that indicate the
        // type and underlying cause of the exception. Every exception object in the adwords.axis
        // packages will return a meaningful value from toString.
        // 
        // ApiException extends RemoteException, so this catch block must appear before the
        // catch block for RemoteException.
        System.err.print("Request failed due to ApiException. Underlying ApiErrors:");
        if (apiException.getErrors() != null) {
            int i = 0;
            for (ApiError apiError : apiException.getErrors()) {
                System.err.printf("  Error %d: %s%n", i++, apiError);
            }
        }
    } catch (RemoteException re) {
        System.err.printf("Request failed unexpectedly due to RemoteException: %s%n", re);
    } catch (IOException e) {
        System.err.printf("Request failed unexpectedly due to IOException: %s%n", e);
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) Builder(com.google.api.ads.adwords.lib.client.AdWordsSession.Builder) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) IOException(java.io.IOException) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) RemoteException(java.rmi.RemoteException) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException)

Example 9 with AdWordsSession

use of com.google.api.ads.adwords.lib.client.AdWordsSession in project googleads-java-lib by googleads.

the class GetAdGroupBidModifier method main.

public static void main(String[] args) {
    AdWordsSession session;
    try {
        // Generate a refreshable OAuth2 credential.
        Credential oAuth2Credential = new OfflineCredentials.Builder().forApi(Api.ADWORDS).fromFile().build().generateCredential();
        // Construct an AdWordsSession.
        session = new AdWordsSession.Builder().fromFile().withOAuth2Credential(oAuth2Credential).build();
    } catch (ConfigurationLoadException cle) {
        System.err.printf("Failed to load configuration from the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, cle);
        return;
    } catch (ValidationException ve) {
        System.err.printf("Invalid configuration in the %s file. Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, ve);
        return;
    } catch (OAuthException oe) {
        System.err.printf("Failed to create OAuth credentials. Check OAuth settings in the %s file. " + "Exception: %s%n", DEFAULT_CONFIGURATION_FILENAME, oe);
        return;
    }
    AdWordsServicesInterface adWordsServices = AdWordsServices.getInstance();
    try {
        runExample(adWordsServices, session);
    } catch (ApiException apiException) {
        // ApiException is the base class for most exceptions thrown by an API request. Instances
        // of this exception have a message and a collection of ApiErrors that indicate the
        // type and underlying cause of the exception. Every exception object in the adwords.axis
        // packages will return a meaningful value from toString
        // 
        // ApiException extends RemoteException, so this catch block must appear before the
        // catch block for RemoteException.
        System.err.println("Request failed due to ApiException. Underlying ApiErrors:");
        if (apiException.getErrors() != null) {
            int i = 0;
            for (ApiError apiError : apiException.getErrors()) {
                System.err.printf("  Error %d: %s%n", i++, apiError);
            }
        }
    } catch (RemoteException re) {
        System.err.printf("Request failed unexpectedly due to RemoteException: %s%n", re);
    }
}
Also used : Credential(com.google.api.client.auth.oauth2.Credential) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) SelectorBuilder(com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) RemoteException(java.rmi.RemoteException) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException)

Example 10 with AdWordsSession

use of com.google.api.ads.adwords.lib.client.AdWordsSession in project googleads-java-lib by googleads.

the class AddExpandedTextAds method runExample.

/**
 * Runs the example.
 *
 * @param adWordsServices the services factory.
 * @param session the session.
 * @param adGroupId the ID of the ad group where the ad 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.
 */
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session, long adGroupId) throws RemoteException {
    // Get the AdGroupAdService.
    AdGroupAdServiceInterface adGroupAdService = adWordsServices.get(session, AdGroupAdServiceInterface.class);
    List<AdGroupAdOperation> operations = new ArrayList<>();
    for (int i = 0; i < NUMBER_OF_ADS; i++) {
        // Create expanded text ad.
        ExpandedTextAd expandedTextAd = new ExpandedTextAd();
        expandedTextAd.setHeadlinePart1(String.format("Cruise #%d to Mars", i));
        expandedTextAd.setHeadlinePart2("Best Space Cruise Line");
        expandedTextAd.setHeadlinePart3("For Your Loved Ones");
        expandedTextAd.setDescription("Buy your tickets now!");
        expandedTextAd.setDescription2("Discount ends soon");
        expandedTextAd.setFinalUrls(new String[] { "http://www.example.com/" + i });
        // Create ad group ad.
        AdGroupAd expandedTextAdGroupAd = new AdGroupAd();
        expandedTextAdGroupAd.setAdGroupId(adGroupId);
        expandedTextAdGroupAd.setAd(expandedTextAd);
        // Optional: set the status.
        expandedTextAdGroupAd.setStatus(AdGroupAdStatus.PAUSED);
        // Create the operation.
        AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation();
        adGroupAdOperation.setOperand(expandedTextAdGroupAd);
        adGroupAdOperation.setOperator(Operator.ADD);
        operations.add(adGroupAdOperation);
    }
    // Add ads.
    AdGroupAdReturnValue result = adGroupAdService.mutate(operations.toArray(new AdGroupAdOperation[operations.size()]));
    // Display ads.
    Arrays.stream(result.getValue()).map(adGroupAdResult -> (ExpandedTextAd) adGroupAdResult.getAd()).forEach(newAd -> System.out.printf("Expanded text ad with ID %d and headline '%s | %s%s' was added.%n", newAd.getId(), newAd.getHeadlinePart1(), newAd.getHeadlinePart2(), newAd.getHeadlinePart3() == null ? "" : String.format(" | %s", newAd.getHeadlinePart3())));
}
Also used : Arrays(java.util.Arrays) Parameter(com.beust.jcommander.Parameter) ArrayList(java.util.ArrayList) OfflineCredentials(com.google.api.ads.common.lib.auth.OfflineCredentials) ApiException(com.google.api.ads.adwords.axis.v201809.cm.ApiException) ArgumentNames(com.google.api.ads.adwords.lib.utils.examples.ArgumentNames) Credential(com.google.api.client.auth.oauth2.Credential) AdGroupAdReturnValue(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdReturnValue) AdGroupAdStatus(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdStatus) OAuthException(com.google.api.ads.common.lib.exception.OAuthException) AdWordsServices(com.google.api.ads.adwords.axis.factory.AdWordsServices) ConfigurationLoadException(com.google.api.ads.common.lib.conf.ConfigurationLoadException) Operator(com.google.api.ads.adwords.axis.v201809.cm.Operator) CodeSampleParams(com.google.api.ads.common.lib.utils.examples.CodeSampleParams) ExpandedTextAd(com.google.api.ads.adwords.axis.v201809.cm.ExpandedTextAd) RemoteException(java.rmi.RemoteException) DEFAULT_CONFIGURATION_FILENAME(com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME) AdGroupAd(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd) List(java.util.List) AdWordsSession(com.google.api.ads.adwords.lib.client.AdWordsSession) AdWordsServicesInterface(com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface) ApiError(com.google.api.ads.adwords.axis.v201809.cm.ApiError) ValidationException(com.google.api.ads.common.lib.exception.ValidationException) AdGroupAdOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdOperation) Api(com.google.api.ads.common.lib.auth.OfflineCredentials.Api) AdGroupAdServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface) AdGroupAd(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAd) AdGroupAdReturnValue(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdReturnValue) AdGroupAdServiceInterface(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdServiceInterface) ArrayList(java.util.ArrayList) ExpandedTextAd(com.google.api.ads.adwords.axis.v201809.cm.ExpandedTextAd) AdGroupAdOperation(com.google.api.ads.adwords.axis.v201809.cm.AdGroupAdOperation)

Aggregations

AdWordsSession (com.google.api.ads.adwords.lib.client.AdWordsSession)121 Credential (com.google.api.client.auth.oauth2.Credential)104 AdWordsServicesInterface (com.google.api.ads.adwords.lib.factory.AdWordsServicesInterface)102 ValidationException (com.google.api.ads.common.lib.exception.ValidationException)101 ConfigurationLoadException (com.google.api.ads.common.lib.conf.ConfigurationLoadException)100 OAuthException (com.google.api.ads.common.lib.exception.OAuthException)100 ApiError (com.google.api.ads.adwords.axis.v201809.cm.ApiError)97 ApiException (com.google.api.ads.adwords.axis.v201809.cm.ApiException)97 RemoteException (java.rmi.RemoteException)97 SelectorBuilder (com.google.api.ads.adwords.axis.utils.v201809.SelectorBuilder)24 Test (org.junit.Test)15 IOException (java.io.IOException)14 OfflineCredentials (com.google.api.ads.common.lib.auth.OfflineCredentials)12 AdWordsServices (com.google.api.ads.adwords.axis.factory.AdWordsServices)10 Api (com.google.api.ads.common.lib.auth.OfflineCredentials.Api)9 DEFAULT_CONFIGURATION_FILENAME (com.google.api.ads.common.lib.utils.Builder.DEFAULT_CONFIGURATION_FILENAME)9 MockHttpIntegrationTest (com.google.api.ads.common.lib.testing.MockHttpIntegrationTest)8 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)7 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)7 List (java.util.List)7