TestandtargetCampaignMediatorImpl.java 70.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.tsdk.common.ComponentDataStorage
 *  com.adobe.tsdk.common.ComponentManager
 *  com.adobe.tsdk.common.DataSerializer
 *  com.adobe.tsdk.common.TSDKException
 *  com.adobe.tsdk.common.task.SynchronizedTaskRunner
 *  com.adobe.tsdk.components.goalsandsettings.GoalsAndSettings
 *  com.adobe.tsdk.components.goalsandsettings.GoalsAndSettingsBuilder
 *  com.adobe.tsdk.components.goalsandsettings.TargetGoalsAndSettingsBuilder
 *  com.adobe.tsdk.components.goalsandsettings.goals.Analytics
 *  com.adobe.tsdk.components.goalsandsettings.goals.Goals
 *  com.adobe.tsdk.components.goalsandsettings.goals.GoalsBuilder
 *  com.adobe.tsdk.components.goalsandsettings.goals.TargetGoalsBuilder
 *  com.adobe.tsdk.components.goalsandsettings.goals.metrics.AnonymousAudienceSyncHelper
 *  com.adobe.tsdk.components.goalsandsettings.goals.metrics.MetricsBuilder
 *  com.adobe.tsdk.components.goalsandsettings.goals.metrics.TargetMetricsBuilder
 *  com.adobe.tsdk.components.goalsandsettings.goals.metrics.dto.Metric
 *  com.adobe.tsdk.components.goalsandsettings.processor.GoalsAndSettingsProcessor
 *  com.adobe.tsdk.components.goalsandsettings.processor.TargetGoalsAndSettingsProcessor
 *  com.day.cq.commons.Externalizer
 *  com.day.cq.commons.Filter
 *  com.day.cq.personalization.Segment
 *  com.day.cq.personalization.Segment$Kind
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.api.PageManager
 *  com.day.cq.wcm.api.Revision
 *  com.day.cq.wcm.api.WCMException
 *  com.day.cq.wcm.api.WCMMode
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory
 *  com.google.gson.JsonArray
 *  com.google.gson.JsonElement
 *  com.google.gson.JsonObject
 *  com.google.gson.JsonParser
 *  javax.jcr.Node
 *  javax.jcr.PathNotFoundException
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  org.apache.commons.lang.StringUtils
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferencePolicyOption
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.ModifiableValueMap
 *  org.apache.sling.api.resource.NonExistingResource
 *  org.apache.sling.api.resource.PersistenceException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.ValueMap
 *  org.codehaus.jackson.JsonNode
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.analytics.testandtarget.impl;

