AudienceManagerClientImpl.java 41.7 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.crypto.CryptoException
 *  com.adobe.granite.crypto.CryptoSupport
 *  javax.jcr.Node
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Deactivate
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.http.HttpEntity
 *  org.apache.http.HttpException
 *  org.apache.http.NameValuePair
 *  org.apache.http.client.entity.UrlEncodedFormEntity
 *  org.apache.http.client.methods.HttpGet
 *  org.apache.http.client.methods.HttpPost
 *  org.apache.http.client.methods.HttpRequestBase
 *  org.apache.http.client.utils.URIBuilder
 *  org.apache.http.entity.ByteArrayEntity
 *  org.apache.http.entity.ContentType
 *  org.apache.http.message.BasicNameValuePair
 *  org.apache.http.osgi.services.HttpClientBuilderFactory
 *  org.apache.sling.commons.json.JSONArray
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.aam.client;

import com.adobe.cq.aam.client.AudienceManagerFolderList;
import com.adobe.cq.aam.client.AudienceManagerItemImpl;
import com.adobe.cq.aam.client.JSONOAuthHttpClient;
import com.adobe.cq.aam.client.MemoryCookieStore;
import com.adobe.cq.aam.client.OAuthResponseImpl;
import com.adobe.cq.aam.client.PagedHttpIterator;
import com.adobe.cq.aam.client.TestData;
import com.adobe.cq.aam.client.spi.AudienceManagerAccessDenied;
import com.adobe.cq.aam.client.spi.AudienceManagerClient;
import com.adobe.cq.aam.client.spi.AudienceManagerConfiguration;
import com.adobe.cq.aam.client.spi.AudienceManagerFolder;
import com.adobe.cq.aam.client.spi.AudienceManagerFolders;
import com.adobe.cq.aam.client.spi.AudienceManagerItem;
import com.adobe.cq.aam.client.spi.HCCookieStore;
import com.adobe.cq.aam.client.spi.OAuthResponse;
import com.adobe.cq.aam.client.spi.SegmentService;
import com.adobe.cq.aam.client.spi.SyncResult;
import com.adobe.cq.aam.client.spi.TraitsService;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(immediate=1, metatype=1)
@Service(value={AudienceManagerClient.class})
public class AudienceManagerClientImpl
implements AudienceManagerClient {
    private static final int DEFAULT_POST_BATCH_SIZE = 10;
    private static final String DEFAULT_DEMDEX_API_ENDPOINT = "https://api.demdex.com/v1";
    private static final String FOLDERS_SEGMENTS_ENDPOINT = "/folders/segments/";
    private static final String FOLDERS_TRAITS_ENDPOINT = "/folders/traits/";
    private static final String DESTINATIONS_ENDPOINT = "/destinations/";
    private static final String BULK_CREATE_ENDPOINT = "/bulk-create";
    private static final String SEGMENTS_ENDPOINT = "/segments/";
    private static final String TRAITS_ENDPOINT = "/traits/";
    private static final String MAPPINGS_PAGE = "/mappings?page=";
    private static final String DEFAULT_DEMDEX_OAUTH_TOKEN_ENDPOINT = "https://api.demdex.com/oauth/token";
    private static final String BULK_DELETE_ENDPOINT = "/bulk-delete/";
    private static final String DEFAULT_DEMDEX_EVENT_ENDPOINT = "https://{0}.demdex.net/event";
    private static final String DEFAULT_CLIENT_ID = "clientid";
    private static final String DEFAULT_CLIENT_SECRET = "clientsecret";
    @Property(value={"https://api.demdex.com/oauth/token"})
    private static final String TOKEN_ENDPOINT = "endpoint.token";
    @Property(value={"https://api.demdex.com/v1"})
    private static final String API_ENDPOINT = "endpoint.api";
    @Property(value={"https://{0}.demdex.net/event"})
    private static final String EVENT_ENDPOINT = "endpoint.event";
    @Property(intValue={10})
    private static final String BATCH_SIZE = "batchsize";
    @Property(value={"clientid"})
    private static final String CLIENT_ID = "clientid";
    @Property(value={"clientsecret"})
    private static final String CLIENT_SECRET = "clientsecret";
    private static final String ERROR_PARTNER_OR_CONTAINERID_INVALID = "partner_invalid";
    private static final String ERROR_CLIENT_NOT_CONFIGURED = "client_not_configured";
    private static final Logger LOGGER = LoggerFactory.getLogger(AudienceManagerClientImpl.class);
    private static final long DAY_IN_MS = 86400000;
    private JSONOAuthHttpClient httpClient;
    private String tokenEndpoint;
    private String clientId;
    private String clientSecret;
    private String apiEndpoint;
    private String eventEndpoint;
    @Reference
    private CryptoSupport cryptoSupport;
    @Reference
    private TraitsService traitsService;
    @Reference
    private SegmentService segmentService;
    @Reference
    private HttpClientBuilderFactory httpClientBuilderFactory;
    private int maxBatchSize;
    private MethodFactory methodFactory;
    private boolean partnerCheckingEnabled;

    public AudienceManagerClientImpl() {
        this.methodFactory = new MethodFactory(){

            @Override
            public HttpPost getPostMethod(String url) {
                return new HttpPost(url);
            }

            @Override
            public HttpGet getGetMethod(String url) {
                return new HttpGet(url);
            }
        };
        this.partnerCheckingEnabled = false;
    }

    @Activate
    public void activate(ComponentContext componentContext) {
        this.httpClient = new JSONOAuthHttpClient(this.httpClientBuilderFactory, new MethodFactory(){

            @Override
            public HttpPost getPostMethod(String url) {
                return AudienceManagerClientImpl.this.methodFactory.getPostMethod(url);
            }

            @Override
            public HttpGet getGetMethod(String url) {
                return AudienceManagerClientImpl.this.methodFactory.getGetMethod(url);
            }
        });
        Dictionary properties = componentContext.getProperties();
        this.apiEndpoint = PropertiesUtil.toString(properties.get("endpoint.api"), (String)"https://api.demdex.com/v1");
        this.eventEndpoint = PropertiesUtil.toString(properties.get("endpoint.event"), (String)"https://{0}.demdex.net/event");
        this.tokenEndpoint = PropertiesUtil.toString(properties.get("endpoint.token"), (String)"https://api.demdex.com/oauth/token");
        this.clientId = PropertiesUtil.toString(properties.get("clientid"), (String)"clientid");
        this.clientSecret = PropertiesUtil.toString(properties.get("clientsecret"), (String)"clientsecret");
        this.maxBatchSize = PropertiesUtil.toInteger(properties.get("batchsize"), (int)10);
    }

    @Deactivate
    public void deactivate(ComponentContext componentContext) {
        this.httpClient = null;
    }

    @Override
    public OAuthResponse authenticate(String username, String password) throws AudienceManagerAccessDenied {
        return this.authenticate(username, password, new HashMap<String, Object>());
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public OAuthResponse authenticate(String username, String password, Map<String, Object> properties) throws AudienceManagerAccessDenied {
        try {
            OAuthResponseImpl oauthResponse;
            block10 : {
                if ("clientid".equals(this.clientId) || "clientsecret".equals(this.clientSecret)) {
                    return new OAuthResponseImpl("client_not_configured");
                }
                HttpPost postMethod = this.methodFactory.getPostMethod(this.tokenEndpoint);
                oauthResponse = new OAuthResponseImpl(this.clientId, this.clientSecret);
                postMethod.addHeader("Content-Type", "application/x-www-form-urlencoded");
                postMethod.addHeader("Authorization", oauthResponse.getBasicAuth());
                postMethod.addHeader("Accept", "application/json");
                ArrayList<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
                nvps.add(new BasicNameValuePair("grant_type", "password"));
                nvps.add(new BasicNameValuePair("username", username));
                nvps.add(new BasicNameValuePair("password", password));
                postMethod.setEntity((HttpEntity)new UrlEncodedFormEntity(nvps));
                oauthResponse.update(this.httpClient.executeJSONObject((HttpRequestBase)postMethod, 200, JSONObject.class), this.cryptoSupport);
                if (this.partnerCheckingEnabled && properties.containsKey("partner")) {
                    String testDestination = "VerifyPartner_" + System.currentTimeMillis();
                    LOGGER.debug("Create Destination");
                    long destinationId = this.createDestination(testDestination, ".cqclientintegration.adobe.com", "Temporary Partner Validation Distribution, should be deleted automatically, if not feel free to delete", oauthResponse);
                    LOGGER.debug("Created Destination {} ({})", (Object)testDestination, (Object)destinationId);
                    try {
                        String partner = (String)properties.get("partner");
                        String containerID = (String)properties.get("container");
                        LOGGER.debug("Getting DCS response for {} {} ", (Object)partner, (Object)containerID);
                        ArrayList<String[]> signals = new ArrayList<String[]>();
                        signals.add(new String[]{"c_verify", "CQ5Verification"});
                        JSONObject response = this.getDCSResponse(partner, containerID, signals);
                        if (!this.traitsService.containsDestination(response, testDestination, ".cqclientintegration.adobe.com")) {
                            LOGGER.debug("Partner Not associated with credentials ");
                            oauthResponse.setErrorStatus("partner_invalid");
                            break block10;
                        }
                        LOGGER.debug("Partner Was associated with credentials ");
                    }
                    finally {
                        LOGGER.debug("Delete Destingation {}  ", (Object)destinationId);
                        this.deleteDestination(destinationId, oauthResponse);
                        LOGGER.debug("Delete Destingation {} Done ", (Object)destinationId);
                    }
                }
            }
            LOGGER.debug("Done Authentication");
            return oauthResponse;
        }
        catch (IOException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (JSONException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (CryptoException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        return null;
    }

    public OAuthResponse refresh(OAuthResponse response) throws AudienceManagerAccessDenied {
        OAuthResponseImpl oauthResponse = (OAuthResponseImpl)response;
        String refreshToken = oauthResponse.getRefreshToken();
        if (refreshToken == null) {
            throw new IllegalStateException("Unable to refresh as no refresh token was supplied in the original response");
        }
        try {
            LOGGER.debug("Refreshing Oauth Access Token");
            HttpPost postMethod = this.methodFactory.getPostMethod("https://api.demdex.com/oauth/token");
            postMethod.addHeader("Content-Type", "application/x-www-form-urlencoded");
            postMethod.addHeader("Authorization", oauthResponse.getBasicAuth());
            LOGGER.debug("Refresh Token is {} ", (Object)oauthResponse.getRefreshToken());
            postMethod.addHeader("Accept", "application/json");
            ArrayList<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
            nvps.add(new BasicNameValuePair("grant_type", "refresh_token"));
            nvps.add(new BasicNameValuePair("refresh_token", oauthResponse.getRefreshToken()));
            postMethod.setEntity((HttpEntity)new UrlEncodedFormEntity(nvps));
            LOGGER.debug("Refresh Token is {} ", (Object)oauthResponse.getRefreshToken());
            oauthResponse.update(this.httpClient.executeJSONObject((HttpRequestBase)postMethod, 200, JSONObject.class), this.cryptoSupport);
            return oauthResponse;
        }
        catch (IOException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (JSONException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (CryptoException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (AudienceManagerAccessDenied e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
            throw e;
        }
        return null;
    }

    public void checkAccess(OAuthResponseImpl oAuthResponseImpl) throws CryptoException, RepositoryException, AudienceManagerAccessDenied, IOException {
        HttpGet getMethod = this.httpClient.prepareMethod(oAuthResponseImpl, this.methodFactory.getGetMethod(this.apiEndpoint + "/traits/" + "?search=testing"));
        this.httpClient.executeJSONObject((HttpRequestBase)getMethod, 200, JSONArray.class);
    }

    @Override
    public boolean isValidForUse(AudienceManagerConfiguration config) {
        try {
            OAuthResponseImpl oauth = new OAuthResponseImpl(config.getNode(), this.clientId, this.clientSecret, this.cryptoSupport);
            if (oauth.hasExpired() && oauth.getRefreshToken() == null) {
                LOGGER.debug("Invalid Config: Has expired {} ", (Object)oauth.hasExpired());
                LOGGER.debug("Invalid Config: Access Token {} ", (Object)oauth.getAccessToken());
                LOGGER.debug("Invalid Config: Refresh Token {} ", (Object)oauth.getRefreshToken());
                return false;
            }
            return true;
        }
        catch (Exception e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
            return false;
        }
    }

    @Override
    public AudienceManagerFolders getSegmentFolders(AudienceManagerConfiguration config, boolean autoSave) throws AudienceManagerAccessDenied {
        return this.getFolders(config, this.apiEndpoint + "/folders/segments/" + "?expand=true", autoSave);
    }

    @Override
    public AudienceManagerFolders getTraitFolders(AudienceManagerConfiguration config, boolean autoSave) throws AudienceManagerAccessDenied {
        return this.getFolders(config, this.apiEndpoint + "/folders/traits/" + "?expand=true", autoSave);
    }

    @Override
    public Iterable<AudienceManagerItem> getSegments(final AudienceManagerConfiguration config, final AudienceManagerFolders folders, final boolean autoSave) {
        return new Iterable<AudienceManagerItem>(){

            @Override
            public Iterator<AudienceManagerItem> iterator() {
                String offlineTestSuite = null;
                if (config.isOfflineTest()) {
                    offlineTestSuite = config.getOfflineTestSet();
                }
                return new PagedHttpIterator<AudienceManagerItem>(offlineTestSuite){

                    @Override
                    protected AudienceManagerItem getElement(JSONObject jsonObject) throws JSONException {
                        return new AudienceManagerItemImpl(jsonObject, folders, config.getTemplate());
                    }

                    @Override
                    protected JSONObject getJSONPageObject(int page) throws CryptoException, IOException, RepositoryException, AudienceManagerAccessDenied {
                        try {
                            return AudienceManagerClientImpl.this.httpClient.executeJSONObject(AudienceManagerClientImpl.this.prepareOAuthMethodFromConfig(config.getNode(), (T)((HttpRequestBase)AudienceManagerClientImpl.this.methodFactory.getGetMethod(AudienceManagerClientImpl.this.apiEndpoint + "/segments/" + "?page=" + page)), autoSave), 200, JSONObject.class);
                        }
                        catch (AudienceManagerAccessDenied e) {
                            AudienceManagerClientImpl.this.refreshAccessToken(config.getNode(), autoSave);
                            return AudienceManagerClientImpl.this.httpClient.executeJSONObject(AudienceManagerClientImpl.this.prepareOAuthMethodFromConfig(config.getNode(), (T)((HttpRequestBase)AudienceManagerClientImpl.this.methodFactory.getGetMethod(AudienceManagerClientImpl.this.apiEndpoint + "/segments/" + "?page=" + page)), autoSave), 200, JSONObject.class);
                        }
                    }
                };
            }

        };
    }

    @Override
    public Iterable<AudienceManagerItem> getTraits(final AudienceManagerConfiguration config, final AudienceManagerFolders folders, final boolean autoSave) {
        return new Iterable<AudienceManagerItem>(){

            @Override
            public Iterator<AudienceManagerItem> iterator() {
                String offlineTestSuite = null;
                if (config.isOfflineTest()) {
                    offlineTestSuite = config.getOfflineTestSet();
                }
                return new PagedHttpIterator<AudienceManagerItem>(offlineTestSuite){

                    @Override
                    protected AudienceManagerItem getElement(JSONObject jsonObject) throws JSONException {
                        return new AudienceManagerItemImpl(jsonObject, folders, config.getTemplate());
                    }

                    @Override
                    protected JSONObject getJSONPageObject(int page) throws CryptoException, IOException, RepositoryException, AudienceManagerAccessDenied {
                        try {
                            return AudienceManagerClientImpl.this.httpClient.executeJSONObject(AudienceManagerClientImpl.this.prepareOAuthMethodFromConfig(config.getNode(), (T)((HttpRequestBase)AudienceManagerClientImpl.this.methodFactory.getGetMethod(AudienceManagerClientImpl.this.apiEndpoint + "/traits/" + "?page=" + page)), autoSave), 200, JSONObject.class);
                        }
                        catch (AudienceManagerAccessDenied e) {
                            AudienceManagerClientImpl.this.refreshAccessToken(config.getNode(), autoSave);
                            return AudienceManagerClientImpl.this.httpClient.executeJSONObject(AudienceManagerClientImpl.this.prepareOAuthMethodFromConfig(config.getNode(), (T)((HttpRequestBase)AudienceManagerClientImpl.this.methodFactory.getGetMethod(AudienceManagerClientImpl.this.apiEndpoint + "/traits/" + "?page=" + page)), autoSave), 200, JSONObject.class);
                        }
                    }
                };
            }

        };
    }

    @Override
    public Iterable<AudienceManagerItem> getTraits(AudienceManagerConfiguration config, AudienceManagerFolders folders, String[] ids, String search, boolean autoSave) throws AudienceManagerAccessDenied {
        ArrayList<AudienceManagerItem> audienceManagerItems = new ArrayList<AudienceManagerItem>();
        try {
            Node configNode = config.getNode();
            if (search != null && search.trim().length() > 0) {
                HttpGet getMethod = this.prepareOAuthMethodFromConfig(configNode, (T)this.methodFactory.getGetMethod(this.apiEndpoint + "/traits/" + "?search=" + URLEncoder.encode(search, "UTF-8")), autoSave);
                JSONArray result = this.httpClient.executeJSONObject((HttpRequestBase)getMethod, 200, JSONArray.class);
                for (int i = 0; i < result.length(); ++i) {
                    audienceManagerItems.add(new AudienceManagerItemImpl(result.getJSONObject(i), folders, ""));
                }
            } else {
                for (String traitID : ids) {
                    long safeTraitID = Long.parseLong(traitID);
                    HttpGet getMethod = this.prepareOAuthMethodFromConfig(configNode, (T)this.methodFactory.getGetMethod(this.apiEndpoint + "/traits/" + safeTraitID), autoSave);
                    JSONObject result = this.httpClient.executeJSONObject((HttpRequestBase)getMethod, 200, JSONObject.class);
                    audienceManagerItems.add(new AudienceManagerItemImpl(result, folders, ""));
                }
            }
        }
        catch (RepositoryException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (CryptoException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (JSONException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (IOException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        return audienceManagerItems;
    }

    @Override
    public Iterable<AudienceManagerItem> getSegments(AudienceManagerConfiguration config, String[] traits) throws AudienceManagerAccessDenied {
        try {
            String url = MessageFormat.format(this.eventEndpoint, config.getPartner());
            NameValuePair[] params = this.addTraitParams(this.traitsService.updateTraits(config, traits), this.getDefaultParams(config.getContainerNSID())).toArray((T[])new NameValuePair[0]);
            URIBuilder builder = new URIBuilder();
            URL buildurl = new URL(url);
            builder.setParameters(params).setScheme(buildurl.getProtocol()).setPort(buildurl.getPort()).setHost(buildurl.getHost()).setPath(buildurl.getPath()).setUserInfo(buildurl.getUserInfo());
            URI uri = builder.build();
            HttpGet eventMethod = this.methodFactory.getGetMethod(uri.toASCIIString());
            MemoryCookieStore cookieStore = new MemoryCookieStore();
            return this.traitsService.getSegments(config, this.httpClient.executeJSONObject((HttpRequestBase)eventMethod, 200, JSONObject.class, cookieStore));
        }
        catch (IOException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (HttpException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (URISyntaxException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        return null;
    }

    @Override
    public Iterable<String> getSegmentIds(AudienceManagerConfiguration config, String[] traits) throws AudienceManagerAccessDenied {
        try {
            List<String[]> traitList = this.traitsService.updateTraits(config, traits);
            return this.traitsService.getSegmentIds(config, this.getDCSResponse(config.getPartner(), config.getContainerNSID(), traitList));
        }
        catch (IOException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
            return null;
        }
    }

    private JSONObject getDCSResponse(String partner, String container, List<String[]> traitList) throws IOException, AudienceManagerAccessDenied {
        String url = MessageFormat.format(this.eventEndpoint, partner.toLowerCase());
        NameValuePair[] params = this.addTraitParams(traitList, this.getDefaultParams(container)).toArray((T[])new NameValuePair[0]);
        try {
            URIBuilder builder = new URIBuilder();
            URL buildurl = new URL(url);
            builder.setParameters(params).setScheme(buildurl.getProtocol()).setPort(buildurl.getPort()).setHost(buildurl.getHost()).setPath(buildurl.getPath()).setUserInfo(buildurl.getUserInfo());
            URI uri = builder.build();
            HttpGet eventMethod = this.methodFactory.getGetMethod(uri.toASCIIString());
            MemoryCookieStore cookieStore = new MemoryCookieStore();
            return this.httpClient.executeJSONObject((HttpRequestBase)eventMethod, 200, JSONObject.class, cookieStore);
        }
        catch (HttpException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
            return null;
        }
        catch (URISyntaxException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
            return null;
        }
    }

    @Override
    public void setupDestinations(AudienceManagerConfiguration config, SyncResult syncResult) throws AudienceManagerAccessDenied {
        this.setupDestinations(config, syncResult, "CQIntegrationDestination");
    }

    public void setupDestinations(AudienceManagerConfiguration config, SyncResult syncResult, String destinationName) throws AudienceManagerAccessDenied {
        try {
            long destinationId = this.getOrCreateDestination(config, destinationName);
            this.registerNewSegments(config, destinationId, syncResult);
        }
        catch (JSONException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (RepositoryException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (CryptoException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (IOException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
    }

    private long getOrCreateDestination(AudienceManagerConfiguration config, String destinationName) throws CryptoException, RepositoryException, AudienceManagerAccessDenied, IOException, JSONException {
        Node configNode = config.getNode();
        HttpGet checkDestination = this.prepareOAuthMethodFromConfig(configNode, (T)this.methodFactory.getGetMethod(this.apiEndpoint + "/destinations/"), false);
        JSONArray results = this.httpClient.executeJSONObject((HttpRequestBase)checkDestination, 200, JSONArray.class);
        for (int i = 0; i < results.length(); ++i) {
            JSONObject destination = results.getJSONObject(i);
            if (destination == null || !destination.has("name") || !destinationName.equals(destination.get("name"))) continue;
            return destination.getLong("destinationId");
        }
        return this.createDestination(destinationName, ".cqclientintegration.adobe.com", "Auto Created CQ Integration Cookie Destination: Please do not edit or disable without talking to the team managing the CQ installation connected to this destination.Doing so may break integration.", this.checkOAuthResponse(configNode, new OAuthResponseImpl(configNode, this.clientId, this.clientSecret, this.cryptoSupport), false));
    }

    private long createDestination(String destinationName, String domain, String description, OAuthResponseImpl oauthResponse) throws JSONException, IOException, AudienceManagerAccessDenied {
        JSONObject requestBody = new JSONObject();
        requestBody.put("name", (Object)destinationName);
        if (description != null) {
            requestBody.put("description", (Object)description);
        }
        requestBody.put("destinationType", (Object)"ADS");
        requestBody.put("cookieName", (Object)destinationName);
        requestBody.put("cnameDomain", (Object)domain);
        requestBody.put("maxSize", (Object)"2048");
        requestBody.put("ttl", (Object)"0");
        requestBody.put("domainRestrictions", (Object)"ALL_DOMAINS");
        requestBody.put("formatType", (Object)"SINGLE_KEY");
        requestBody.put("singleKey", (Object)"segs");
        requestBody.put("keySeparator", (Object)"=");
        requestBody.put("valueSeparator", (Object)",");
        HttpPost createDestination = this.prepareJSONPostMethod(oauthResponse, this.methodFactory.getPostMethod(this.apiEndpoint + "/destinations/"), requestBody);
        JSONObject created = this.httpClient.executeJSONObject((HttpRequestBase)createDestination, 201, JSONObject.class);
        LOGGER.debug("Created response is {} ", (Object)created.toString(2));
        if (created != null && created.has("name") && destinationName.equals(created.get("name"))) {
            return created.getLong("destinationId");
        }
        throw new IllegalStateException("Unable to create destination " + destinationName + " on Audience Manager Server");
    }

    private void deleteDestination(long destinationId, OAuthResponseImpl oAuthResponse) throws IOException, AudienceManagerAccessDenied {
        JSONArray batch = new JSONArray();
        batch.put(destinationId);
        this.executeJSONBatch(oAuthResponse, batch, this.methodFactory.getPostMethod(this.apiEndpoint + "/destinations/" + "/bulk-delete/"), 204);
    }

    private JSONObject getDestinationMappings(long destinationId, OAuthResponseImpl oAuthResponse) throws IOException, AudienceManagerAccessDenied, JSONException {
        JSONObject destinations = new JSONObject();
        int total = 1;
        int n = 0;
        for (int page = 0; n < total && page < 500; ++page) {
            HttpGet getMappings = this.prepareOAuthMethod(oAuthResponse, (T)this.methodFactory.getGetMethod(this.apiEndpoint + "/destinations/" + destinationId + "/mappings?page=" + page));
            JSONObject results = this.httpClient.executeJSONObject((HttpRequestBase)getMappings, 200, JSONObject.class);
            LOGGER.debug(results.toString(2));
            if (total == 1) {
                total = results.has("total") ? results.getInt("total") : 0;
            }
            JSONArray list = results.getJSONArray("list");
            for (int i = 0; i < list.length(); ++i) {
                JSONObject dest = list.getJSONObject(i);
                if (dest.has("destinationMappingId")) {
                    destinations.put(dest.getString("destinationMappingId"), (Object)dest);
                }
                ++n;
            }
        }
        return destinations;
    }

    private void registerNewSegments(AudienceManagerConfiguration config, long destinationId, SyncResult syncResult) throws JSONException, CryptoException, RepositoryException, IOException, AudienceManagerAccessDenied {
        Node configNode = config.getNode();
        OAuthResponseImpl oAuthResponseImpl = this.checkOAuthResponse(configNode, new OAuthResponseImpl(configNode, this.clientId, this.clientSecret, this.cryptoSupport), false);
        final JSONObject destinations = this.getDestinationMappings(destinationId, oAuthResponseImpl);
        HashSet<Long> seen = new HashSet<Long>();
        for (String k : new Iterable<String>(){

            @Override
            public Iterator<String> iterator() {
                return destinations.keys();
            }
        }) {
            JSONObject dest = destinations.getJSONObject(k);
            if (!dest.has("traitType") || !"SEGMENT".equals(dest.get("traitType")) || !dest.has("sid")) continue;
            seen.add(dest.getLong("sid"));
        }
        JSONArray batch = new JSONArray();
        ArrayList<Long> seglist = new ArrayList<Long>();
        long startDate = System.currentTimeMillis() - 86400000;
        for (AudienceManagerItem item : syncResult.getNewSegments()) {
            if (seen.contains(item.getItemId())) continue;
            seen.add(item.getItemId());
            seglist.add(item.getItemId());
            JSONObject segment = new JSONObject();
            segment.put("sid", item.getItemId());
            segment.put("traitType", (Object)"SEGMENT");
            segment.put("startDate", startDate);
            segment.put("valueAlias", (Object)String.valueOf(item.getItemId()));
            batch.put((Object)segment);
            if (batch.length() < this.maxBatchSize) continue;
            JSONArray result = new JSONArray();
            try {
                oAuthResponseImpl = this.checkOAuthResponse(configNode, oAuthResponseImpl, false);
                result = this.executeJSONBatch(oAuthResponseImpl, batch, this.methodFactory.getPostMethod(this.apiEndpoint + "/destinations/" + destinationId + "/bulk-create"), 200);
            }
            catch (AudienceManagerAccessDenied e) {
                this.refreshAccessToken(configNode, false);
                oAuthResponseImpl = this.checkOAuthResponse(configNode, new OAuthResponseImpl(configNode, this.clientId, this.clientSecret, this.cryptoSupport), false);
                result = this.executeJSONBatch(oAuthResponseImpl, batch, this.methodFactory.getPostMethod(this.apiEndpoint + "/destinations/" + destinationId + "/bulk-create"), 200);
            }
            if (result.length() != batch.length()) {
                LOGGER.error("None of the following segments were registered {} ", seglist);
                LOGGER.error("Please Log in to the Audience Manager UI and try and add each segment ID in turn. One of the segments is in error, probably as a result of being duplicated in an Audience Manager SQL table. Alternatively delete the Destination called CQIntegrationDestination set the batch size on this component to 1 (OSGi console) and retry.");
            }
            seglist.clear();
            batch = new JSONArray();
        }
        if (batch.length() > 0) {
            try {
                this.executeJSONBatch(oAuthResponseImpl, batch, this.methodFactory.getPostMethod(this.apiEndpoint + "/destinations/" + destinationId + "/bulk-create"), 200);
            }
            catch (AudienceManagerAccessDenied e) {
                this.refreshAccessToken(configNode, false);
                oAuthResponseImpl = this.checkOAuthResponse(configNode, new OAuthResponseImpl(configNode, this.clientId, this.clientSecret, this.cryptoSupport), false);
                this.executeJSONBatch(oAuthResponseImpl, batch, this.methodFactory.getPostMethod(this.apiEndpoint + "/destinations/" + destinationId + "/bulk-create"), 200);
            }
        }
        configNode.getSession().save();
    }

    private OAuthResponseImpl refreshAccessToken(Node configNode, boolean autoSave) throws CryptoException, RepositoryException, AudienceManagerAccessDenied {
        return this.checkOAuthResponse(configNode, new OAuthResponseImpl(configNode, this.clientId, this.clientSecret, this.cryptoSupport), autoSave);
    }

    private HttpPost prepareJSONPostMethod(OAuthResponseImpl oauthResponse, HttpPost postMethod, JSONArray requestBody) throws UnsupportedEncodingException {
        postMethod = this.prepareOAuthMethod(oauthResponse, (T)postMethod);
        postMethod.setHeader("Content-Type", "application/json");
        ByteArrayEntity requestEntity = new ByteArrayEntity(requestBody.toString().getBytes("UTF-8"), ContentType.APPLICATION_JSON);
        postMethod.setEntity((HttpEntity)requestEntity);
        return postMethod;
    }

    private HttpPost prepareJSONPostMethod(OAuthResponseImpl oauthResponse, HttpPost postMethod, JSONObject requestBody) throws UnsupportedEncodingException {
        postMethod = this.prepareOAuthMethod(oauthResponse, (T)postMethod);
        postMethod.setHeader("Content-Type", "application/json");
        ByteArrayEntity requestEntity = new ByteArrayEntity(requestBody.toString().getBytes("UTF-8"), ContentType.APPLICATION_JSON);
        postMethod.setEntity((HttpEntity)requestEntity);
        return postMethod;
    }

    private <T extends HttpRequestBase> T prepareOAuthMethodFromConfig(Node configNode, T method, boolean autoSave) throws CryptoException, RepositoryException, AudienceManagerAccessDenied {
        return this.prepareOAuthMethod(this.checkOAuthResponse(configNode, new OAuthResponseImpl(configNode, this.clientId, this.clientSecret, this.cryptoSupport), autoSave), method);
    }

    private <T extends HttpRequestBase> T prepareOAuthMethod(OAuthResponseImpl oauthResponse, T method) {
        return this.httpClient.prepareMethod(oauthResponse, method);
    }

    private OAuthResponseImpl checkOAuthResponse(Node n, OAuthResponseImpl oAuthResponse, boolean autoSave) throws CryptoException, RepositoryException, AudienceManagerAccessDenied {
        if (oAuthResponse.hasExpired()) {
            if ((oAuthResponse = (OAuthResponseImpl)this.refresh(oAuthResponse)) == null) {
                throw new RuntimeException("OAuth Authentication token has expired and cant be refreshed ");
            }
            oAuthResponse.save(n, this.cryptoSupport);
            if (autoSave) {
                n.getSession().save();
            }
        } else {
            LOGGER.debug("Access Token is valid and current value: {} ", (Object)oAuthResponse.getAccessToken());
        }
        return oAuthResponse;
    }

    private AudienceManagerFolders getFolders(AudienceManagerConfiguration config, String url, boolean autoSave) throws AudienceManagerAccessDenied {
        try {
            if (config.isOfflineTest()) {
                return new AudienceManagerFolderList(new JSONArray(TestData.loadTestData(config.getOfflineTestSet() + "_folders.json")), config.getTemplate());
            }
            try {
                return new AudienceManagerFolderList(this.httpClient.executeJSONObject((HttpRequestBase)this.prepareOAuthMethodFromConfig(config.getNode(), (T)this.methodFactory.getGetMethod(url), autoSave), 200, JSONArray.class), config.getTemplate());
            }
            catch (AudienceManagerAccessDenied e) {
                this.refreshAccessToken(config.getNode(), autoSave);
                return new AudienceManagerFolderList(this.httpClient.executeJSONObject((HttpRequestBase)this.prepareOAuthMethodFromConfig(config.getNode(), (T)this.methodFactory.getGetMethod(url), autoSave), 200, JSONArray.class), config.getTemplate());
            }
        }
        catch (IOException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (JSONException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (RepositoryException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        catch (CryptoException e) {
            LOGGER.error(e.getMessage(), (Throwable)e);
        }
        return new AudienceManagerFolders(){
            private List<AudienceManagerFolder> empty;

            @Override
            public AudienceManagerFolder getFolder(long folderId) {
                return null;
            }

            @Override
            public Iterator<AudienceManagerFolder> iterator() {
                return this.empty.iterator();
            }
        };
    }

    private JSONArray executeJSONBatch(OAuthResponseImpl oAuthResponseImpl, JSONArray batch, HttpPost method, int expectedCode) throws IOException, AudienceManagerAccessDenied {
        HttpPost batchCreate = this.prepareJSONPostMethod(oAuthResponseImpl, method, batch);
        JSONArray result = this.httpClient.executeJSONObject((HttpRequestBase)batchCreate, expectedCode, JSONArray.class);
        if (result.length() < batch.length()) {
            LOGGER.warn("Not all items were accepted {} out of {}", (Object)result.length(), (Object)batch.length());
        } else {
            LOGGER.debug("Accepted {}", (Object)result.length());
        }
        return result;
    }

    private List<NameValuePair> getDefaultParams(String containerNSID) {
        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add((NameValuePair)new BasicNameValuePair("d_rtbd", "json"));
        params.add((NameValuePair)new BasicNameValuePair("d_nsid", containerNSID));
        return params;
    }

    private List<NameValuePair> addTraitParams(List<String[]> moreParams, List<NameValuePair> params) {
        if (moreParams != null) {
            for (String[] param : moreParams) {
                params.add((NameValuePair)new BasicNameValuePair(param[0], param[1]));
            }
        }
        return params;
    }

    protected void bindCryptoSupport(CryptoSupport cryptoSupport) {
        this.cryptoSupport = cryptoSupport;
    }

    protected void unbindCryptoSupport(CryptoSupport cryptoSupport) {
        if (this.cryptoSupport == cryptoSupport) {
            this.cryptoSupport = null;
        }
    }

    protected void bindTraitsService(TraitsService traitsService) {
        this.traitsService = traitsService;
    }

    protected void unbindTraitsService(TraitsService traitsService) {
        if (this.traitsService == traitsService) {
            this.traitsService = null;
        }
    }

    protected void bindSegmentService(SegmentService segmentService) {
        this.segmentService = segmentService;
    }

    protected void unbindSegmentService(SegmentService segmentService) {
        if (this.segmentService == segmentService) {
            this.segmentService = null;
        }
    }

    protected void bindHttpClientBuilderFactory(HttpClientBuilderFactory httpClientBuilderFactory) {
        this.httpClientBuilderFactory = httpClientBuilderFactory;
    }

    protected void unbindHttpClientBuilderFactory(HttpClientBuilderFactory httpClientBuilderFactory) {
        if (this.httpClientBuilderFactory == httpClientBuilderFactory) {
            this.httpClientBuilderFactory = null;
        }
    }

    public static interface MethodFactory {
        public HttpPost getPostMethod(String var1);

        public HttpGet getGetMethod(String var1);
    }

}