public class CreateAdUnits {
public static void runExample(DfpServices dfpServices, DfpSession session)
throws Exception {
// Get the InventoryService.
InventoryServiceInterface inventoryService =
dfpServices.get(session, InventoryServiceInterface.class);
// Get the NetworkService.
NetworkServiceInterface networkService =
dfpServices.get(session, NetworkServiceInterface.class);
// Set the parent ad unit's ID for all ad units to be created under.
String parentAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId();
// Create a 300x250 web ad unit size.
Size webSize = new Size();
webSize.setWidth(300);
webSize.setHeight(250);
webSize.setIsAspectRatio(false);
AdUnitSize webAdUnitSize = new AdUnitSize();
webAdUnitSize.setSize(webSize);
webAdUnitSize.setEnvironmentType(EnvironmentType.BROWSER);
// Create a 640x360v video ad unit size with a companion.
Size videoSize = new Size();
videoSize.setWidth(640);
videoSize.setHeight(360);
videoSize.setIsAspectRatio(false);
AdUnitSize videoAdUnitSize = new AdUnitSize();
videoAdUnitSize.setSize(videoSize);
videoAdUnitSize.setCompanions(new AdUnitSize[] {webAdUnitSize});
videoAdUnitSize.setEnvironmentType(EnvironmentType.VIDEO_PLAYER);
// Create a web ad unit.
AdUnit webAdUnit = new AdUnit();
webAdUnit.setName("web_ad_unit_" + new Random().nextInt(Integer.MAX_VALUE));
webAdUnit.setDescription(webAdUnit.getName());
webAdUnit.setTargetPlatform(TargetPlatform.WEB);
webAdUnit.setParentId(parentAdUnitId);
webAdUnit.setTargetWindow(AdUnitTargetWindow.BLANK);
webAdUnit.setAdUnitSizes(new AdUnitSize[]{webAdUnitSize});
// Create a video ad unit.
AdUnit videoAdUnit = new AdUnit();
videoAdUnit.setName("video_ad_unit_" + new Random().nextInt(Integer.MAX_VALUE));
videoAdUnit.setDescription(videoAdUnit.getName());
videoAdUnit.setTargetPlatform(TargetPlatform.WEB);
videoAdUnit.setParentId(parentAdUnitId);
videoAdUnit.setTargetWindow(AdUnitTargetWindow.BLANK);
videoAdUnit.setAdUnitSizes(new AdUnitSize[]{videoAdUnitSize});
// Create the ad units on the server.
AdUnit[] adUnits = inventoryService.createAdUnits(new AdUnit[] {webAdUnit, videoAdUnit});
for (AdUnit adUnit : adUnits) {
System.out.printf("An ad unit with ID \"%s\", name \"%s\" was created.\n", adUnit.getId(),
adUnit.getName());
}