import com.adobe.tsdk.common.ComponentDataStorage;
import com.adobe.tsdk.common.ComponentManager;
import com.adobe.tsdk.common.DataSerializer;
import com.adobe.tsdk.common.TSDKException;
import com.adobe.tsdk.common.task.SynchronizedTaskRunner;
import com.adobe.tsdk.components.goalsandsettings.GoalsAndSettings;
import com.adobe.tsdk.components.goalsandsettings.GoalsAndSettingsBuilder;
import com.adobe.tsdk.components.goalsandsettings.TargetGoalsAndSettingsBuilder;
import com.adobe.tsdk.components.goalsandsettings.goals.Analytics;
import com.adobe.tsdk.components.goalsandsettings.goals.Goals;
import com.adobe.tsdk.components.goalsandsettings.goals.GoalsBuilder;
import com.adobe.tsdk.components.goalsandsettings.goals.TargetGoalsBuilder;
import com.adobe.tsdk.components.goalsandsettings.goals.metrics.AnonymousAudienceSyncHelper;
import com.adobe.tsdk.components.goalsandsettings.goals.metrics.MetricsBuilder;
import com.adobe.tsdk.components.goalsandsettings.goals.metrics.TargetMetricsBuilder;
import com.adobe.tsdk.components.goalsandsettings.goals.metrics.dto.Metric;
import com.adobe.tsdk.components.goalsandsettings.processor.GoalsAndSettingsProcessor;
import com.adobe.tsdk.components.goalsandsettings.processor.TargetGoalsAndSettingsProcessor;
import com.day.cq.analytics.testandtarget.Campaign;
import com.day.cq.analytics.testandtarget.HTMLOffer;
import com.day.cq.analytics.testandtarget.ListFilter;
import com.day.cq.analytics.testandtarget.ListOffersRequest;
import com.day.cq.analytics.testandtarget.SaveOfferRequest;
import com.day.cq.analytics.testandtarget.TargetLocationNameProvider;
import com.day.cq.analytics.testandtarget.TargetMediator;
import com.day.cq.analytics.testandtarget.TestandtargetException;
import com.day.cq.analytics.testandtarget.TestandtargetUnsupportedApiOperationException;
import com.day.cq.analytics.testandtarget.ViewOfferResponse;
import com.day.cq.analytics.testandtarget.impl.TargetHelperService;
import com.day.cq.analytics.testandtarget.impl.TestandTargetCampaignType;
import com.day.cq.analytics.testandtarget.impl.TestandTargetConversionStyle;
import com.day.cq.analytics.testandtarget.impl.TestandTargetOperator;
import com.day.cq.analytics.testandtarget.impl.TestandtargetCampaign;
import com.day.cq.analytics.testandtarget.impl.TestandtargetHttpClientResponseException;
import com.day.cq.analytics.testandtarget.impl.TestandtargetPrivateService;
import com.day.cq.analytics.testandtarget.impl.TestandtargetSegment;
import com.day.cq.analytics.testandtarget.impl.TntCampaignState;
import com.day.cq.analytics.testandtarget.impl.TokenManager;
import com.day.cq.analytics.testandtarget.impl.exception.TestandtargetValidationException;
import com.day.cq.analytics.testandtarget.impl.model.TestandtargetExperience;
import com.day.cq.analytics.testandtarget.impl.model.TestandtargetOffer;
import com.day.cq.analytics.testandtarget.impl.model.TntMbox;
import com.day.cq.analytics.testandtarget.impl.util.ActivityComponentDataStorage;
import com.day.cq.analytics.testandtarget.impl.util.LocalIdCounter;
import com.day.cq.analytics.testandtarget.impl.util.MetricHelper;
import com.day.cq.analytics.testandtarget.impl.util.TSDKSynchronizedTaskRunner;
import com.day.cq.analytics.testandtarget.util.CampaignType;
import com.day.cq.analytics.testandtarget.util.ExperiencePageFilter;
import com.day.cq.analytics.testandtarget.util.OfferHelper;
import com.day.cq.analytics.testandtarget.util.TeaserPageFilter;
import com.day.cq.commons.Externalizer;
import com.day.cq.commons.Filter;
import com.day.cq.personalization.Segment;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.api.Revision;
import com.day.cq.wcm.api.WCMException;
import com.day.cq.wcm.api.WCMMode;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import com.day.cq.wcm.webservicesupport.ConfigurationManagerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferencePolicyOption;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.NonExistingResource;
import org.apache.sling.api.resource.PersistenceException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.codehaus.jackson.JsonNode;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
@Service(value={TargetMediator.class})
public class TestandtargetCampaignMediatorImpl
implements TargetMediator {
    private static final String PN_LAST_SYNC_ERROR = "lastSyncError";
    private static final String PN_CAMPAIGN_ACTIVE = "campaignActive";
    private static final long CAMPAIGN_LOCK_AQUIRE_LOG_INTERVAL = TimeUnit.SECONDS.toMillis(10);
    private static final Logger log = LoggerFactory.getLogger(TestandtargetCampaignMediatorImpl.class);
    private static final String DEFAULT_CONTENT_PATH = "/content/campaigns";
    private static final String TEASER_TYPE = "cq/personalization/components/teaserpage";
    private static final String EXPERIENCE_TYPE = "cq/personalization/components/experiencepage";
    private static final String EDITOR_URL = "/libs/cq/personalization/touch-ui/content/activities/createactivitywizard.html";
    private static final String SETTINGS_NODE = "cq:ActivitySettings";
    private static final String SETTINGS_LOCATIONS_NODE = "locations";
    private static final int MAX_SIZE_EXPERIENCE_NAME = 20;
    @Reference
    private TestandtargetPrivateService testandtargetService;
    @Reference
    private ConfigurationManagerFactory configurationManagerFactory;
    @Reference
    private ResourceResolverFactory resolverFactory;
    @Reference
    private TargetHelperService helperService;
    @Reference(policyOption=ReferencePolicyOption.GREEDY)
    private volatile TargetLocationNameProvider locationNameProvider;
    private TokenManager tokenManager = new TokenManager();
    private String contentPath;
    private ActivityComponentDataStorage activityComponentDataStorage;

    protected void activate(ComponentContext context) {
        this.contentPath = "/content/campaigns";
        this.activityComponentDataStorage = new ActivityComponentDataStorage(this.resolverFactory);
        ComponentManager tsdkComponentManager = ComponentManager.getComponentManager();
        tsdkComponentManager.setComponentDataStorage((ComponentDataStorage)this.activityComponentDataStorage);
        tsdkComponentManager.setSynchronizedTaskRunner((SynchronizedTaskRunner)new TSDKSynchronizedTaskRunner());
        log.info("{} started with contentPath {}", (Object)this.getClass().getSimpleName(), (Object)this.contentPath);
    }

    @Override
    public void syncAuthorCampaign(String campaignPath) throws TestandtargetException {
        if (!campaignPath.startsWith(this.contentPath)) {
            log.debug("Not synchronizing campaign at {} because it's not under the configured campaign path ({})", (Object)campaignPath, (Object)this.contentPath);
            return;
        }
        this.syncCampaignWithErrorLogging(campaignPath, WCMMode.PREVIEW);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void syncCampaignWithErrorLogging(String campaignPath, WCMMode wcmMode) throws TestandtargetException {
        String thirdPartyId;
        ResourceResolver serviceResolver = null;
        CampaignContext context = null;
        try {
            serviceResolver = this.resolverFactory.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "target"));
            Resource resource = serviceResolver.getResource(campaignPath);
            if (resource instanceof NonExistingResource) {
                log.warn("Cannot synchronize path at {} because the resource is non-existent");
                return;
            }
            if (resource.isResourceType("cq:Page") && resource.getChild("jcr:content").isResourceType("cq/personalization/components/experiencepage")) {
                campaignPath = resource.getParent().getPath();
            }
            if (!(context = this.getCampaignContext(serviceResolver, campaignPath, wcmMode)).isValid()) {
                log.debug("Not synchronizing page at path {} since it is not a valid campaign.", (Object)campaignPath);
                return;
            }
            if (!context.isCampaignActive()) {
                log.debug("Not synchronizing page at path {} since the campaign has been deactivated", (Object)campaignPath);
                return;
            }
            List<CampaignType> availableCampaignTypes = this.helperService.getAvailableCampaignTypes(context.getConfiguration());
            if (!availableCampaignTypes.contains((Object)context.getCampaignType())) {
                String msg = MessageFormat.format("Cannot synchronize campaign at {0} because your Target account options does not allow campaign type {1}", new Object[]{campaignPath, context.getCampaignType()});
                log.error(msg);
                throw new TestandtargetException(msg);
            }
            thirdPartyId = context.getThirdPartyId();
            try {
                while (!this.tokenManager.aquireToken(thirdPartyId, CAMPAIGN_LOCK_AQUIRE_LOG_INTERVAL)) {
                    log.warn("Did not get lock for campaign at path {} after {} milliseconds, still trying.", (Object)campaignPath, (Object)CAMPAIGN_LOCK_AQUIRE_LOG_INTERVAL);
                }
                serviceResolver.refresh();
                this.syncCampaign(context, serviceResolver);
            }
            catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                if (serviceResolver != null) {
                    serviceResolver.close();
                }
                return;
            }
            this.setErrorMessage(context, null);
        }
        catch (RepositoryException e) {
            this.setErrorMessage(context, (Throwable)e);
            throw new TestandtargetException((Throwable)e);
        }
        catch (LoginException e) {
            this.setErrorMessage(context, (Throwable)e);
            throw new TestandtargetException((Throwable)e);
        }
        catch (TestandtargetValidationException e) {
            throw new TestandtargetException(e.getMessage());
        }
        catch (TestandtargetException e) {
            this.setErrorMessage(context, e);
            throw e;
        }
        catch (RuntimeException e) {
            this.setErrorMessage(context, e);
            throw e;
        }
        catch (PersistenceException e) {
            this.setErrorMessage(context, (Throwable)e);
            throw new TestandtargetException((Throwable)e);
        }
        catch (TSDKException e) {
            this.setErrorMessage(context, (Throwable)e);
        }
        {
            finally {
                this.tokenManager.releaseToken(thirdPartyId);
            }
        }
        {
            throw new TestandtargetException((Throwable)e);
        }
        finally {
            if (serviceResolver != null) {
                serviceResolver.close();
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public void deleteCampaign(String campaignPath) throws TestandtargetException {
        block17 : {
            ResourceResolver serviceResolver = null;
            try {
                String campaignType;
                Configuration configuration;
                String thirdPartyId;
                block15 : {
                    Page campaignPage;
                    block16 : {
                        configuration = null;
                        thirdPartyId = null;
                        campaignType = null;
                        serviceResolver = this.resolverFactory.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "target"));
                        if (serviceResolver.resolve(campaignPath) instanceof NonExistingResource) break block15;
                        campaignPage = ((PageManager)serviceResolver.adaptTo(PageManager.class)).getPage(campaignPath);
                        configuration = this.getCampaignConfiguration(serviceResolver, campaignPage.getProperties());
                        if (configuration != null) break block16;
                        log.warn("Not synchronizing since the campaign at {} is not a Target campaign", (Object)campaignPath);
                        return;
                    }
                    thirdPartyId = OfferHelper.getThirdPartyCampaignId((Node)campaignPage.getContentResource().adaptTo(Node.class));
                    ValueMap properties = (ValueMap)campaignPage.adaptTo(ValueMap.class);
                    campaignType = (String)properties.get("campaignType", String.class);
                    this.setDeletedState(configuration, thirdPartyId, campaignType);
                    break block17;
                }
                log.debug("Campaign has been deleted from the repository, searching through revisions...");
                campaignPath = ResourceUtil.getParent((String)campaignPath);
                PageManager pMgr = (PageManager)serviceResolver.adaptTo(PageManager.class);
                Collection revisions = pMgr.getChildRevisions(campaignPath, null);
                for (Revision revision : revisions) {
                    if (!revision.isDeleted()) continue;
                    log.debug("Found revision {}", (Object)revision.getName());
                    ValueMap properties = revision.getProperties();
                    if (!properties.containsKey((Object)"cq:cloudserviceconfigs")) {
                        log.warn("Not synchronizing since the campaign at {} is not a Target campaign", (Object)campaignPath);
                        return;
                    }
                    configuration = this.getCampaignConfiguration(serviceResolver, properties);
                    try {
                        if (properties.containsKey((Object)"ttThirdPartyId")) {
                            thirdPartyId = (String)properties.get("ttThirdPartyId", String.class);
                        } else {
                            String deletedPath = campaignPath + "/" + revision.getName();
                            log.debug("Deleted path is {}", (Object)deletedPath);
                            thirdPartyId = OfferHelper.getCampaignName(deletedPath);
                        }
                        campaignType = (String)properties.get("campaignType", String.class);
                        this.setDeletedState(configuration, thirdPartyId, campaignType);
                        continue;
                    }
                    catch (LoginException e) {
                        throw new TestandtargetException((Throwable)e);
                    }
                    catch (RepositoryException e) {
                        throw new TestandtargetException((Throwable)e);
                    }
                    catch (WCMException e) {
                        throw new TestandtargetException((Throwable)e);
                    }
                }
            }
            finally {
                if (serviceResolver != null) {
                    serviceResolver.close();
                }
            }
        }
    }

    private void setDeletedState(Configuration configuration, String thirdPartyId, String campaignType) throws TestandtargetException {
        block2 : {
            try {
                String authorThirdPartyId = thirdPartyId + "--author";
                this.testandtargetService.setCampaignState(configuration, TntCampaignState.DEACTIVATED.name(), null, authorThirdPartyId, CampaignType.fromString(campaignType));
                this.testandtargetService.setCampaignState(configuration, TntCampaignState.DELETED.name(), null, authorThirdPartyId, CampaignType.fromString(campaignType));
            }
            catch (TestandtargetHttpClientResponseException e) {
                if (e.getResponseCode() != 404) break block2;
                log.warn("Campaign with third party id {} was not found in Target", (Object)thirdPartyId);
            }
        }
    }

    private void setErrorMessage(CampaignContext context, Throwable t) {
        if (context == null || context.getWcmMode() != WCMMode.PREVIEW) {
            return;
        }
        Resource resource = context.getPage().getContentResource();
        String msg = t != null ? t.getMessage() : "";
        ((ModifiableValueMap)resource.adaptTo(ModifiableValueMap.class)).put((Object)"lastSyncError", (Object)(msg == null ? "" : msg));
        try {
            resource.getResourceResolver().commit();
        }
        catch (PersistenceException e) {
            log.warn("Failed persisting error message on content resource at path {}", (Object)resource.getPath());
        }
    }

    private void syncCampaign(CampaignContext context, ResourceResolver serviceResolver) throws LoginException, RepositoryException, TestandtargetException, PersistenceException, TSDKException {
        long startTime = System.currentTimeMillis();
        Configuration configuration = context.getConfiguration();
        TestandtargetCampaign campaign = this.generateCampaignObject(context, serviceResolver);
        if (campaign == null) {
            return;
        }
        this.validateCampaignObject(campaign);
        String thirdPartyId = campaign.getThirdPartyId();
        this.testandtargetService.saveCampaign(context.getConfiguration(), thirdPartyId, campaign);
        String campaignPath = context.getPage().getPath();
        String nameSuffix = context.getNameSuffix();
        this.updateCampaignContent(serviceResolver, campaignPath, campaign, StringUtils.isEmpty((String)nameSuffix));
        this.testandtargetService.setCampaignState(configuration, "Approved", campaign.getCampaignId(), thirdPartyId, campaign.getCampaignType().toCampaignType());
        log.debug("Campaign synchronized to Target in {}ms", (Object)(System.currentTimeMillis() - startTime));
    }

    protected void validateCampaignObject(TestandtargetCampaign campaign) throws TestandtargetValidationException {
        log.debug("Validating campaing object...");
        List<TestandtargetExperience> experiences = campaign.getExperiences();
        int refNumber = experiences.get(0).getOffers().size();
        log.debug("Experience count must be {}", (Object)refNumber);
        for (int idx = 1; idx < experiences.size(); ++idx) {
            TestandtargetExperience e = experiences.get(idx);
            log.debug("Checking experience {}", (Object)e.getName());
            if (refNumber == e.getOffers().size()) continue;
            log.error("Experience {} has {} offers instead of {}", new Object[]{e.getName(), e.getOffers().size(), refNumber});
            throw new TestandtargetValidationException("Experience " + e.getName() + " has a different number of offers than " + "others");
        }
    }

    protected TestandtargetCampaign generateCampaignObject(CampaignContext context, final ResourceResolver serviceResolver) throws TestandtargetException, TestandtargetValidationException, TSDKException {
        Campaign existingCampaign;
        Page campaignPage = context.getPage();
        String campaignPath = campaignPage.getPath();
        String nameSuffix = context.getNameSuffix();
        String externalIdProp = context.getWcmMode() == WCMMode.DISABLED ? "cq:publishExternalId" : "cq:authorExternalId";
        StringBuilder title = new StringBuilder(campaignPage.getTitle());
        if (!"master".equals(context.getCampaignAmbit())) {
            title.append("-").append(context.getCampaignAmbit());
        }
        title.append(nameSuffix.length() > 0 ? "_" + nameSuffix : "");
        Calendar start = campaignPage.getOnTime();
        Calendar end = campaignPage.getOffTime();
        String conversionStyle = (String)campaignPage.getProperties().get("conversionStyle", String.class);
        String conversionGoal = null;
        String type = (String)campaignPage.getProperties().get("campaignType", (Object)CampaignType.LANDING_PAGE.getType());
        String campaignEditPath = this.buildEditUrl(serviceResolver, campaignPage.getPath());
        String lastModifiedBy = this.getLastModificationUser(campaignPage);
        try {
            if (conversionStyle != null && TestandTargetConversionStyle.fromString(conversionStyle) == TestandTargetConversionStyle.NAME) {
                conversionGoal = (String)campaignPage.getProperties().get("conversionGoalName", String.class);
            }
        }
        catch (RuntimeException e) {
            log.warn("Error retrieving the conversionStyle, falling back to default conversion goal", (Throwable)e);
        }
        TestandTargetCampaignType campaignType = TestandTargetCampaignType.fromString(type);
        String thirdPartyId = context.getThirdPartyId() + (nameSuffix.length() > 0 ? new StringBuilder().append("--").append(nameSuffix).toString() : "");
        final Configuration configuration = context.getConfiguration();
        log.debug("Generated thirdPartyId is {}. Looking for the campaign in Target...", (Object)thirdPartyId);
        long externalId = this.getExternalIdProp(campaignPage.getProperties(), externalIdProp);
        if (externalId == 0 && (existingCampaign = this.testandtargetService.getCampaignByThirdPartyId(configuration, thirdPartyId, CampaignType.fromString(type))) != null) {
            log.debug("Campaign with thirdPartyId {} found in Target (name {}, {}). It will be overwritten by this campaign", new Object[]{thirdPartyId, existingCampaign.getName(), existingCampaign.getId()});
            externalId = Long.valueOf(existingCampaign.getId());
        }
        log.debug("Would create campaign with title {}, start {}, end {}, conversionGoal {}, campaignType {} .", new Object[]{title, start, end, conversionGoal, campaignType});
        TestandtargetCampaign campaign = new TestandtargetCampaign(title.toString(), start != null ? start.getTime() : null, end != null ? end.getTime() : null, conversionGoal, campaignType, campaignEditPath, lastModifiedBy);
        log.debug("Campaign external id is {}", (Object)externalId);
        int priority = (Integer)campaignPage.getProperties().get("priority", (Object)0);
        campaign.setId(externalId);
        campaign.setForceLandingPageCampaign(context.getWcmMode() != WCMMode.DISABLED);
        campaign.setThirdPartyId(thirdPartyId);
        campaign.setPriority(priority);
        Resource campaignSettings = context.getSettings();
        Map savedLocations = new HashMap();
        String metricsJsonDefinition = "";
        long experienceLocalIdCounter = 0;
        int defaultVisitorPercentage = 0;
        if (campaignSettings != null) {
            ValueMap settingsMap = (ValueMap)campaignSettings.adaptTo(ValueMap.class);
            metricsJsonDefinition = (String)settingsMap.get("metricsJson", (Object)"");
            log.debug("Reading campaign locations...");
            savedLocations = this.readLocations(campaignSettings);
            log.debug("Reading experienceLocalId counter...");
            experienceLocalIdCounter = this.readLastCounterValue(campaignSettings, LocalIdCounter.EXPERIENCE);
            defaultVisitorPercentage = (Integer)settingsMap.get("defaultVisitorPercentage", (Object)0);
        }
        boolean invalidCampaign = false;
        int totalVisitorPercentage = defaultVisitorPercentage;
        Iterator experiences = campaignPage.listChildren((Filter)ExperiencePageFilter.INSTANCE);
        while (experiences.hasNext()) {
            Page experience = (Page)experiences.next();
            log.debug("Evaluating experience at {} ", (Object)experience.getPath());
            ValueMap properties = experience.getProperties();
            String segmentPath = (String)properties.get("cq:segments", String.class);
            if (campaignType == TestandTargetCampaignType.LANDING_PAGE && segmentPath == null) {
                log.debug("Experience page at {} does not have any segments defined, skippping campaign sync.", (Object)experience.getPath());
                throw new TestandtargetException(MessageFormat.format("The experience {0} has no segments. The campaign will not be synchronized", experience.getPath()));
            }
            TestandtargetExperience tandTExperience = this.createExperience(serviceResolver, experience, segmentPath, campaignType);
            if (tandTExperience == null) {
                invalidCampaign = true;
                break;
            }
            long experienceLocalId = this.getExternalIdProp(properties, externalIdProp) != 0 ? this.getExternalIdProp(properties, externalIdProp) : experienceLocalIdCounter + 1;
            log.debug("Setting experienceLocalId to {}", (Object)experienceLocalId);
            tandTExperience.withLocalId(experienceLocalId);
            Iterator offers = experience.listChildren((Filter)TeaserPageFilter.INSTANCE);
            while (offers.hasNext()) {
                Page offerPage = (Page)offers.next();
                Set<String> offerLocations = this.locationNameProvider.getOfferLocationNames(offerPage, context.getWcmMode());
                for (String offerLocation : offerLocations) {
                    String offerName = OfferHelper.getOfferName(offerPage, context.getWcmMode(), context.getCampaignAmbit());
                    TestandtargetOffer offer = new TestandtargetOffer(offerName, offerLocation, offerPage.getPath());
                    offer.setOfferId(OfferHelper.getOfferId(offerPage, context.getWcmMode()));
                    tandTExperience.addOffer(offer);
                    offer.setPagePath(offerPage.getPath());
                }
            }
            if (tandTExperience.getOffers().isEmpty()) {
                log.debug("Skipping campaign sync since experience at path {} has no offers.", (Object)experience.getPath());
                throw new TestandtargetValidationException(MessageFormat.format("Experience at path {0} has no offers. The campaign will not be synchronized", experience.getPath()));
            }
            if (tandTExperience.getPercentageConstraint() != null) {
                totalVisitorPercentage += tandTExperience.getPercentageConstraint().intValue();
            }
            campaign.addExperience(tandTExperience);
        }
        if (campaign.getExperiences().isEmpty()) {
            log.error("The campaign {} doesn't have any experiences. Synchronization aborted.", (Object)campaign.getName());
            throw new TestandtargetValidationException(MessageFormat.format("Campaign {0} doesn't have any experiences defined. The campaign will not be synchronized", campaign.getName()));
        }
        if (campaign.getCampaignType() == TestandTargetCampaignType.ABN && totalVisitorPercentage != 100) {
            String comparator = totalVisitorPercentage > 100 ? "greater" : "less";
            log.error("The overal visitor percentage is {} than 100 ( {} )", (Object)comparator, (Object)totalVisitorPercentage);
            throw new TestandtargetValidationException(MessageFormat.format("The overall visitor percentage is {0} than 100 ({1}). The campaign will not be synchronized", comparator, totalVisitorPercentage));
        }
        TestandtargetExperience defaultExperience = campaign.getCampaignType() == TestandTargetCampaignType.ABN ? TestandtargetExperience.newSegmentAndPercentBasedExperience("Default", defaultVisitorPercentage, new TestandtargetSegment[0]) : TestandtargetExperience.newSegmentBasedExperience("Default", new TestandtargetSegment[0]);
        defaultExperience.setExperienceLocalId(0);
        for (String mboxLocation : campaign.getAllMboxLocations()) {
            log.debug("Default experience : added offer for mbox location {}", (Object)mboxLocation);
            defaultExperience.addOffer(new TestandtargetOffer("Default AEM offer", mboxLocation, "", true));
        }
        campaign.getExperiences().add(0, defaultExperience);
        Set<String> unmatchedLocations = savedLocations.keySet();
        Collection<TntMbox> collectedMboxes = this.collectOffersMboxes(campaign.getOffers());
        for (TntMbox mbox : collectedMboxes) {
            TntMbox savedMbox = (TntMbox)savedLocations.get(mbox.getName());
            if (savedMbox == null) continue;
            mbox.setLocationLocalId(savedMbox.getLocationLocalId());
            unmatchedLocations.remove(savedMbox.getName());
        }
        campaign.addMboxes(new ArrayList<TntMbox>(collectedMboxes));
        this.removeLocations(campaignSettings, unmatchedLocations);
        this.detectOffersToCreate(configuration, campaign, context.getWcmMode());
        List syncMetrics = null;
        Analytics syncAnalytics = null;
        if (StringUtils.isNotEmpty((String)metricsJsonDefinition) && !this.metricLocalIdsPresent(metricsJsonDefinition)) {
            String processedMetricsJson = DataSerializer.getSerializedData((Object)new TargetGoalsAndSettingsProcessor().setGoalsAndSettings(metricsJsonDefinition).process(campaignPage.getPath()).getGoalsAndSettings(), (String)"goalsAndSettings");
            ModifiableValueMap modifiebleSettings = (ModifiableValueMap)campaignSettings.adaptTo(ModifiableValueMap.class);
            modifiebleSettings.put((Object)"metricsJson", (Object)processedMetricsJson);
            metricsJsonDefinition = processedMetricsJson;
        }
        if (StringUtils.isNotEmpty((String)metricsJsonDefinition) && context.getWcmMode() == WCMMode.DISABLED) {
            ArrayList<String> mboxNames = new ArrayList<String>();
            for (String mboxName : savedLocations.keySet()) {
                mboxNames.add(mboxName);
            }
            MetricsBuilder metricsBuilder = new TargetMetricsBuilder().setDisplayMboxes(mboxNames).setAnonymousAudienceSyncHelper(new AnonymousAudienceSyncHelper(){

                public List<String> syncSerializedSegments(List<String> list) {
                    ArrayList<String> createdAudiences = new ArrayList<String>();
                    for (String createAudienceJson : list) {
                        try {
                            String createAudienceResponse = TestandtargetCampaignMediatorImpl.this.testandtargetService.createAudience(configuration, createAudienceJson, false, serviceResolver.getUserID());
                            createdAudiences.add(createAudienceResponse);
                        }
                        catch (Exception e) {
                            log.error("Could not create audience! JSON body:" + createAudienceJson, (Throwable)e);
                        }
                    }
                    return createdAudiences;
                }
            });
            TargetGoalsBuilder targetGoalsBuilder = new TargetGoalsBuilder(metricsBuilder);
            TargetGoalsAndSettingsBuilder goalsBuilder = new TargetGoalsAndSettingsBuilder((GoalsBuilder)targetGoalsBuilder, (Object)null);
            goalsBuilder.setGoalsAndSettings(metricsJsonDefinition);
            GoalsAndSettings targetGoalsAndSettings = goalsBuilder.build().getGoalsAndSettings();
            syncMetrics = targetGoalsAndSettings.getGoals().getMetrics();
            syncAnalytics = targetGoalsAndSettings.getGoals().getAnalytics();
            if (StringUtils.isEmpty((String)syncAnalytics.getReportSuite())) {
                syncAnalytics = null;
            }
        }
        if (syncMetrics == null || syncMetrics.isEmpty()) {
            syncMetrics = new ArrayList<Metric>();
            Metric defaultMetric = MetricHelper.getDefaultMetric(context.getWcmMode(), campaign);
            syncMetrics.add(defaultMetric);
        }
        campaign.setMetrics(syncMetrics);
        campaign.setAnalytics(syncAnalytics);
        return campaign;
    }

    protected String buildEditUrl(ResourceResolver serviceResolver, String campaignPath) {
        Externalizer externalizer = (Externalizer)serviceResolver.adaptTo(Externalizer.class);
        StringBuilder editUrl = new StringBuilder(externalizer.authorLink(serviceResolver, "/libs/cq/personalization/touch-ui/content/activities/createactivitywizard.html"));
        String campaignRoot = StringUtils.substring((String)campaignPath, (int)0, (int)campaignPath.lastIndexOf("/"));
        editUrl.append(campaignRoot).append("/?activity=").append(campaignPath);
        return editUrl.toString();
    }

    protected void assignExperienceLocalIds(TestandtargetCampaign campaign, long localIdCounterValue) {
        log.debug("Assigning local ids to experiences...");
        LinkedList<TestandtargetExperience> experiences = new LinkedList<TestandtargetExperience>();
        for (TestandtargetExperience e : campaign.getExperiences()) {
            if (e.getExperienceLocalId() == -1) {
                experiences.add(e);
                continue;
            }
            log.debug("Experience {} already has the id {}, so we're skipping it...", (Object)e.getInternalName(), (Object)e.getExperienceLocalId());
        }
        log.debug("{} experiences don't have local id, assigning ids starting with {}", (Object)experiences.size(), (Object)(localIdCounterValue + 1));
        for (int c = 0; c < experiences.size(); ++c) {
            ((TestandtargetExperience)experiences.get(c)).setExperienceLocalId(++localIdCounterValue);
        }
    }

    protected Collection<TntMbox> collectOffersMboxes(List<TestandtargetOffer> offers) {
        HashMap<String, TntMbox> collectedMboxes = new HashMap<String, TntMbox>();
        log.debug("Collecting offers mboxes...");
        int localIdCounter = 0;
        TntMbox tntMbox = null;
        for (TestandtargetOffer o : offers) {
            log.debug("Collecting mbox names from offer {}", (Object)o.getName());
            if (collectedMboxes.get(o.getLocationName()) == null) {
                tntMbox = new TntMbox(localIdCounter++, o.getLocationName());
                collectedMboxes.put(o.getLocationName(), tntMbox);
            } else {
                tntMbox = (TntMbox)collectedMboxes.get(o.getLocationName());
            }
            o.setTntMbox(tntMbox);
        }
        return collectedMboxes.values();
    }

    protected Map<String, TntMbox> readLocations(Resource campaignSettings) {
        Resource mboxRoot = campaignSettings.getChild("locations");
        HashMap<String, TntMbox> locations = new HashMap<String, TntMbox>();
        if (mboxRoot != null) {
            Iterator it = mboxRoot.listChildren();
            while (it.hasNext()) {
                Resource locationRes = (Resource)it.next();
                ValueMap properties = (ValueMap)locationRes.adaptTo(ValueMap.class);
                locations.put(locationRes.getName(), new TntMbox((Long)properties.get("cq:authorExternalId", (Object)0), locationRes.getName()));
            }
        }
        return locations;
    }

    protected void removeLocations(Resource campaignSettings, Set<String> locationsToRemove) {
        try {
            Resource mboxRoot = campaignSettings.getChild("locations");
            if (mboxRoot != null && locationsToRemove != null) {
                for (String locationId : locationsToRemove) {
                    Resource locationNode = mboxRoot.getChild(locationId);
                    if (locationNode == null) continue;
                    campaignSettings.getResourceResolver().delete(locationNode);
                }
            }
        }
        catch (Exception e) {
            log.warn("Could not remove locations from the campaign settings!", (Throwable)e);
        }
    }

    protected long readLastCounterValue(Resource campaignSettings, LocalIdCounter counter) {
        ValueMap properties = (ValueMap)campaignSettings.adaptTo(ValueMap.class);
        return ((Integer)properties.get(counter.getPropName(), (Object)0)).intValue();
    }

    private void updateCampaignContent(ResourceResolver serviceResolver, String path, TestandtargetCampaign campaign, boolean isPublishCampaign) throws LoginException, RepositoryException, PersistenceException {
        log.debug("Updating campaign {} with id {}", (Object)path, (Object)campaign.getCampaignId());
        PageManager pageManager = (PageManager)serviceResolver.adaptTo(PageManager.class);
        Page campaignPage = pageManager.getPage(path);
        Resource campaignRes = campaignPage.getContentResource();
        String externalIdProp = isPublishCampaign ? "cq:publishExternalId" : "cq:authorExternalId";
        String legacyExternalIdProp = externalIdProp.replace("cq:", "");
        String settingsNodePath = campaignRes.getPath() + "/" + "cq:ActivitySettings";
        String locationsNodePath = settingsNodePath + "/" + "locations";
        ModifiableValueMap mvm = (ModifiableValueMap)campaignRes.adaptTo(ModifiableValueMap.class);
        if (mvm.containsKey((Object)legacyExternalIdProp)) {
            mvm.remove((Object)legacyExternalIdProp);
        }
        if (campaign.getId() != 0) {
            mvm.put((Object)externalIdProp, (Object)campaign.getCampaignId());
        }
        if (isPublishCampaign) {
            mvm.put((Object)"publishCampaignId", (Object)campaign.getCampaignId());
        }
        log.debug("Updating campaign id: {}", (Object)campaign.getCampaignId());
        log.debug("Updating experience local ids...");
        HashMap<String, Long> expLocalIds = new HashMap<String, Long>();
        for (TestandtargetExperience e : campaign.getExperiences()) {
            expLocalIds.put(e.getInternalName(), e.getExperienceLocalId());
        }
        Iterator children = campaignPage.listChildren((Filter)new Filter<Page>(){

            public boolean includes(Page page) {
                return page.getContentResource().isResourceType("cq/personalization/components/experiencepage");
            }
        });
        if (children != null) {
            while (children.hasNext()) {
                Page exPage = (Page)children.next();
                ModifiableValueMap pageProps = (ModifiableValueMap)exPage.getContentResource().adaptTo(ModifiableValueMap.class);
                Long experienceId = (Long)expLocalIds.get(exPage.getTitle());
                if (experienceId == null) continue;
                pageProps.put((Object)externalIdProp, (Object)experienceId);
            }
        } else {
            log.warn("No experiences found under {}", (Object)campaignPage.getPath());
        }
        log.debug("Done updating experience local ids");
        log.debug("Updating the campaign's settings...");
        Resource settings = ResourceUtil.getOrCreateResource((ResourceResolver)serviceResolver, (String)settingsNodePath, Collections.singletonMap("jcr:primaryType", "nt:unstructured"), (String)"", (boolean)false);
        ModifiableValueMap settingsProps = (ModifiableValueMap)settings.adaptTo(ModifiableValueMap.class);
        Resource locationsFolder = ResourceUtil.getOrCreateResource((ResourceResolver)serviceResolver, (String)locationsNodePath, Collections.singletonMap("jcr:primaryType", "nt:unstructured"), (String)"", (boolean)false);
        List<TntMbox> campaignLocations = campaign.getTntMboxes();
        for (TntMbox location : campaignLocations) {
            Resource locationResource;
            String locationName = location.getName();
            if (locationName.endsWith("--author")) {
                locationName = StringUtils.replace((String)locationName, (String)"--author", (String)"");
            }
            if ((locationResource = locationsFolder.getChild(locationName)) == null) {
                HashMap<String, Long> properties = new HashMap<String, Long>();
                properties.put(externalIdProp, location.getLocationLocalId());
                serviceResolver.create(locationsFolder, locationName, properties);
                continue;
            }
            ModifiableValueMap mvp = (ModifiableValueMap)locationResource.adaptTo(ModifiableValueMap.class);
            mvp.put((Object)externalIdProp, (Object)location.getLocationLocalId());
        }
        ArrayList localIds = new ArrayList();
        localIds.addAll(expLocalIds.values());
        Collections.sort(localIds, new Comparator<Long>(){

            @Override
            public int compare(Long o1, Long o2) {
                return o2.compareTo(o1);
            }
        });
        long experienceLocalIdCounter = this.readLastCounterValue(serviceResolver.getResource(settingsNodePath), LocalIdCounter.EXPERIENCE);
        experienceLocalIdCounter = experienceLocalIdCounter > (Long)localIds.get(0) ? experienceLocalIdCounter : (Long)localIds.get(0);
        settingsProps.put((Object)LocalIdCounter.EXPERIENCE.getPropName(), (Object)experienceLocalIdCounter);
        log.debug("Done updating the campaigns settings.");
        log.debug("Update missing offer ids...");
        for (TestandtargetOffer offer : campaign.getOffers()) {
            if (offer.isDefault()) continue;
            Page offerPage = pageManager.getPage(offer.getPagePath());
            ModifiableValueMap offerProps = (ModifiableValueMap)offerPage.getContentResource().adaptTo(ModifiableValueMap.class);
            if (isPublishCampaign && !offerProps.containsKey((Object)"cq:publishExternalId")) {
                offerProps.put((Object)"cq:publishExternalId", (Object)offer.getOfferId());
                continue;
            }
            if (isPublishCampaign || offerProps.containsKey((Object)"cq:authorExternalId")) continue;
            offerProps.put((Object)"cq:authorExternalId", (Object)offer.getOfferId());
        }
        log.debug("Done updating the missing offer ids.");
        serviceResolver.commit();
        log.debug("Campaign updated");
    }

    protected TestandtargetExperience createExperience(ResourceResolver serviceResolver, Page experience, String segmentPath, TestandTargetCampaignType type) {
        ValueMap experienceProps = experience.getProperties();
        int visitorPercentage = (Integer)experienceProps.get("visitorPercentage", (Object)-1);
        if (segmentPath == null) {
            return TestandtargetExperience.newPercentageBasedExperience(experience.getTitle(), visitorPercentage);
        }
        Resource segmentResource = serviceResolver.getResource(segmentPath);
        if (segmentResource == null) {
            log.warn("Dangling segment path {} for experience at {}", (Object)segmentPath, (Object)experience.getPath());
            return null;
        }
        Segment segment = (Segment)segmentResource.adaptTo(Segment.class);
        if (segment == null) {
            log.warn("Unable to adapt resource at {} to {}", (Object)segmentPath, (Object)Segment.class.getSimpleName());
            return null;
        }
        log.debug("Found segment {} at path {}", (Object)segment, (Object)segmentPath);
        switch (segment.getKind()) {
            case Direct: {
                TestandtargetSegment tandSegment = new TestandtargetSegment(TestandtargetSegment.Kind.VALUE, segment.getName(), TestandTargetOperator.getTestandTargetOperator(segment.getOperator()), segment.getValue());
                return type == TestandTargetCampaignType.ABN ? TestandtargetExperience.newSegmentAndPercentBasedExperience(experience.getTitle(), visitorPercentage, tandSegment) : TestandtargetExperience.newSegmentBasedExperience(experience.getTitle(), tandSegment);
            }
            case And: {
                ArrayList<TestandtargetSegment> segments = new ArrayList<TestandtargetSegment>();
                this.processAndSegments(segment, segments);
                if (segments.isEmpty()) {
                    log.warn("No valid T&T segments can be extracted from segment at {}", (Object)segmentPath);
                    return null;
                }
                TestandtargetSegment percentileSegment = null;
                for (TestandtargetSegment childSegment : segments) {
                    if (!"percentile".equals(childSegment.getName())) continue;
                    percentileSegment = childSegment;
                    break;
                }
                if (percentileSegment != null) {
                    int percentageConstraint;
                    if (segments.size() != 1) {
                        log.warn("Segment at path {} has one percentile segment and at least one other segment. This combination is not supported by Adobe Target, so skipping", (Object)segmentPath);
                    }
                    if ((percentageConstraint = this.evaluatePercentileSegment(segmentPath, percentileSegment)) == 0) {
                        log.warn("Found percentile segment at path {} whose percentageConstraints evaluates to {}, skipping.", (Object)segmentPath, (Object)percentageConstraint);
                        return null;
                    }
                    return TestandtargetExperience.newPercentageBasedExperience(experience.getTitle(), percentageConstraint);
                }
                return type == TestandTargetCampaignType.ABN ? TestandtargetExperience.newSegmentAndPercentBasedExperience(experience.getTitle(), visitorPercentage, segments.toArray(new TestandtargetSegment[0])) : TestandtargetExperience.newSegmentBasedExperience(experience.getTitle(), segments.toArray(new TestandtargetSegment[0]));
            }
            case ExternalReference: {
                TestandtargetSegment referenceSegment = new TestandtargetSegment(TestandtargetSegment.Kind.VALUE, segment.getName(), segment.getOperator(), segment.getValue());
                return type == TestandTargetCampaignType.ABN ? TestandtargetExperience.newSegmentAndPercentBasedExperience(experience.getTitle(), visitorPercentage, referenceSegment) : TestandtargetExperience.newSegmentBasedExperience(experience.getTitle(), referenceSegment);
            }
            case ClientOnly: {
                TestandtargetSegment byPathSegment = new TestandtargetSegment(TestandtargetSegment.Kind.BY_PATH, segment.getName(), segment.getOperator(), segment.getValue());
                return type == TestandTargetCampaignType.ABN ? TestandtargetExperience.newSegmentAndPercentBasedExperience(experience.getTitle(), visitorPercentage, byPathSegment) : TestandtargetExperience.newSegmentBasedExperience(experience.getTitle(), byPathSegment);
            }
        }
        log.warn("Unable to handle segment of kind {} at path {} ( {} )", new Object[]{segment.getKind(), segmentPath, segment});
        return null;
    }

    protected int evaluatePercentileSegment(String segmentPath, TestandtargetSegment percentileSegment) {
        int percentageConstraint = 0;
        try {
            for (String percentileEntry : percentileSegment.getValues()) {
                String[] range = percentileEntry.split("-");
                if (range.length != 2) continue;
                int start = Integer.parseInt(range[0]);
                int end = Integer.parseInt(range[1]);
                percentageConstraint += end - start;
            }
        }
        catch (NumberFormatException e) {
            log.warn("Failed parsing percentile segment at " + segmentPath, (Throwable)e);
        }
        return percentageConstraint;
    }

    protected void processAndSegments(Segment segment, List<TestandtargetSegment> segments) {
        block5 : for (Segment subSegment : segment.getChildren()) {
            switch (subSegment.getKind()) {
                case Direct: {
                    log.debug("Adding subSegment {}", (Object)subSegment);
                    segments.add(new TestandtargetSegment(TestandtargetSegment.Kind.VALUE, subSegment.getName(), TestandTargetOperator.getTestandTargetOperator(subSegment.getOperator()), subSegment.getValue()));
                    continue block5;
                }
                case And: {
                    log.debug("Recursing into subSegment {}", (Object)subSegment);
                    this.processAndSegments(subSegment, segments);
                    continue block5;
                }
                case ExternalReference: {
                    log.debug("Adding external reference segment{}", (Object)subSegment);
                    segments.add(new TestandtargetSegment(TestandtargetSegment.Kind.REFERENCE, subSegment.getName(), TestandTargetOperator.getTestandTargetOperator(subSegment.getOperator()), subSegment.getValue(), (long)Long.valueOf((String)subSegment.getValue().get(0))));
                    continue block5;
                }
            }
            log.warn("Not recursing into unhandled subSegment {}", (Object)subSegment);
        }
    }

    protected void detectOffersToCreate(Configuration configuration, TestandtargetCampaign campaign, WCMMode wcmMode) throws TestandtargetException {
        for (TestandtargetOffer offer : campaign.getOffers()) {
            try {
                log.debug("Checking for the external id property...");
                if (offer.getOfferId() != 0) {
                    log.debug("Offer external id is {}, skip offer creation...", (Object)offer.getOfferId());
                    continue;
                }
                log.debug("Verifying if offer {} exists in T&T ...", (Object)offer.getName());
                this.testandtargetService.getHTMLOffer(configuration, offer.getName());
                log.debug("Offer {} found in T&T.", (Object)offer.getName());
            }
            catch (TestandtargetUnsupportedApiOperationException e) {
                log.debug("Switching to the REST API...");
                long offerId = this.searchOffer(configuration, offer.getName());
                if (offerId == 0) {
                    log.debug("Offer not found in Target, creating...");
                    offerId = this.syncOffer(offer.getContentPath(), configuration, configuration.getResource().getResourceResolver(), wcmMode);
                }
                offer.setOfferId(offerId);
            }
            catch (TestandtargetException e) {
                offer.setNeedsCreating(true);
                log.debug("Offer {} not found in T&T ( error message from API : {} ).", (Object)offer.getName(), (Object)e.getMessage());
            }
        }
    }

    protected long searchOffer(Configuration configuration, String offerName) throws TestandtargetException {
        ListOffersRequest request = new ListOffersRequest().includeContent(false).withFilter(new ListFilter().property("name").value(offerName));
        Collection<ViewOfferResponse> allOffers = this.testandtargetService.listOffers(configuration, request);
        for (ViewOfferResponse offerResponse : allOffers) {
            if (!offerName.equalsIgnoreCase(offerResponse.getName())) continue;
            log.debug("Offer {} found in Target, id is {}", (Object)offerName, (Object)offerResponse.getId());
            return offerResponse.getId();
        }
        return 0;
    }

    @Override
    public void syncPublishCampaign(String campaignPath) throws TestandtargetException {
        log.debug("Synchronizing publish campaign at {}", (Object)campaignPath);
        if (!campaignPath.startsWith(this.contentPath)) {
            return;
        }
        this.syncCampaignWithErrorLogging(campaignPath, WCMMode.DISABLED);
    }

    @Override
    public void deactivatePublishCampaign(String campaignPath) throws TestandtargetException {
        log.debug("Deactivating path at {}", (Object)campaignPath);
        if (!campaignPath.startsWith(this.contentPath)) {
            return;
        }
        ResourceResolver serviceResolver = null;
        try {
            serviceResolver = this.resolverFactory.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "target"));
            Page page = ((PageManager)serviceResolver.adaptTo(PageManager.class)).getPage(campaignPath);
            if (page == null || !page.getContentResource().isResourceType("cq/personalization/components/campaignpage")) {
                log.warn("Page at {} is not a campaign, so you cannot deactivate it");
                return;
            }
            CampaignContext context = this.getCampaignContext(serviceResolver, campaignPath, WCMMode.READ_ONLY);
            if (!context.isValid()) {
                return;
            }
            ModifiableValueMap properties = (ModifiableValueMap)context.getPage().getContentResource().adaptTo(ModifiableValueMap.class);
            if (!properties.containsKey((Object)"cq:lastReplicated")) {
                log.debug("Campaign at {} is not published so we cannot deactivate it.", (Object)campaignPath);
                return;
            }
            String type = (String)properties.get("campaignType", (Object)"landingPage");
            this.testandtargetService.setCampaignState(context.getConfiguration(), "Deactivated", String.valueOf(context.getPublishExternalId()), context.getThirdPartyId(), CampaignType.fromString(type));
            properties.put((Object)"campaignActive", (Object)false);
            serviceResolver.commit();
        }
        catch (LoginException e) {
            throw new TestandtargetException((Throwable)e);
        }
        catch (PathNotFoundException e) {
            throw new TestandtargetException((Throwable)e);
        }
        catch (RepositoryException e) {
            throw new TestandtargetException((Throwable)e);
        }
        catch (PersistenceException e) {
            throw new TestandtargetException((Throwable)e);
        }
        finally {
            if (serviceResolver != null) {
                serviceResolver.close();
            }
        }
    }

    protected String getLastModificationUser(Page campaignPage) {
        String lastModifiedBy;
        TreeMap<Calendar, String> dates = new TreeMap<Calendar, String>();
        Iterator children = campaignPage.listChildren((Filter)new ResourceTypeFilter(new String[]{"cq/personalization/components/teaserpage", "cq/personalization/components/experiencepage"}));
        while (children.hasNext()) {
            Page child = (Page)children.next();
            dates.put(child.getLastModified(), child.getLastModifiedBy());
        }
        if (dates.size() == 0) {
            lastModifiedBy = campaignPage.getLastModifiedBy();
        } else {
            Calendar lastDate = (Calendar)dates.lastKey();
            lastModifiedBy = (String)dates.get(lastDate);
        }
        return lastModifiedBy;
    }

    protected CampaignContext getCampaignContext(ResourceResolver serviceResolver, String campaignPath, WCMMode wcmMode) throws RepositoryException {
        PageManager pageManager = (PageManager)serviceResolver.adaptTo(PageManager.class);
        Page page = OfferHelper.getCampaign(pageManager.getPage(campaignPath));
        if (page == null) {
            log.debug("Page at path {} is not part of a campaign.", (Object)campaignPath);
            return CampaignContext.INVALID;
        }
        Node contentNode = (Node)page.getContentResource().adaptTo(Node.class);
        String slingResourceType = contentNode.getProperty("sling:resourceType").getString();
        if (!"cq/personalization/components/campaignpage".equals(slingResourceType)) {
            log.debug("Skipping page at {} since its resourceType {} does not match {}", new Object[]{campaignPath, slingResourceType, "cq/personalization/components/campaignpage"});
            return CampaignContext.INVALID;
        }
        Configuration configuration = this.getCampaignConfiguration(serviceResolver, page.getProperties());
        if (configuration == null) {
            log.debug("Unable to process campaign page at {} since no configuration was found for it.", (Object)campaignPath);
            return CampaignContext.INVALID;
        }
        String thirdPartyId = OfferHelper.getThirdPartyCampaignId(contentNode);
        Resource settings = page.getContentResource().getChild("cq:ActivitySettings");
        long authorCampaignId = 0;
        long publishCampaignId = 0;
        boolean campaignActive = true;
        authorCampaignId = this.getExternalIdPropFromNode(contentNode, "cq:authorExternalId");
        publishCampaignId = this.getExternalIdPropFromNode(contentNode, "publishCampaignId");
        if (contentNode.hasProperty("campaignActive")) {
            campaignActive = contentNode.getProperty("campaignActive").getBoolean();
        }
        CampaignContext context = new CampaignContext(thirdPartyId, configuration, page, wcmMode, settings, authorCampaignId, publishCampaignId, campaignActive);
        context.setCampaignAmbit(this.getAmbitName(page));
        String campaignType = CampaignType.LANDING_PAGE.getType();
        if (contentNode.hasProperty("campaignType")) {
            campaignType = contentNode.getProperty("campaignType").getString();
        }
        context.setCampaignType(CampaignType.fromString(campaignType));
        return context;
    }

    private Configuration getCampaignConfiguration(ResourceResolver serviceResolver, ValueMap properties) throws RepositoryException {
        Configuration configuration = null;
        if (properties.containsKey((Object)"cq:cloudserviceconfigs")) {
            configuration = this.configurationManagerFactory.getConfigurationManager(serviceResolver).getConfiguration((String)properties.get("cq:cloudserviceconfigs", String.class));
        }
        return configuration;
    }

    @Override
    public long syncOffer(Configuration configuration, String offerPath) throws TestandtargetException {
        ResourceResolver serviceResolver = null;
        if (StringUtils.isEmpty((String)offerPath)) {
            log.warn("Empty path provided, we'll create the default offer in Target");
        }
        try {
            serviceResolver = this.resolverFactory.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "target"));
            return this.syncOffer(offerPath, configuration, serviceResolver);
        }
        catch (LoginException e) {
            log.error(e.getMessage(), (Throwable)e);
            throw new TestandtargetException((Throwable)e);
        }
        catch (TestandtargetException e) {
            log.error(e.getMessage(), (Throwable)e);
            throw e;
        }
    }

    @Override
    public long syncSegment(Configuration configuration, String segmentPath) {
        return 0;
    }

    private long syncOffer(String offerPath, Configuration configuration, ResourceResolver resourceResolver) throws TestandtargetException {
        return this.syncOffer(offerPath, configuration, resourceResolver, WCMMode.DISABLED);
    }

    private long syncOffer(String offerPath, Configuration configuration, ResourceResolver resourceResolver, WCMMode wcmMode) throws TestandtargetException {
        String offerName;
        long newOfferId;
        String offerContent;
        SaveOfferRequest saveOfferRequest;
        if (StringUtils.isEmpty((String)offerPath)) {
            return this.syncDefaultOffer(configuration);
        }
        Resource offerResource = resourceResolver.getResource(offerPath);
        Page offerPage = (Page)offerResource.adaptTo(Page.class);
        long offerId = OfferHelper.getOfferId(offerPage);
        if (offerId != (newOfferId = this.testandtargetService.createHTMLOffer(configuration, saveOfferRequest = new SaveOfferRequest(offerId, offerName = OfferHelper.getOfferName(offerPage, wcmMode, this.getAmbitName(offerPage)), offerContent = TestandtargetOffer.buildOfferContent(offerPath))))) {
            ModifiableValueMap mvm = (ModifiableValueMap)offerPage.getContentResource().adaptTo(ModifiableValueMap.class);
            String idProp = wcmMode != WCMMode.DISABLED ? "cq:authorExternalId" : "cq:publishExternalId";
            mvm.put((Object)idProp, (Object)newOfferId);
            try {
                resourceResolver.commit();
            }
            catch (PersistenceException e) {
                log.error(e.getMessage(), (Throwable)e);
                throw new TestandtargetException((Throwable)e);
            }
        }
        return newOfferId;
    }

    private long getExternalIdProp(ValueMap propsMap, String externalIdProp) {
        long externalId = (Long)propsMap.get(externalIdProp, (Object)0);
        if (externalId == 0) {
            String legacyExternalIdProp = externalIdProp.replace("cq:", "");
            externalId = (Long)propsMap.get(legacyExternalIdProp, (Object)0);
        }
        return externalId;
    }

    private long getExternalIdPropFromNode(Node contentNode, String externalIdProp) {
        long externalId = 0;
        Property nodeProp = null;
        String legacyExternalIdProp = externalIdProp.replace("cq:", "");
        try {
            if (contentNode.hasProperty(externalIdProp)) {
                nodeProp = contentNode.getProperty(externalIdProp);
            } else if (contentNode.hasProperty(legacyExternalIdProp)) {
                nodeProp = contentNode.getProperty(legacyExternalIdProp);
            }
            if (nodeProp != null) {
                externalId = nodeProp.getLong();
            }
        }
        catch (Exception e) {
            log.warn("Can't read external id property " + externalIdProp, (Throwable)e);
        }
        return externalId;
    }

    private String getAmbitName(Page page) {
        if (page == null) {
            return "";
        }
        if (page.getContentResource().isResourceType("cq/personalization/components/ambitpage")) {
            return page.getName();
        }
        return this.getAmbitName(page.getParent());
    }

    private long syncDefaultOffer(Configuration configuration) throws TestandtargetException {
        SaveOfferRequest offerRequest = new SaveOfferRequest("Default AEM offer", "<script type=\"text/javascript\">(function() { CQ_Analytics.TestTarget.signalDefaultOffer('${mbox.name}');})();</script>");
        long offerId = this.testandtargetService.createHTMLOffer(configuration, offerRequest);
        return offerId;
    }

    private boolean metricLocalIdsPresent(String metricsJsonDefinition) {
        boolean metricLocalIdsPresent = true;
        JsonObject goalsDef = new JsonParser().parse(metricsJsonDefinition).getAsJsonObject();
        JsonArray metricsArray = goalsDef.get("goals").getAsJsonObject().get("metrics").getAsJsonArray();
        for (JsonElement metricElement : metricsArray) {
            JsonObject metricJsonObj = metricElement.getAsJsonObject();
            if (metricJsonObj.has("metricLocalId")) continue;
            metricLocalIdsPresent = false;
            break;
        }
        return metricLocalIdsPresent;
    }

    protected void bindTestandtargetService(TestandtargetPrivateService testandtargetPrivateService) {
        this.testandtargetService = testandtargetPrivateService;
    }

    protected void unbindTestandtargetService(TestandtargetPrivateService testandtargetPrivateService) {
        if (this.testandtargetService == testandtargetPrivateService) {
            this.testandtargetService = null;
        }
    }

    protected void bindConfigurationManagerFactory(ConfigurationManagerFactory configurationManagerFactory) {
        this.configurationManagerFactory = configurationManagerFactory;
    }

    protected void unbindConfigurationManagerFactory(ConfigurationManagerFactory configurationManagerFactory) {
        if (this.configurationManagerFactory == configurationManagerFactory) {
            this.configurationManagerFactory = null;
        }
    }

    protected void bindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        this.resolverFactory = resourceResolverFactory;
    }

    protected void unbindResolverFactory(ResourceResolverFactory resourceResolverFactory) {
        if (this.resolverFactory == resourceResolverFactory) {
            this.resolverFactory = null;
        }
    }

    protected void bindHelperService(TargetHelperService targetHelperService) {
        this.helperService = targetHelperService;
    }

    protected void unbindHelperService(TargetHelperService targetHelperService) {
        if (this.helperService == targetHelperService) {
            this.helperService = null;
        }
    }

    protected void bindLocationNameProvider(TargetLocationNameProvider targetLocationNameProvider) {
        this.locationNameProvider = targetLocationNameProvider;
    }

    protected void unbindLocationNameProvider(TargetLocationNameProvider targetLocationNameProvider) {
        if (this.locationNameProvider == targetLocationNameProvider) {
            this.locationNameProvider = null;
        }
    }

    private class ResourceTypeFilter
    implements Filter<Page> {
        private final String[] types;

        ResourceTypeFilter(String[] types) {
            this.types = types;
        }

        public boolean includes(Page page) {
            String type;
            if (page == null) {
                return false;
            }
            Resource r = page.getContentResource();
            if (r == null) {
                return false;
            }
            boolean isType = false;
            String[] arr$ = this.types;
            int len$ = arr$.length;
            for (int i$ = 0; i$ < len$ && !(isType = r.isResourceType(type = arr$[i$])); ++i$) {
            }
            return isType;
        }
    }

    protected static class CampaignContext {
        static CampaignContext INVALID = new CampaignContext(null, null, null, null, null);
        private final String thirdPartyId;
        private final Configuration configuration;
        private final Page page;
        private final WCMMode wcmMode;
        private final Resource settings;
        private String campaignAmbit;
        private long authorExternalId;
        private long publishExternalId;
        private CampaignType campaignType;
        private boolean campaignActive = false;

        public CampaignContext(String thirdPartyId, Configuration configuration, Page page, WCMMode wcmMode, Resource settings) {
            this.settings = settings;
            this.thirdPartyId = thirdPartyId;
            this.configuration = configuration;
            this.page = page;
            this.wcmMode = wcmMode;
        }

        public CampaignContext(String thirdPartyId, Configuration configuration, Page page, WCMMode wcmMode, Resource settings, long authorCampaignId, long publishCampaignId, boolean campaignActive) {
            this(thirdPartyId, configuration, page, wcmMode, settings);
            this.authorExternalId = authorCampaignId;
            this.publishExternalId = publishCampaignId;
            this.campaignActive = campaignActive;
        }

        public CampaignType getCampaignType() {
            return this.campaignType;
        }

        public void setCampaignType(CampaignType type) {
            this.campaignType = type;
        }

        public String getCampaignAmbit() {
            return this.campaignAmbit;
        }

        public void setCampaignAmbit(String ambit) {
            this.campaignAmbit = ambit;
        }

        public boolean isValid() {
            return this.thirdPartyId != null && this.configuration != null;
        }

        public String getThirdPartyId() {
            return this.thirdPartyId;
        }

        public Configuration getConfiguration() {
            return this.configuration;
        }

        public Page getPage() {
            return this.page;
        }

        public WCMMode getWcmMode() {
            return this.wcmMode;
        }

        public String getNameSuffix() {
            return this.wcmMode != WCMMode.DISABLED ? "author" : "";
        }

        public Resource getSettings() {
            return this.settings;
        }

        public long getPublishExternalId() {
            return this.publishExternalId;
        }

        public long getAuthorExternalId() {
            return this.authorExternalId;
        }

        public boolean isCampaignActive() {
            return this.campaignActive;
        }
    }

}