public static void main(java.lang.String[] args) {
   	 
    	NumberFormat currencyFmt = NumberFormat.getCurrencyInstance();
    	
        try
        {
            authorizationData = new AuthorizationData();
            authorizationData.setDeveloperToken(DeveloperToken);
            authorizationData.setAuthentication(new PasswordAuthentication(UserName, Password));
            authorizationData.setCustomerId(CustomerId);
            authorizationData.setAccountId(AccountId);
	         
            AdIntelligenceService = new ServiceClient<IAdIntelligenceService>(
                    authorizationData, 
                    IAdIntelligenceService.class);
        

            // Set the Currency, Keywords, Language, PublisherCountries, and TargetPositionForAds
            // for the estimated bid by keywords request.
            
            Currency currency = Currency.US_DOLLAR;
            
            ArrayOfKeywordAndMatchType keywordAndMatchTypes = new ArrayOfKeywordAndMatchType();
            ArrayOfMatchType matchTypes = new ArrayOfMatchType();
            matchTypes.getMatchTypes().add(MatchType.EXACT);
            matchTypes.getMatchTypes().add(MatchType.PHRASE);
            matchTypes.getMatchTypes().add(MatchType.BROAD);
            KeywordAndMatchType keywordAndMatchType1 = new KeywordAndMatchType();
            keywordAndMatchType1.setKeywordText("flower");
            keywordAndMatchType1.setMatchTypes(matchTypes);
            keywordAndMatchTypes.getKeywordAndMatchTypes().add(keywordAndMatchType1);
            KeywordAndMatchType keywordAndMatchType2 = new KeywordAndMatchType();
            keywordAndMatchType2.setKeywordText("delivery");
            keywordAndMatchType2.setMatchTypes(matchTypes);
            keywordAndMatchTypes.getKeywordAndMatchTypes().add(keywordAndMatchType2);
            
            java.lang.String language = "English";
            
            ArrayOfstring publisherCountries = new ArrayOfstring();
            publisherCountries.getStrings().add("US");
            
            TargetAdPosition targetPositionForAds = TargetAdPosition.SIDE_BAR;
            
            // GetKeywordEstimatedBidByKeywords helper method calls the corresponding Bing Ads AdIntelligenceService.getService() operation 
            // to request the KeywordEstimatedBids.
            
            ArrayOfKeywordEstimatedBid keywordEstimatedBids = getKeywordEstimatedBidByKeywords(
            	currency,
                keywordAndMatchTypes, 
                language, 
                publisherCountries, 
                targetPositionForAds
                );

            // GetAdGroupEstimatedBidByKeywords helper method calls the corresponding Bing Ads AdIntelligenceService.getService() operation 
            // to request the AdGroupEstimatedBid.
            
            AdGroupEstimatedBid adGroupEstimatedBid = getAdGroupEstimatedBidByKeywords(
                currency,
                keywordAndMatchTypes,
                language,
                publisherCountries,
                targetPositionForAds
                );
			
            // Print the KeywordEstimatedBids

            if (keywordEstimatedBids != null)
            {
            	System.out.println("KeywordEstimatedBids\n");
            	
                for (KeywordEstimatedBid bid : keywordEstimatedBids.getKeywordEstimatedBids())
                {
                    if (bid == null)
                    {
                        System.out.println("The keyword is not valid.\n");
                    }
                    else
                    {
                        System.out.println(bid.getKeyword());

                        if (bid.getEstimatedBids() == null)
                        {
                            System.out.println("  There is no bid information available for the keyword.\n");
                        }
                        else
                        {
                            for (EstimatedBidAndTraffic estimatedBidAndTraffic : bid.getEstimatedBids().getEstimatedBidAndTraffics())
                            {
                            	System.out.println("    Estimated Minimum Bid: " + 
                                        currencyFmt.format(estimatedBidAndTraffic.getEstimatedMinBid()));
                                System.out.println("    Match Type: " + estimatedBidAndTraffic.getMatchType());
                                System.out.println("    Average CPC: " + 
                                        (estimatedBidAndTraffic.getAverageCPC() != null ? currencyFmt.format(estimatedBidAndTraffic.getAverageCPC()) : "null"));
                                System.out.printf("    Estimated clicks per week: %s to %s\n",
                                		estimatedBidAndTraffic.getMinClicksPerWeek(), estimatedBidAndTraffic.getMaxClicksPerWeek());
                                System.out.printf("    Estimated impressions per week: %s to %s\n",
                                		estimatedBidAndTraffic.getMinImpressionsPerWeek(), estimatedBidAndTraffic.getMaxImpressionsPerWeek());
                                System.out.printf("    Estimated cost per week: %s to %s\n",
                                    (estimatedBidAndTraffic.getMinTotalCostPerWeek() != null ? currencyFmt.format(estimatedBidAndTraffic.getMinTotalCostPerWeek()) : "null"),
                                    (estimatedBidAndTraffic.getMaxTotalCostPerWeek() != null ? currencyFmt.format(estimatedBidAndTraffic.getMaxTotalCostPerWeek()) : "null"));
                                System.out.println();
                            }
                        }
                    }
                }
            }
            
            // Print the AdGroupEstimatedBid

            if (adGroupEstimatedBid != null) {
            	System.out.println("AdGroupEstimatedBid\n");
                
                System.out.println("    Estimated Ad Group Bid: " + 
                        currencyFmt.format(adGroupEstimatedBid.getEstimatedAdGroupBid()));
                System.out.println("    Average CPC: " + 
                        (adGroupEstimatedBid.getAverageCPC() != null ? currencyFmt.format(adGroupEstimatedBid.getAverageCPC()) : "null"));
                System.out.printf("    Estimated clicks per week: %s to %s\n",
                		adGroupEstimatedBid.getMinClicksPerWeek(), adGroupEstimatedBid.getMaxClicksPerWeek());
                System.out.printf("    Estimated impressions per week: %s to %s\n",
                		adGroupEstimatedBid.getMinImpressionsPerWeek(), adGroupEstimatedBid.getMaxImpressionsPerWeek());
                System.out.printf("    Estimated cost per week: %s to %s\n",
                    (adGroupEstimatedBid.getMinTotalCostPerWeek() != null ? currencyFmt.format(adGroupEstimatedBid.getMinTotalCostPerWeek()) : "null"),
                    (adGroupEstimatedBid.getMaxTotalCostPerWeek() != null ? currencyFmt.format(adGroupEstimatedBid.getMaxTotalCostPerWeek()) : "null"));
                System.out.println();
             }

        // Ad Intelligence service operations can throw AdApiFaultDetail.
        } catch (AdApiFaultDetail_Exception ex) {
            System.out.println("The operation failed with the following faults:\n");

            for (AdApiError error : ex.getFaultInfo().getErrors().getAdApiErrors())
            {
                System.out.printf("AdApiError\n");
                System.out.printf("Code: %d\nError Code: %s\nMessage: %s\n\n", error.getCode(), error.getErrorCode(), error.getMessage());
            }
        
        // Ad Intelligence service operations can throw ApiFaultDetail.
        } catch (ApiFaultDetail_Exception ex) {
            System.out.println("The operation failed with the following faults:\n");

            for (BatchError error : ex.getFaultInfo().getBatchErrors().getBatchErrors())
            {
                System.out.printf("BatchError at Index: %d\n", error.getIndex());
                System.out.printf("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage());
            }

            for (OperationError error : ex.getFaultInfo().getOperationErrors().getOperationErrors())
            {
                System.out.printf("OperationError\n");
                System.out.printf("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage());
            }
        } catch (RemoteException ex) {
            System.out.println("Service communication error encountered: ");
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        } catch (Exception ex) {
             System.out.println("Error encountered: ");
             System.out.println(ex.getMessage());
             ex.printStackTrace();
         }
    }
  public static void main(java.lang.String[] args) {

    try {
      authorizationData = new AuthorizationData();
      authorizationData.setDeveloperToken(DeveloperToken);
      authorizationData.setAuthentication(new PasswordAuthentication(UserName, Password));
      authorizationData.setCustomerId(CustomerId);
      authorizationData.setAccountId(AccountId);

      CampaignService =
          new ServiceClient<ICampaignManagementService>(
              authorizationData, ICampaignManagementService.class);

      // Get the user's list of Bing Merchant Center (BMC) stores.

      final ArrayOfBMCStore stores = getBMCStoresByCustomerId();

      if (stores == null) {
        outputStatusMessage(
            String.format(
                "Customer %d does not have any regeistered BMC stores.\n\n",
                authorizationData.getCustomerId()));
        return;
      }

      // Create a Bing Shopping campaign using the ID of the first store in the list.

      Campaign campaign = new Campaign();
      campaign.setName("Bing Shopping Campaign " + System.currentTimeMillis());
      campaign.setDescription("Bing Shopping Campaign Example.");
      campaign.setBudgetType(BudgetLimitType.MONTHLY_BUDGET_SPEND_UNTIL_DEPLETED);
      campaign.setMonthlyBudget(1000.00);
      campaign.setTimeZone("PacificTimeUSCanadaTijuana");
      ArrayList<CampaignType> campaignTypes = new ArrayList<CampaignType>();
      campaignTypes.add(CampaignType.SHOPPING);
      ArrayOfSetting settings = new ArrayOfSetting();
      ShoppingSetting shoppingSetting = new ShoppingSetting();
      shoppingSetting.setPriority(0);
      shoppingSetting.setSalesCountryCode("US");
      shoppingSetting.setStoreId(stores.getBMCStores().get(0).getId());
      settings.getSettings().add(shoppingSetting);
      campaign.setSettings(settings);
      campaign.setCampaignType(campaignTypes);
      campaign.setDaylightSaving(true);

      ArrayOfCampaign campaigns = new ArrayOfCampaign();
      campaigns.getCampaigns().add(campaign);
      AddCampaignsResponse addCampaignsResponse = addCampaigns(AccountId, campaigns);
      ArrayOfNullableOflong campaignIds = addCampaignsResponse.getCampaignIds();
      ArrayOfBatchError campaignErrors = addCampaignsResponse.getPartialErrors();
      outputCampaignsWithPartialErrors(campaigns, campaignIds, campaignErrors);

      ArrayOfAdGroup adGroups = new ArrayOfAdGroup();
      AdGroup adGroup = new AdGroup();
      adGroup.setName("Product Categories");
      ArrayList<AdDistribution> adDistribution = new ArrayList<AdDistribution>();
      adDistribution.add(AdDistribution.SEARCH);
      adGroup.setAdDistribution(adDistribution);
      adGroup.setBiddingModel(BiddingModel.KEYWORD);
      adGroup.setPricingModel(PricingModel.CPC);
      adGroup.setStartDate(null);
      adGroup.setEndDate(new com.microsoft.bingads.v10.campaignmanagement.Date());
      adGroup.getEndDate().setDay(31);
      adGroup.getEndDate().setMonth(12);
      adGroup.getEndDate().setYear(2016);
      Bid searchBid = new Bid();
      searchBid.setAmount(0.09);
      adGroup.setSearchBid(searchBid);
      adGroup.setLanguage("English");
      adGroups.getAdGroups().add(adGroup);

      AddAdGroupsResponse addAdGroupsResponse =
          addAdGroups(campaignIds.getLongs().get(0), adGroups);
      ArrayOfNullableOflong adGroupIds = addAdGroupsResponse.getAdGroupIds();
      ArrayOfBatchError adGroupErrors = addAdGroupsResponse.getPartialErrors();
      outputAdGroupsWithPartialErrors(adGroups, adGroupIds, adGroupErrors);

      ArrayOfAd ads = new ArrayOfAd();
      ProductAd productAd =
          new ProductAd() {
            {
              promotionalText = "Free shipping on $99 purchases.";
            }
          };
      ads.getAds().add(productAd);

      AddAdsResponse addAdsResponse = addAds(adGroupIds.getLongs().get(0), ads);
      ArrayOfNullableOflong adIds = addAdsResponse.getAdIds();
      ArrayOfBatchError adErrors = addAdsResponse.getPartialErrors();
      outputAdsWithPartialErrors(ads, adIds, adErrors);

      // Add criterion to the campaign. The criterion is used to limit the campaign to a subset of
      // your product catalog.

      AddCampaignCriterionsResponse addCriterionResponse =
          addCampaignCriterion(campaignIds.getLongs().get(0));
      printCampaignCriterionIdentifiers(
          addCriterionResponse.getCampaignCriterionIds(),
          addCriterionResponse.getNestedPartialErrors());

      addAndUpdateAdGroupCriterion(adGroupIds.getLongs().get(0));
      ApplyProductPartitionActionsResponse applyPartitionActionsResponse =
          addBranchAndLeafCriterion(adGroupIds.getLongs().get(0));

      long rootId = applyPartitionActionsResponse.getAdGroupCriterionIds().getLongs().get(1);
      long electronicsCriterionId =
          applyPartitionActionsResponse.getAdGroupCriterionIds().getLongs().get(8);
      updateBranchAndLeafCriterion(adGroupIds.getLongs().get(0), rootId, electronicsCriterionId);

      // Delete the campaign from the account.

      ArrayOflong deleteCampaignIds = new ArrayOflong();
      deleteCampaignIds.getLongs().add(campaignIds.getLongs().get(0));
      deleteCampaigns(AccountId, deleteCampaignIds);
      outputStatusMessage(String.format("Deleted CampaignId %d\n", campaignIds.getLongs().get(0)));

      // Campaign Management service operations can throw AdApiFaultDetail.
    } catch (AdApiFaultDetail_Exception ex) {
      outputStatusMessage("The operation failed with the following faults:\n");

      for (AdApiError error : ex.getFaultInfo().getErrors().getAdApiErrors()) {
        outputStatusMessage("AdApiError\n");
        outputStatusMessage(
            String.format(
                "Code: %d\nError Code: %s\nMessage: %s\n\n",
                error.getCode(), error.getErrorCode(), error.getMessage()));
      }

      // Campaign Management service operations can throw ApiFaultDetail.
    } catch (ApiFaultDetail_Exception ex) {
      outputStatusMessage("The operation failed with the following faults:\n");

      for (BatchError error : ex.getFaultInfo().getBatchErrors().getBatchErrors()) {
        outputStatusMessage(String.format("BatchError at Index: %d\n", error.getIndex()));
        outputStatusMessage(
            String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
      }

      for (OperationError error : ex.getFaultInfo().getOperationErrors().getOperationErrors()) {
        outputStatusMessage("OperationError\n");
        outputStatusMessage(
            String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
      }

      // Some Campaign Management service operations such as SetAdExtensionsAssociations can throw
      // EditorialApiFaultDetail.
    } catch (EditorialApiFaultDetail_Exception ex) {
      outputStatusMessage("The operation failed with the following faults:\n");

      for (BatchError error : ex.getFaultInfo().getBatchErrors().getBatchErrors()) {
        outputStatusMessage(String.format("BatchError at Index: %d\n", error.getIndex()));
        outputStatusMessage(
            String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
      }

      for (EditorialError error : ex.getFaultInfo().getEditorialErrors().getEditorialErrors()) {
        outputStatusMessage(String.format("EditorialError at Index: %d\n\n", error.getIndex()));
        outputStatusMessage(
            String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
        outputStatusMessage(
            String.format(
                "Appealable: %s\nDisapproved Text: %s\nCountry: %s\n\n",
                error.getAppealable(), error.getDisapprovedText(), error.getPublisherCountry()));
      }

      for (OperationError error : ex.getFaultInfo().getOperationErrors().getOperationErrors()) {
        outputStatusMessage("OperationError\n");
        outputStatusMessage(
            String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
      }
    } catch (RemoteException ex) {
      outputStatusMessage("Service communication error encountered: ");
      outputStatusMessage(ex.getMessage());
      ex.printStackTrace();
    } catch (Exception ex) {
      outputStatusMessage("Error encountered: ");
      outputStatusMessage(ex.getMessage());
      ex.printStackTrace();
    }
  }