RestApiAdapter.java 42.6 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.crypto.CryptoSupport
 *  com.day.cq.commons.Externalizer
 *  com.day.cq.wcm.webservicesupport.Configuration
 *  com.google.common.collect.ImmutableMap
 *  com.google.gson.Gson
 *  com.google.gson.GsonBuilder
 *  com.google.gson.JsonArray
 *  com.google.gson.JsonElement
 *  com.google.gson.JsonObject
 *  com.google.gson.JsonParser
 *  com.google.gson.JsonPrimitive
 *  com.google.gson.TypeAdapterFactory
 *  org.apache.commons.lang.StringUtils
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.commons.json.JSONArray
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.analytics.testandtarget.impl;

import com.adobe.granite.crypto.CryptoSupport;
import com.day.cq.analytics.testandtarget.Campaign;
import com.day.cq.analytics.testandtarget.ListOffersRequest;
import com.day.cq.analytics.testandtarget.ListSegmentsRequest;
import com.day.cq.analytics.testandtarget.PerformanceReport;
import com.day.cq.analytics.testandtarget.SaveOfferRequest;
import com.day.cq.analytics.testandtarget.Segment;
import com.day.cq.analytics.testandtarget.TestandtargetCallOptions;
import com.day.cq.analytics.testandtarget.TestandtargetException;
import com.day.cq.analytics.testandtarget.TestandtargetHttpClient;
import com.day.cq.analytics.testandtarget.TestandtargetHttpParameters;
import com.day.cq.analytics.testandtarget.ViewOfferRequest;
import com.day.cq.analytics.testandtarget.ViewOfferResponse;
import com.day.cq.analytics.testandtarget.impl.AbstractApiAdapter;
import com.day.cq.analytics.testandtarget.impl.ISO8601DateTypeAdapter;
import com.day.cq.analytics.testandtarget.impl.ListSegmentsRequestImpl;
import com.day.cq.analytics.testandtarget.impl.TestandTargetCampaignType;
import com.day.cq.analytics.testandtarget.impl.TestandtargetAudience;
import com.day.cq.analytics.testandtarget.impl.TestandtargetCampaign;
import com.day.cq.analytics.testandtarget.impl.TestandtargetHttpClientResponseException;
import com.day.cq.analytics.testandtarget.impl.TestandtargetHttpParametersImpl;
import com.day.cq.analytics.testandtarget.impl.TestandtargetJsonResponse;
import com.day.cq.analytics.testandtarget.impl.TestandtargetMbox;
import com.day.cq.analytics.testandtarget.impl.mapper.ListOffersRequestMapper;
import com.day.cq.analytics.testandtarget.impl.model.TargetAccountOptions;
import com.day.cq.analytics.testandtarget.impl.model.TestandtargetExperience;
import com.day.cq.analytics.testandtarget.impl.model.TntProfileAttribute;
import com.day.cq.analytics.testandtarget.impl.serializer.PerformanceReportSerializer;
import com.day.cq.analytics.testandtarget.impl.serializer.TntJsonSerializer;
import com.day.cq.analytics.testandtarget.util.CampaignType;
import com.day.cq.commons.Externalizer;
import com.day.cq.wcm.webservicesupport.Configuration;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.gson.TypeAdapterFactory;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RestApiAdapter
extends AbstractApiAdapter {
    private static final Logger LOG = LoggerFactory.getLogger(RestApiAdapter.class);
    private static final String CONTENT_TYPE_JSON = "application/json";
    private static final String MAC_METADATA_PRODUCT_NAME = "AEM";
    private static final String AUDIENCE_EDIT_URL = "/libs/cq/personalization/touch-ui/content/audiences.html";
    private final TestandtargetHttpClient client;
    private final CryptoSupport cryptoSupport;

    public RestApiAdapter(TestandtargetHttpClient client, CryptoSupport cryptoSupport) {
        this.client = client;
        this.cryptoSupport = cryptoSupport;
    }

    public long createOffer(Configuration configuration, SaveOfferRequest offerRequest) throws TestandtargetException {
        String data = new TntJsonSerializer<SaveOfferRequest>().serialize(offerRequest);
        TestandtargetHttpParametersImpl parameters = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration), data.getBytes(), "application/json");
        TestandtargetCallOptions options = new TestandtargetCallOptions().withParameters(parameters).withLocation(RestApiEndpoints.OFFERS.getEndpoint()).withApiVersion("1").withSolution(TestandtargetHttpClient.TestandtargetSolution.TARGET).withCallMethod(TestandtargetHttpClient.TestandtargetMethodType.POST);
        String response = this.client.executeRestCall(options);
        ViewOfferResponse offer = (ViewOfferResponse)new GsonBuilder().create().fromJson(response, ViewOfferResponse.class);
        return offer.getId();
    }

    public Collection<ViewOfferResponse> listOffers(Configuration configuration, ListOffersRequest request) throws TestandtargetException {
        Map<String, String> queryParams = this.getInitialParameters(configuration);
        queryParams.putAll(ListOffersRequestMapper.toParameterMap(request));
        TestandtargetCallOptions options = new TestandtargetCallOptions().withParameters(new TestandtargetHttpParametersImpl(queryParams)).withCallMethod(TestandtargetHttpClient.TestandtargetMethodType.GET).withLocation(RestApiEndpoints.OFFERS.getEndpoint()).withApiVersion(RestApiEndpoints.OFFERS.getApiVersion()).withSolution(TestandtargetHttpClient.TestandtargetSolution.TARGET);
        String response = this.client.executeRestGetCall(options);
        JsonObject object = new JsonParser().parse(response).getAsJsonObject();
        JsonArray offersArray = object.getAsJsonArray("offers");
        ViewOfferResponse[] result = null;
        result = offersArray == null ? new ViewOfferResponse[]{} : new TntJsonSerializer<ViewOfferResponse[]>().deserialize(object.getAsJsonArray("offers").toString(), ViewOfferResponse[].class);
        return Arrays.asList(result);
    }

    public ViewOfferResponse getOffer(Configuration configuration, ViewOfferRequest request) throws TestandtargetException {
        Map<String, String> queryParams = this.getInitialParameters(configuration);
        TestandtargetCallOptions options = new TestandtargetCallOptions().withCallMethod(TestandtargetHttpClient.TestandtargetMethodType.GET).withLocation(RestApiEndpoints.OFFERS.getEndpoint() + "/" + request.getId()).withApiVersion(RestApiEndpoints.OFFERS.getApiVersion()).withParameters(new TestandtargetHttpParametersImpl(queryParams));
        String result = this.client.executeRestCall(options);
        TestandtargetJsonResponse response = new TestandtargetJsonResponse(result);
        return response.getPayload(ViewOfferResponse.class);
    }

    public List<Segment> listSegments(Configuration configuration, ListSegmentsRequest request) throws TestandtargetException {
        Map<String, String> requestParameters = this.getInitialParameters(configuration);
        requestParameters.put("type", "reusable");
        if (request instanceof ListSegmentsRequestImpl) {
            ListSegmentsRequestImpl listSegmentsRequest = (ListSegmentsRequestImpl)request;
            requestParameters.putAll(listSegmentsRequest.getParameters());
        }
        ArrayList<Segment> segmentList = new ArrayList<Segment>();
        boolean hasMore = true;
        long offset = 0;
        long pageSize = 2000;
        requestParameters.put("limit", String.valueOf(pageSize));
        String lastRawResponse = null;
        while (hasMore) {
            requestParameters.put("offset", String.valueOf(offset));
            TestandtargetHttpParametersImpl testandtargetParameters = new TestandtargetHttpParametersImpl(requestParameters);
            TestandtargetCallOptions options = new TestandtargetCallOptions().withClientCode((String)configuration.getInherited("clientcode", (Object)"")).withLocation(RestApiEndpoints.SEGMENTS.getEndpoint()).withParameters(testandtargetParameters).withApiVersion(RestApiEndpoints.SEGMENTS.getApiVersion());
            String result = this.client.executeRestGetCall(options);
            if (StringUtils.isNotEmpty((String)lastRawResponse) && result.equalsIgnoreCase(lastRawResponse)) {
                LOG.debug("Detected 2 identical responses for two different segment list pages, assuming v6 API or older, breaking loop");
                hasMore = false;
                continue;
            }
            TestandtargetJsonResponse response = new TestandtargetJsonResponse(result);
            List<Object> segmentListChunk = Arrays.asList((Object[])response.getPayload(Segment[].class));
            segmentList.addAll(segmentListChunk);
            lastRawResponse = result;
            if (segmentListChunk.size() == 0) {
                hasMore = false;
                continue;
            }
            offset += pageSize;
        }
        return segmentList;
    }

    public Map<Integer, String> listCampaigns(Configuration configuration, Date modifiedSince, Date modifiedUntil, String name, String state) throws TestandtargetException {
        Map<String, String> queryParams = this.getInitialParameters(configuration);
        if (name != null) {
            queryParams.put("name", name);
        }
        if (state != null) {
            queryParams.put("state", state);
        }
        String response = this.client.executeRestGetCall(queryParams.get("client"), RestApiEndpoints.CAMPAIGNS.getEndpoint(), queryParams);
        JsonParser parser = new JsonParser();
        JsonObject element = parser.parse(response).getAsJsonObject();
        JsonArray campaigns = element.get("campaigns").getAsJsonArray();
        LinkedHashMap<Integer, String> campaignIdToName = new LinkedHashMap<Integer, String>(campaigns.size());
        for (JsonElement campaignElement : campaigns) {
            JsonObject campaign = campaignElement.getAsJsonObject();
            campaignIdToName.put(campaign.get("id").getAsInt(), campaign.get("name").getAsString());
        }
        return campaignIdToName;
    }

    public void saveCampaign(Configuration configuration, TestandtargetCampaign campaign) throws TestandtargetException {
        String data = new TntJsonSerializer<TestandtargetCampaign>().serialize(campaign);
        TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration), data.getBytes(StandardCharsets.UTF_8), "application/json");
        long campaignId = campaign.getId();
        TestandtargetHttpClient.TestandtargetMethodType methodType = TestandtargetHttpClient.TestandtargetMethodType.POST;
        TestandTargetCampaignType campaignType = campaign.getCampaignType();
        String endpoint = campaignType == TestandTargetCampaignType.LANDING_PAGE ? RestApiEndpoints.LANDING_PAGE_CAMPAIGNS.getEndpoint() : RestApiEndpoints.AB_CAMPAIGNS.getEndpoint();
        if (campaignId != 0) {
            methodType = TestandtargetHttpClient.TestandtargetMethodType.PUT;
            endpoint = endpoint + "/" + campaignId;
        }
        LOG.debug("Call parameters: {}, {}", (Object)methodType, (Object)endpoint);
        String result = this.client.executeRestCall(methodType, (String)configuration.getInherited("clientcode", (Object)""), endpoint, TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
        JsonParser parser = new JsonParser();
        JsonObject element = parser.parse(result).getAsJsonObject();
        LOG.debug("Parsing result...");
        if (element.has("id")) {
            String id = element.getAsJsonPrimitive("id").getAsString();
            LOG.debug("Campaign id is {}", (Object)id);
            campaign.setId(Long.valueOf(id));
        }
        if (element.has("experiences")) {
            LOG.debug("Extracting local ids for experiences...");
            HashMap<String, String> experienceLocalIds = new HashMap<String, String>();
            JsonArray expArray = element.getAsJsonArray("experiences");
            for (int idx = 0; idx < expArray.size(); ++idx) {
                JsonObject experience = expArray.get(idx).getAsJsonObject();
                experienceLocalIds.put(experience.get("name").getAsString(), experience.get("experienceLocalId").getAsString());
            }
            for (TestandtargetExperience experience : campaign.getExperiences()) {
                if (experience.getExperienceLocalId() != -1) {
                    LOG.debug("Experience {} already has an external id. Skipping.", (Object)experience.getInternalName());
                    continue;
                }
                String localId = (String)experienceLocalIds.get(experience.getName());
                if (StringUtils.isEmpty((String)localId)) {
                    LOG.warn("Local id for experience {} not found. Skipping.");
                    continue;
                }
                LOG.debug("Setting local id {} for experience {}", (Object)localId, (Object)experience.getInternalName());
                experience.setExperienceLocalId(Long.valueOf(localId));
            }
        }
    }

    @Override
    protected CryptoSupport getCryptoSupport() {
        return this.cryptoSupport;
    }

    public List<String> getMboxActivityCollisions(Configuration configuration, String mboxName, String mboxUrl) throws TestandtargetException {
        HashMap<String, String> query = new HashMap<String, String>();
        query.put("mbox", mboxName);
        query.put("pageUrl", mboxUrl);
        query.put("states", (String)new String[]{"approved"});
        String data = new Gson().toJson(query);
        TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration), data.getBytes(StandardCharsets.UTF_8), "application/json");
        String response = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.POST, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.MBOX_COLLISIONS.getEndpoint(), TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
        JsonParser parser = new JsonParser();
        JsonObject element = parser.parse(response).getAsJsonObject();
        JsonArray campaigns = element.get("campaigns").getAsJsonArray();
        ArrayList<String> collisions = new ArrayList<String>(campaigns.size());
        for (JsonElement campaignElement : campaigns) {
            collisions.add(campaignElement.getAsJsonObject().get("name").getAsString());
        }
        return collisions;
    }

    public PerformanceReport getCampaignPerformanceReportSummary(Configuration configuration, long campaignId, Map<String, String> otherApiParams) throws TestandtargetException {
        TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration));
        if (otherApiParams != null) {
            for (String otherParam : otherApiParams.keySet()) {
                params.getQueryParameters().put(otherParam, otherApiParams.get(otherParam));
            }
        }
        String response = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.GET, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.CAMPAIGNS.getEndpoint() + "/" + campaignId + "/report/summary", TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
        return new PerformanceReportSerializer().deserialize(response, (Class)PerformanceReport.class);
    }

    public List<TestandtargetAudience> getAudienceList(Configuration configuration) throws TestandtargetException {
        TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration));
        String response = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.GET, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.SEGMENTS.getEndpoint(), TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
        TestandtargetAudience[] audienceArray = (TestandtargetAudience[])new GsonBuilder().registerTypeAdapterFactory(ISO8601DateTypeAdapter.FACTORY).create().fromJson(response, TestandtargetAudience[].class);
        List<TestandtargetAudience> audienceList = Arrays.asList(audienceArray);
        return audienceList;
    }

    public void deleteCampaign(Configuration configuration, long campaignID) throws TestandtargetException {
        TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration));
        boolean retValue = false;
        try {
            String campaignDeleteRet = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.DELETE, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.AB_CAMPAIGNS.getEndpoint() + "/" + campaignID, TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
            JSONObject campDelResponseObj = new JSONObject(campaignDeleteRet);
            String deleteState = campDelResponseObj.getString("state");
            retValue = deleteState.equalsIgnoreCase("deleted");
        }
        catch (JSONException e) {
            retValue = false;
            LOG.debug("deleteCampaign raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), (Throwable)e);
        }
        if (!retValue) {
            LOG.debug("deleteCampaign raised exception: could not delete campaign");
            throw new TestandtargetException("Could not delete campaign");
        }
    }

    public String createVisualOffer(Configuration configuration, String offerName, String content) throws TestandtargetException {
        long retVal = -1;
        try {
            String contentInner;
            JSONObject jsonBody = new JSONObject();
            String offerNameObj = offerName;
            jsonBody.put("name", (Object)offerNameObj);
            String typeObj = "visual";
            jsonBody.put("type", (Object)typeObj);
            String contentObj = contentInner = content;
            jsonBody.put("content", (Object)contentObj);
            String bodyStr = jsonBody.toString();
            TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration), bodyStr.getBytes("UTF-8"), "application/json;charset=UTF-8");
            String response = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.POST, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.OFFERS.getEndpoint(), TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
            return response;
        }
        catch (UnsupportedEncodingException e) {
            LOG.debug("createVisualOffer raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), e);
        }
        catch (JSONException e) {
            LOG.debug("createVisualOffer raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), (Throwable)e);
        }
    }

    public String createSegment(Configuration configuration, String segmentName, String requestBody, boolean isReusable, String modifiedByUser) throws TestandtargetException {
        try {
            requestBody = this.addSegmentMACMetadata(configuration, requestBody, isReusable, modifiedByUser);
            TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration), requestBody.getBytes("UTF-8"), "application/json;charset=UTF-8");
            TestandtargetCallOptions options = new TestandtargetCallOptions().withCallMethod(TestandtargetHttpClient.TestandtargetMethodType.POST).withClientCode((String)configuration.getInherited("clientcode", (Object)"")).withLocation(RestApiEndpoints.SEGMENTS.getEndpoint()).withParameters(params).withApiVersion(RestApiEndpoints.SEGMENTS.getApiVersion());
            String response = this.client.executeRestCall(options);
            return response;
        }
        catch (Exception e) {
            LOG.debug("createSegment raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), e);
        }
    }

    public String updateSegment(Configuration configuration, long segmentId, String requestBody, boolean isReusable, String modifiedByUser) throws TestandtargetException {
        try {
            requestBody = this.addSegmentMACMetadata(configuration, requestBody, isReusable, modifiedByUser);
            TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration), requestBody.getBytes("UTF-8"), "application/json;charset=UTF-8");
            TestandtargetCallOptions options = new TestandtargetCallOptions().withCallMethod(TestandtargetHttpClient.TestandtargetMethodType.PUT).withClientCode((String)configuration.getInherited("clientcode", (Object)"")).withLocation(RestApiEndpoints.SEGMENTS.getEndpoint() + "/" + segmentId).withApiVersion(RestApiEndpoints.SEGMENTS.getApiVersion()).withParameters(params);
            String response = this.client.executeRestCall(options);
            return response;
        }
        catch (UnsupportedEncodingException e) {
            LOG.debug("updateSegment raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), e);
        }
    }

    private String addSegmentMACMetadata(Configuration configuration, String segmentJson, boolean isReusable, String modifiedByUser) {
        String localSegmentJson = segmentJson;
        try {
            ResourceResolver resolver = configuration.getContentResource().getResourceResolver();
            JSONObject jsonSegmentRequest = new JSONObject(segmentJson);
            jsonSegmentRequest.put("type", (Object)(isReusable ? "reusable" : "anonymous"));
            JSONObject macMetadata = new JSONObject();
            macMetadata.put("sourceProductName", (Object)"AEM");
            macMetadata.put("remoteModifiedBy", (Object)modifiedByUser);
            String audienceEditUrl = "/libs/cq/personalization/touch-ui/content/audiences.html";
            Externalizer externalizer = (Externalizer)resolver.adaptTo(Externalizer.class);
            if (externalizer != null) {
                audienceEditUrl = externalizer.externalLink(resolver, "local", audienceEditUrl);
            }
            macMetadata.put("editURL", (Object)audienceEditUrl);
            jsonSegmentRequest.put("marketingCloudMetadata", (Object)macMetadata);
            localSegmentJson = jsonSegmentRequest.toString();
        }
        catch (Exception e) {
            LOG.error("Can't add the marketing cloud metadata field to the segment!", (Throwable)e);
        }
        return localSegmentJson;
    }

    public String createCampaign(Configuration configuration, String campaignName, String requestBody) throws TestandtargetException {
        String response = "";
        try {
            TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration), requestBody.getBytes("UTF-8"), "application/json;charset=UTF-8");
            response = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.POST, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.AB_CAMPAIGNS.getEndpoint(), TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
            return response;
        }
        catch (UnsupportedEncodingException e) {
            LOG.debug("createVisualOffer raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), e);
        }
    }

    private long parseOfferID(JSONObject campDetailsObj) throws JSONException {
        JSONObject experience;
        JSONObject offerLocation;
        JSONArray offerLocationsArray;
        JSONArray experiencesArray = campDetailsObj.getJSONArray("experiences");
        long offerID = 0;
        if (experiencesArray.length() == 2 && (offerID = (long)(offerLocation = (offerLocationsArray = (experience = experiencesArray.getJSONObject(0)).getJSONArray("offerLocations")).getJSONObject(0)).getInt("offerId")) == 0) {
            experience = experiencesArray.getJSONObject(1);
            offerLocationsArray = experience.getJSONArray("offerLocations");
            offerLocation = offerLocationsArray.getJSONObject(0);
            offerID = offerLocation.getInt("offerId");
        }
        return offerID;
    }

    public void deleteOffer(Configuration configuration, long offerID) throws TestandtargetException {
        TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration));
        boolean retVal = false;
        try {
            String offerDeleteRetVal = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.DELETE, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.OFFERS.getEndpoint() + "/" + offerID, TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
            JSONObject offerDelResponse = new JSONObject(offerDeleteRetVal);
            long offerIdDeleted = offerDelResponse.getLong("id");
            retVal = offerIdDeleted == offerID;
        }
        catch (JSONException e) {
            LOG.debug("deleteOffer raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), (Throwable)e);
        }
        if (!retVal) {
            LOG.debug("deleteOffer raised exception: could not delete offer");
            throw new TestandtargetException("Could not delete offer");
        }
    }

    public void deleteSegment(Configuration configuration, long segmentID) throws TestandtargetException {
        TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration));
        boolean retVal = false;
        try {
            String segmentDeleteRetVal = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.DELETE, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.SEGMENTS.getEndpoint() + "/" + segmentID, TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
            JSONObject segmentDelResponse = new JSONObject(segmentDeleteRetVal);
            long segmentIdDeleted = segmentDelResponse.getLong("id");
            retVal = segmentIdDeleted == segmentID;
        }
        catch (JSONException e) {
            LOG.debug("deleteSegment raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), (Throwable)e);
        }
        if (!retVal) {
            LOG.debug("deleteSegment raised exception: could not delete segment");
            throw new TestandtargetException("Could not delete segment");
        }
    }

    public String updateCampaign(Configuration configuration, long campaignId, String requestBody) throws TestandtargetException {
        String response = "";
        try {
            TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration), requestBody.getBytes("UTF-8"), "application/json;charset=UTF-8");
            response = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.PUT, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.AB_CAMPAIGNS.getEndpoint() + "/" + campaignId, TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
            return response;
        }
        catch (UnsupportedEncodingException e) {
            LOG.debug("createVisualOffer raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), e);
        }
    }

    public String getCampaignDetails(Configuration configuration, long campaignId) throws TestandtargetException {
        String response = "";
        TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration));
        response = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.GET, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.AB_CAMPAIGNS.getEndpoint() + "/" + campaignId, TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
        return response;
    }

    public String getReportSummary(Configuration configuration, long campaignId) throws TestandtargetException {
        TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration));
        String response = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.GET, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.CAMPAIGNS.getEndpoint() + "/" + campaignId + "/report/summary", TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
        return response;
    }

    public String getReportSummaryWithDate(Configuration configuration, JSONObject reportDescription) throws TestandtargetException {
        String response = null;
        try {
            HashMap<String, String> queryParameter = new HashMap<String, String>();
            queryParameter.put("startDate", reportDescription.getString("fromDate") + "T00");
            queryParameter.put("endDate", reportDescription.getString("toDate") + "T23");
            queryParameter.put("email", (String)configuration.getInherited("email", (Object)""));
            queryParameter.put("password", this.getPassword(configuration));
            String slashCampaigns = "/campaigns/";
            String location = slashCampaigns + reportDescription.getInt("campaignID") + "/report/summary.json";
            TestandtargetHttpParametersImpl testandtargetParameters = new TestandtargetHttpParametersImpl(queryParameter);
            TestandtargetCallOptions options = new TestandtargetCallOptions().withClientCode((String)configuration.getInherited("clientcode", (Object)"")).withLocation(location).withParameters(testandtargetParameters).withApiVersion(RestApiEndpoints.CAMPAIGNS.getApiVersion());
            response = this.client.executeRestGetCall(options);
        }
        catch (TestandtargetException e) {
            LOG.debug("getReportSummaryWithDate raised exception: {}", (Object)e.toString());
            throw e;
        }
        catch (JSONException e) {
            LOG.debug("getReportSummaryWithDate raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), (Throwable)e);
        }
        catch (Exception e) {
            LOG.debug("getReportSummaryWithDate raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), e);
        }
        return response;
    }

    public boolean setCampaignState(Configuration configuration, String campaignState, String testAndTargetCampaignId, String thirdPartyCampaignId, CampaignType campaignType) throws TestandtargetException {
        ImmutableMap data = ImmutableMap.of((Object)"state", (Object)campaignState);
        String jsonData = new GsonBuilder().create().toJson((Object)data);
        RestApiEndpoints endpoint = RestApiEndpoints.fromCampaignType(campaignType);
        String idParam = StringUtils.isEmpty((String)testAndTargetCampaignId) ? "thirdPartyId/" + thirdPartyCampaignId : testAndTargetCampaignId;
        LOG.debug("Setting campaign state to {} for campaign {}", (Object)campaignState, (Object)idParam);
        TestandtargetCallOptions options = null;
        try {
            options = new TestandtargetCallOptions().withLocation(endpoint.getEndpoint() + "/" + idParam).withApiVersion(endpoint.getApiVersion()).withClientCode((String)configuration.getInherited("clientcode", (Object)"")).withParameters(new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration), jsonData.getBytes("UTF8"), "application/json")).withCallMethod(TestandtargetHttpClient.TestandtargetMethodType.PATCH);
        }
        catch (UnsupportedEncodingException e) {
            throw new TestandtargetException(e.getMessage(), e);
        }
        String response = this.client.executeRestCall(options);
        Map responseObject = (Map)new GsonBuilder().create().fromJson(response, Map.class);
        LOG.debug("State of campaign {} set to {}", responseObject.get("id"), responseObject.get("state"));
        return responseObject.get("id").equals(testAndTargetCampaignId);
    }

    public List<String> listMboxes(Configuration configuration) throws TestandtargetException {
        TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration));
        String response = this.client.executeRestCall(TestandtargetHttpClient.TestandtargetMethodType.GET, (String)configuration.getInherited("clientcode", (Object)""), RestApiEndpoints.MBOXES.getEndpoint(), TestandtargetHttpClient.TestandtargetSolution.TARGET, params);
        TestandtargetMbox[] mboxArray = (TestandtargetMbox[])new GsonBuilder().create().fromJson(response, TestandtargetMbox[].class);
        ArrayList<String> mboxNameList = new ArrayList<String>();
        for (TestandtargetMbox mboxObj : mboxArray) {
            mboxNameList.add(mboxObj.getName());
        }
        return mboxNameList;
    }

    public Campaign getCampaignByThirdPartyId(Configuration configuration, String thirdPartyId, CampaignType campaignType) throws TestandtargetException {
        LOG.debug("Retrieving campaign with thirdPartyId {}", (Object)thirdPartyId);
        RestApiEndpoints endpoint = RestApiEndpoints.fromCampaignType(campaignType);
        if (endpoint == null) {
            throw new TestandtargetException("Unknown campaign type " + (Object)((Object)campaignType));
        }
        String location = endpoint.getEndpoint() + "/thirdPartyId/" + thirdPartyId;
        return this.getCampaign(configuration, location, endpoint.getApiVersion());
    }

    public Campaign getCampaignById(Configuration configuration, long campaignId, CampaignType campaignType) throws TestandtargetException {
        LOG.debug("Retrieving campaign with id {}", (Object)campaignId);
        RestApiEndpoints endpoint = RestApiEndpoints.fromCampaignType(campaignType);
        if (endpoint == null) {
            throw new TestandtargetException("Unknown campaign type " + (Object)((Object)campaignType));
        }
        String location = endpoint.getEndpoint() + "/" + String.valueOf(campaignId);
        return this.getCampaign(configuration, location, endpoint.getApiVersion());
    }

    private Campaign getCampaign(Configuration configuration, String location, String apiVersion) throws TestandtargetException {
        TestandtargetCallOptions options = new TestandtargetCallOptions().withLocation(location).withApiVersion(apiVersion).withParameters(new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration)));
        try {
            String response = this.client.executeRestGetCall(options);
            JsonParser parser = new JsonParser();
            JsonObject obj = parser.parse(response).getAsJsonObject();
            if (obj.get("id") == null) {
                return null;
            }
            String campaignName = obj.get("name").getAsString();
            String id = obj.get("id").getAsString();
            return new Campaign(campaignName, id);
        }
        catch (TestandtargetHttpClientResponseException e) {
            if (e.getResponseCode() == 404) {
                return null;
            }
            throw e;
        }
    }

    public TargetAccountOptions getAccountOptions(Configuration configuration) throws TestandtargetException {
        Map<String, String> initialParameters = this.getInitialParameters(configuration);
        TestandtargetCallOptions callOptions = new TestandtargetCallOptions().withLocation(RestApiEndpoints.CLIENTS.getEndpoint() + "/" + initialParameters.get("client")).withApiVersion(RestApiEndpoints.CLIENTS.getApiVersion()).withCallMethod(TestandtargetHttpClient.TestandtargetMethodType.GET).withParameters(new TestandtargetHttpParametersImpl(initialParameters));
        String response = this.client.executeRestGetCall(callOptions);
        TargetAccountOptions options = (TargetAccountOptions)new GsonBuilder().create().fromJson(response, TargetAccountOptions.class);
        boolean a4tEnabled = false;
        try {
            callOptions.withLocation(callOptions.getLocation() + "/analytics").withApiVersion("1");
            response = this.client.executeRestCall(callOptions);
            JsonParser parser = new JsonParser();
            JsonObject obj = parser.parse(response).getAsJsonObject();
            if (obj.get("enableAnalytics") != null) {
                JsonElement a4tStatus = obj.get("enableAnalytics");
                a4tEnabled = a4tStatus.getAsBoolean();
            }
        }
        catch (Exception e) {
            LOG.debug("Account status check for Analytics and Targeting failed!", (Throwable)e);
        }
        if (a4tEnabled) {
            options.addProductOption("enableAnalytics");
        }
        return options;
    }

    public List<TntProfileAttribute> getProfileAttributes(Configuration configuration) throws TestandtargetException {
        try {
            TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration));
            TestandtargetCallOptions options = new TestandtargetCallOptions().withCallMethod(TestandtargetHttpClient.TestandtargetMethodType.GET).withClientCode((String)configuration.getInherited("clientcode", (Object)"")).withLocation(RestApiEndpoints.PROFILE_ATTRIBUTES.getEndpoint()).withApiVersion(RestApiEndpoints.PROFILE_ATTRIBUTES.getApiVersion()).withParameters(params);
            String response = this.client.executeRestCall(options);
            JsonParser parser = new JsonParser();
            JsonObject element = parser.parse(response).getAsJsonObject();
            JsonArray campaigns = element.get("attribute").getAsJsonArray();
            List<Object> profileAttributes = Arrays.asList((Object[])new GsonBuilder().create().fromJson((JsonElement)campaigns, TntProfileAttribute[].class));
            return profileAttributes;
        }
        catch (Exception e) {
            LOG.debug("getProfileAttributes raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), e);
        }
    }

    public List<TntProfileAttribute> getCustomProfileAttributes(Configuration configuration) throws TestandtargetException {
        try {
            TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(this.getInitialParameters(configuration));
            TestandtargetCallOptions options = new TestandtargetCallOptions().withCallMethod(TestandtargetHttpClient.TestandtargetMethodType.GET).withClientCode((String)configuration.getInherited("clientcode", (Object)"")).withLocation(RestApiEndpoints.MBOX_PROFILE_ATTRIBUTES.getEndpoint()).withApiVersion(RestApiEndpoints.MBOX_PROFILE_ATTRIBUTES.getApiVersion()).withParameters(params);
            String response = this.client.executeRestCall(options);
            List<Object> customProfileAttributes = Arrays.asList((Object[])new GsonBuilder().create().fromJson(response, String[].class));
            ArrayList<TntProfileAttribute> tntProfileAttributes = new ArrayList<TntProfileAttribute>();
            for (String customProfileAttribute : customProfileAttributes) {
                TntProfileAttribute tntProfileAttribute = new TntProfileAttribute();
                tntProfileAttribute.setName(customProfileAttribute);
                tntProfileAttribute.setType("PROFILE");
                tntProfileAttribute.setEnabled(true);
                tntProfileAttributes.add(tntProfileAttribute);
            }
            return tntProfileAttributes;
        }
        catch (Exception e) {
            LOG.debug("profileAttributes/mbox raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), e);
        }
    }

    public String searchMobileAttributes(Configuration configuration, String searchType, String paramName, String searchTerm) throws TestandtargetException {
        try {
            Map<String, String> parameters = this.getInitialParameters(configuration);
            parameters.put("searchType", searchType);
            parameters.put("term", searchTerm);
            parameters.put("paramName", paramName);
            TestandtargetHttpParametersImpl params = new TestandtargetHttpParametersImpl(parameters);
            TestandtargetCallOptions options = new TestandtargetCallOptions().withCallMethod(TestandtargetHttpClient.TestandtargetMethodType.GET).withClientCode((String)configuration.getInherited("clientcode", (Object)"")).withLocation(RestApiEndpoints.SEARCH_MOBILE.getEndpoint()).withApiVersion(RestApiEndpoints.SEARCH_MOBILE.getApiVersion()).withParameters(params);
            return this.client.executeRestCall(options);
        }
        catch (Exception e) {
            LOG.debug("search/mobile raised exception: {}", (Object)e.toString());
            throw new TestandtargetException(e.getMessage(), e);
        }
    }

    private static enum RestApiEndpoints {
        OFFERS("/offers", "2"),
        SEGMENTS("/segments", "7"),
        AB_CAMPAIGNS("/campaigns/ab", "1"),
        LANDING_PAGE_CAMPAIGNS("/campaigns/landing", "1"),
        CAMPAIGNS("/campaigns", "1"),
        MBOX_COLLISIONS("/campaigns/collisions", "1"),
        MBOXJS("/mboxjs", "1"),
        MBOXES("/mboxes", "1"),
        CLIENTS("/clients", "2"),
        PROFILE_ATTRIBUTES("/profileAttributes", "1"),
        MBOX_PROFILE_ATTRIBUTES("/profileAttributes/mbox", "2"),
        SEARCH_MOBILE("/search/mobile", "1");
        
        private String endpoint = null;
        private String apiVersion = null;

        private RestApiEndpoints(String endpoint, String apiVersion) {
            this.endpoint = endpoint;
            this.apiVersion = apiVersion;
        }

        private String getEndpoint() {
            return this.endpoint;
        }

        private String getApiVersion() {
            return this.apiVersion;
        }

        private static RestApiEndpoints fromCampaignType(CampaignType type) {
            if (type == CampaignType.AB) {
                return AB_CAMPAIGNS;
            }
            if (type == CampaignType.LANDING_PAGE) {
                return LANDING_PAGE_CAMPAIGNS;
            }
            return null;
        }
    }

}