*/
public class CreatePlacements {
public static void runExample(DfpServices dfpServices, DfpSession session) throws Exception {
// Get the PlacementService.
PlacementServiceInterface placementService =
dfpServices.get(session, PlacementServiceInterface.class);
// Get all ad units.
List<AdUnit> adUnits = getAllAdUnits(dfpServices, session);
// Partition ad units by their size.
Set<String> mediumSquareAdUnitIds = Sets.newHashSet();
Set<String> skyscraperAdUnitIds = Sets.newHashSet();
Set<String> bannerAdUnitIds = Sets.newHashSet();
for (AdUnit adUnit : adUnits) {
if (adUnit.getParentId() != null && adUnit.getAdUnitSizes() != null) {
for (AdUnitSize adUnitSize : adUnit.getAdUnitSizes()) {
Size size = adUnitSize.getSize();
if (size.getWidth() == 300 && size.getHeight() == 250) {
mediumSquareAdUnitIds.add(adUnit.getId());
} else if (size.getWidth() == 120 && size.getHeight() == 600) {
skyscraperAdUnitIds.add(adUnit.getId());
} else if (size.getWidth() == 468 && size.getHeight() == 60) {
bannerAdUnitIds.add(adUnit.getId());
}
}
}
}
List<Placement> placementsToCreate = Lists.newArrayList();
// Only create placements with one or more ad unit.
if (!mediumSquareAdUnitIds.isEmpty()) {
// Create medium square placement.
Placement mediumSquareAdUnitPlacement = new Placement();
mediumSquareAdUnitPlacement.setName("Medium Square AdUnit Placement #"
+ new Random().nextInt(Integer.MAX_VALUE));
mediumSquareAdUnitPlacement.setDescription(
"Contains ad units that can hold creatives of size 300x250");
mediumSquareAdUnitPlacement.setTargetedAdUnitIds(
mediumSquareAdUnitIds.toArray(new String[] {}));
placementsToCreate.add(mediumSquareAdUnitPlacement);
}
if (!skyscraperAdUnitIds.isEmpty()) {
// Create skyscraper placement.
Placement skyscraperAdUnitPlacement = new Placement();
skyscraperAdUnitPlacement.setName(
"Skyscraper AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
skyscraperAdUnitPlacement.setDescription(
"Contains ad units that can hold creatives of size 120x600");
skyscraperAdUnitPlacement.setTargetedAdUnitIds(skyscraperAdUnitIds.toArray(new String[] {}));
placementsToCreate.add(skyscraperAdUnitPlacement);
}
if (!bannerAdUnitIds.isEmpty()) {
// Create banner placement.
Placement bannerAdUnitPlacement = new Placement();
bannerAdUnitPlacement.setName(
"Banner AdUnit Placement #" + new Random().nextInt(Integer.MAX_VALUE));
bannerAdUnitPlacement.setDescription(
"Contains ad units that can hold creatives of size 468x60");
bannerAdUnitPlacement.setTargetedAdUnitIds(bannerAdUnitIds.toArray(new String[] {}));
placementsToCreate.add(bannerAdUnitPlacement);
}
if (!placementsToCreate.isEmpty()) {
// Create the placements on the server.
Placement[] placements =
placementService.createPlacements(placementsToCreate.toArray(new Placement[] {}));
for (Placement createdPlacement : placements) {
System.out.printf(
"A placement with ID \"%d\", name \"%s\", and containing ad units [%s] was created.\n",
createdPlacement.getId(), createdPlacement.getName(),