DPSClientImpl.java 62.8 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.dps.client.producer.EntityListOptions
 *  com.adobe.dps.client.producer.EntityProducerDAO
 *  com.adobe.dps.client.producer.EntityType
 *  com.adobe.dps.client.producer.api.ProducerApi
 *  com.adobe.dps.client.producer.exceptions.EntityVersionConflictException
 *  com.adobe.dps.client.producer.utils.AccessToken
 *  com.adobe.dps.client.producer.utils.EntityUtils
 *  com.adobe.dps.client.producer.utils.Session
 *  com.adobe.dps.producer.entity.dto.ArticleEntity
 *  com.adobe.dps.producer.entity.dto.BannerEntity
 *  com.adobe.dps.producer.entity.dto.CollectionEntity
 *  com.adobe.dps.producer.entity.dto.Entity
 *  com.adobe.dps.producer.entity.dto.EntityLink
 *  com.adobe.dps.producer.entity.dto.EntityList
 *  com.adobe.dps.producer.entity.dto.EntityResponse
 *  com.adobe.dps.producer.entity.dto.LayoutEntity
 *  com.adobe.dps.producer.entity.dto.SharedContentEntity
 *  com.adobe.dps.producer.entity.dto.StatusList
 *  com.day.cq.contentsync.handler.util.RequestResponseFactory
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.webservicesupport.ConfigurationManager
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.servlet.http.HttpServletRequest
 *  javax.servlet.http.HttpServletResponse
 *  org.apache.commons.io.FileUtils
 *  org.apache.commons.io.FilenameUtils
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.sling.api.adapter.AdapterManager
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.commons.json.JSONArray
 *  org.apache.sling.commons.json.JSONObject
 *  org.apache.sling.commons.threads.ThreadPool
 *  org.apache.sling.engine.SlingRequestProcessor
 *  org.osgi.service.event.EventAdmin
 *  org.slf4j.Logger
 */
package com.adobe.cq.mobile.dps.impl.service;

import com.adobe.cq.mobile.dps.DPSArticle;
import com.adobe.cq.mobile.dps.DPSBanner;
import com.adobe.cq.mobile.dps.DPSCollection;
import com.adobe.cq.mobile.dps.DPSEntity;
import com.adobe.cq.mobile.dps.DPSException;
import com.adobe.cq.mobile.dps.DPSObject;
import com.adobe.cq.mobile.dps.DPSProject;
import com.adobe.cq.mobile.dps.impl.DPSClient;
import com.adobe.cq.mobile.dps.impl.DPSConnection;
import com.adobe.cq.mobile.dps.impl.DPSPageExporter;
import com.adobe.cq.mobile.dps.impl.export.ExportOptions;
import com.adobe.cq.mobile.dps.impl.service.AbstractDPSClient;
import com.adobe.cq.mobile.dps.impl.service.DPSConnectionAdapterFactory;
import com.adobe.cq.mobile.dps.impl.service.actions.GetEntity;
import com.adobe.cq.mobile.dps.impl.service.actions.GetReferences;
import com.adobe.cq.mobile.dps.impl.service.actions.GetStatus;
import com.adobe.cq.mobile.dps.impl.service.actions.LinkArticleToSharedResourceEntity;
import com.adobe.cq.mobile.dps.impl.ui.PerfTimer;
import com.adobe.cq.mobile.dps.impl.utils.DPSUtil;
import com.adobe.cq.mobile.dps.impl.utils.JSONUtil;
import com.adobe.cq.mobile.dps.impl.utils.MetadataJSONUtil;
import com.adobe.cq.mobile.dps.impl.utils.ModelConversionUtil;
import com.adobe.dps.client.producer.EntityListOptions;
import com.adobe.dps.client.producer.EntityProducerDAO;
import com.adobe.dps.client.producer.EntityType;
import com.adobe.dps.client.producer.api.ProducerApi;
import com.adobe.dps.client.producer.exceptions.EntityVersionConflictException;
import com.adobe.dps.client.producer.utils.AccessToken;
import com.adobe.dps.client.producer.utils.EntityUtils;
import com.adobe.dps.producer.entity.dto.ArticleEntity;
import com.adobe.dps.producer.entity.dto.BannerEntity;
import com.adobe.dps.producer.entity.dto.CollectionEntity;
import com.adobe.dps.producer.entity.dto.Entity;
import com.adobe.dps.producer.entity.dto.EntityLink;
import com.adobe.dps.producer.entity.dto.EntityList;
import com.adobe.dps.producer.entity.dto.EntityResponse;
import com.adobe.dps.producer.entity.dto.LayoutEntity;
import com.adobe.dps.producer.entity.dto.SharedContentEntity;
import com.adobe.dps.producer.entity.dto.StatusList;
import com.day.cq.contentsync.handler.util.RequestResponseFactory;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.webservicesupport.ConfigurationManager;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.adapter.AdapterManager;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.threads.ThreadPool;
import org.apache.sling.engine.SlingRequestProcessor;
import org.osgi.service.event.EventAdmin;
import org.slf4j.Logger;

public class DPSClientImpl
extends AbstractDPSClient
implements DPSClient {
    private static final int BUFFER = 16384;
    private DPSPageExporter exporterService = null;
    private ResourceResolver resourceResolver = null;
    private SlingRequestProcessor slingRequestProcessor = null;
    private RequestResponseFactory requestResponseFactory = null;

    public DPSClientImpl(ResourceResolver resourceResolver, Session userSession, DPSPageExporter exporterService, DPSConnectionAdapterFactory dpsConnectionAdapterFactory, ConfigurationManager configurationManagerService, EventAdmin eventAdminService, AdapterManager adapterManager, SlingRequestProcessor slingRequestProcessor, RequestResponseFactory requestResponseFactory, ThreadPool threadPool) {
        super(userSession, dpsConnectionAdapterFactory, configurationManagerService, eventAdminService, adapterManager, threadPool);
        this.resourceResolver = resourceResolver;
        this.slingRequestProcessor = slingRequestProcessor;
        this.requestResponseFactory = requestResponseFactory;
        this.exporterService = exporterService;
    }

    @Override
    public boolean articleExistsInDPS(DPSProject project, String name) throws DPSException {
        return this.doesEntityExistInDPS(project, name, EntityType.ARTICLE);
    }

    public void uploadArticle(DPSArticle dpsArticle, boolean createIfMissing, boolean includeContent) throws DPSException {
        try {
            this.LOGGER.info("Uploading article {}:{}", (Object)dpsArticle.getName(), (Object)dpsArticle.getPath());
            this.LOGGER.debug("Uploading article params {}", (Object)("createIfMissing=" + createIfMissing + ", includeContent=" + includeContent));
            if (dpsArticle.getId() == null && !createIfMissing) {
                throw new DPSException("Article does not exist in Experience Manager Mobile.");
            }
            this.uploadArticleToDPSImpl(dpsArticle, createIfMissing, includeContent);
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            DPSException dpsEx = new DPSException("Failed to upload: " + dpsArticle.getPath(), ex);
            throw dpsEx;
        }
    }

    @Override
    public void uploadHTMLResources(DPSProject dpsProject) throws DPSException {
        try {
            this.LOGGER.info("Uploading shared HTMLResources {}:{}", (Object)dpsProject.getName(), (Object)dpsProject.getPath());
            this.uploadHTMLResourcesToDPSImpl(dpsProject);
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            DPSException dpsEx = new DPSException("Failed to upload shared HTMLResources for: " + dpsProject.getPath(), ex);
            throw dpsEx;
        }
    }

    @Override
    public void preview(DPSProject dpsProject) throws DPSException {
        try {
            this.LOGGER.info("Preview project {}:{}", (Object)dpsProject.getName(), (Object)dpsProject.getPath());
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsProject, DPSConnection.class);
            ProducerApi producerAPI = dpsConnection.getProducerAPI(this.getAndAssertProjectId(dpsProject));
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            producerAPI.preview(session);
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            DPSException dpsEx = new DPSException("Failed to initiate preview for: " + dpsProject.getPath(), ex);
            throw dpsEx;
        }
    }

    @Override
    public String publishEntity(DPSEntity dpsEntity) throws DPSException {
        String publishId;
        publishId = null;
        try {
            EntityResponse entity;
            this.LOGGER.info("Publish entity {}:{}", (Object)dpsEntity.getName(), (Object)dpsEntity.getPath());
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsEntity, DPSConnection.class);
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            AccessToken accessToken = dpsConnection.getAccessToken();
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            String publicationId = this.getAndAssertProjectId(dpsEntity);
            String entityName = dpsEntity.getName();
            if (dpsEntity.getId() != null) {
                String entityURI = DPSUtil.getEntityURI(dpsEntity);
                entity = (EntityResponse)entityAccess.readEntity(accessToken, entityURI, session);
                if (entity == null) {
                    throw new DPSException("Entity not found in Experience Manager Mobile for " + entityName + " at uri " + entityURI);
                }
            } else {
                throw new DPSException("Experience Manager Mobile id not set. AEM is not managing a remote instance for " + dpsEntity.getPath());
            }
            ArrayList<String> entitiesList = new ArrayList<String>();
            entitiesList.add(EntityUtils.getEntityUrl((EntityResponse)entity));
            publishId = entityAccess.publishEntities(accessToken, publicationId, entitiesList, session.generateNewRequestId());
            this.LOGGER.debug("Publish job started {0}:{1}", (Object)publishId, (Object)dpsEntity.getPath());
            Node entityContentNode = ((Node)dpsEntity.adaptTo(Node.class)).getNode("jcr:content");
            entityContentNode.setProperty("dps-lastPublished", Calendar.getInstance());
            entityContentNode.setProperty("dps-lastPublishedBy", this.userSession.getUserID());
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            DPSException dpsEx = new DPSException("Failed to initiate publish of : " + dpsEntity.getPath(), ex);
            throw dpsEx;
        }
        return publishId;
    }

    @Override
    public void publish(DPSProject dpsProject, List<DPSEntity> entities) throws DPSException {
        try {
            this.LOGGER.info("Publish " + entities.size() + " entities");
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsProject, DPSConnection.class);
            ProducerApi producerAPI = dpsConnection.getProducerAPI(this.getAndAssertProjectId(dpsProject));
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            ArrayList<EntityLink> entityLinks = new ArrayList<EntityLink>();
            for (DPSEntity dpsEntity : entities) {
                String entityName = dpsEntity.getEntityName();
                if (dpsEntity.getId() != null) {
                    String entityURI = DPSUtil.getEntityURI(dpsEntity);
                    Entity entity = producerAPI.getEntity(entityName, DPSUtil.getEntityType(dpsEntity), session);
                    if (entity == null) {
                        throw new DPSException("Entity not found in Experience Manager Mobile for " + entityName + " at uri " + entityURI);
                    }
                    URI href = new URI(dpsEntity.getId());
                    EntityLink entityLink = new EntityLink();
                    entityLink.setHref(href);
                    entityLinks.add(entityLink);
                    Node entityContentNode = ((Node)dpsEntity.adaptTo(Node.class)).getNode("jcr:content");
                    entityContentNode.setProperty("dps-lastPublished", Calendar.getInstance());
                    entityContentNode.setProperty("dps-lastPublishedBy", this.userSession.getUserID());
                    continue;
                }
                throw new DPSException("Experience Manager Mobile id not set. AEM is not managing a remote instance for " + dpsEntity.getPath());
            }
            producerAPI.publishEntities(entityLinks, session);
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            DPSException dpsEx = new DPSException("Failed to initiate batch publish for : " + dpsProject.getPath(), ex);
            throw dpsEx;
        }
    }

    @Override
    public void unpublish(DPSProject dpsProject, List<DPSEntity> entities) throws DPSException {
        try {
            this.LOGGER.info("UnPublish " + entities.size() + " entities");
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsProject, DPSConnection.class);
            ProducerApi producerAPI = dpsConnection.getProducerAPI(this.getAndAssertProjectId(dpsProject));
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            ArrayList<EntityLink> entityLinks = new ArrayList<EntityLink>();
            for (DPSEntity dpsEntity : entities) {
                String entityName = dpsEntity.getEntityName();
                if (dpsEntity.getId() != null) {
                    String entityURI = DPSUtil.getEntityURI(dpsEntity);
                    Entity entity = producerAPI.getEntity(entityName, DPSUtil.getEntityType(dpsEntity), session);
                    if (entity == null) {
                        throw new DPSException("Entity not found in Experience Manager Mobile for " + entityName + " at uri " + entityURI);
                    }
                    entityLinks.add(new EntityLink());
                    URI href = new URI(dpsEntity.getId());
                    EntityLink entityLink = new EntityLink();
                    entityLink.setHref(href);
                    entityLinks.add(entityLink);
                    Node entityContentNode = ((Node)dpsEntity.adaptTo(Node.class)).getNode("jcr:content");
                    entityContentNode.setProperty("dps-lastPublished", Calendar.getInstance());
                    entityContentNode.setProperty("dps-lastPublishedBy", this.userSession.getUserID());
                    continue;
                }
                throw new DPSException("Experience Manager Mobile id not set. AEM is not managing a remote instance for " + dpsEntity.getPath());
            }
            producerAPI.unpublishEntities(entityLinks, session);
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            DPSException dpsEx = new DPSException("Failed to initiate batch unpublish for : " + dpsProject.getPath(), ex);
            throw dpsEx;
        }
    }

    @Override
    public String unpublishEntity(DPSEntity dpsEntity) throws DPSException {
        String publishId;
        publishId = null;
        try {
            this.LOGGER.info("Unpublish {}:{}", (Object)dpsEntity.getName(), (Object)dpsEntity.getPath());
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsEntity, DPSConnection.class);
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            AccessToken accessToken = dpsConnection.getAccessToken();
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            String publicationId = this.getAndAssertProjectId(dpsEntity);
            String entityName = dpsEntity.getName();
            if (dpsEntity.getId() != null) {
                String entityURI = DPSUtil.getEntityURI(dpsEntity);
                EntityResponse entity = (EntityResponse)entityAccess.readEntity(accessToken, entityURI, session);
                if (entity == null) {
                    throw new DPSException("Entity not found in Experience Manager Mobile for " + entityName + " at uri " + entityURI);
                }
                ArrayList<String> entitiesList = new ArrayList<String>();
                entitiesList.add(EntityUtils.getEntityUrl((EntityResponse)entity));
                publishId = entityAccess.unpublishEntities(accessToken, publicationId, entitiesList, session.generateNewRequestId());
                this.LOGGER.debug("Unpublish job started {0}:{1}", (Object)publishId, (Object)dpsEntity.getPath());
            } else {
                this.LOGGER.warn("Experience Manager Mobile id not set. AEM is not managing a remote instance for " + dpsEntity.getPath());
            }
            Node entityContentNode = ((Node)dpsEntity.adaptTo(Node.class)).getNode("jcr:content");
            if (entityContentNode.hasProperty("dps-lastPublished")) {
                entityContentNode.getProperty("dps-lastPublished").setValue((Calendar)null);
            }
            if (entityContentNode.hasProperty("dps-lastPublishedBy")) {
                entityContentNode.getProperty("dps-lastPublishedBy").setValue((String)null);
            }
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            DPSException dpsEx = new DPSException("Failed to initiate unpublish of : " + dpsEntity.getPath(), ex);
            throw dpsEx;
        }
        return publishId;
    }

    @Override
    public void uploadEntity(DPSEntity dpsEntity, boolean createIfMissing, boolean includeContent) throws DPSException {
        if (dpsEntity instanceof DPSArticle) {
            this.uploadArticle((DPSArticle)dpsEntity, createIfMissing, includeContent);
        } else if (dpsEntity instanceof DPSCollection) {
            this.uploadCollection((DPSCollection)dpsEntity, createIfMissing, includeContent);
        } else if (dpsEntity instanceof DPSBanner) {
            this.uploadBanner((DPSBanner)dpsEntity, createIfMissing, includeContent);
        } else {
            throw new DPSException("Experience Manager Mobile Upload not supported for " + dpsEntity.getPath());
        }
    }

    public void uploadCollection(DPSCollection dpsCollection, boolean createIfMissing, boolean includeContent) throws DPSException {
        try {
            this.LOGGER.info("Uploading collection {}:{}", (Object)dpsCollection.getName(), (Object)dpsCollection.getPath());
            if (dpsCollection.getId() == null && !createIfMissing) {
                throw new DPSException("Collection does not exist in Experience Manager Mobile.");
            }
            this.uploadCollectionToDPSImpl(dpsCollection, createIfMissing, includeContent);
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            DPSException dpsEx = new DPSException("Failed to upload: " + dpsCollection.getPath(), ex);
            throw dpsEx;
        }
    }

    @Override
    public void deleteEntity(DPSEntity dpsEntity, boolean deleteLocal) throws DPSException {
        String warningMessage;
        if (dpsEntity == null) {
            this.LOGGER.debug("dpsEntity was null in deleteEntity");
            return;
        }
        warningMessage = null;
        try {
            this.LOGGER.info("Deleting {}:{}", (Object)dpsEntity.getName(), (Object)dpsEntity.getPath());
            this.LOGGER.debug("Deleting params {}", (Object)("deleteLocal=" + deleteLocal));
            if (dpsEntity.getId() != null) {
                DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsEntity, DPSConnection.class);
                EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
                AccessToken accessToken = dpsConnection.getAccessToken();
                com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
                String entityURI = DPSUtil.getEntityURI(dpsEntity);
                Entity entityInDPS = entityAccess.readEntity(accessToken, entityURI, session);
                if (entityInDPS != null) {
                    entityAccess.deleteEntity(accessToken, EntityUtils.getEntityUrlFromEntity((Entity)entityInDPS), session.generateNewRequestId());
                } else {
                    warningMessage = "Warning: Entity was not found on Experience Manager Mobile.";
                    this.LOGGER.warn("Entity could not be deleted. Entity was not found in DPS and may already have been deleted for " + dpsEntity.getName() + " at uri " + entityURI);
                }
                Node node = (Node)dpsEntity.adaptTo(Node.class);
                this.cleanIds(node);
            } else {
                this.LOGGER.warn("Entity id not set. AEM is not managing, and will not delete, a remote instance for " + dpsEntity.getPath());
            }
            if (deleteLocal) {
                ((Node)dpsEntity.adaptTo(Node.class)).remove();
            }
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            DPSException dpsEx = new DPSException("Failed to delete remote entity : " + dpsEntity.getPath(), ex);
            throw dpsEx;
        }
        if (StringUtils.isNotBlank((CharSequence)warningMessage)) {
            throw new DPSException(warningMessage);
        }
    }

    @Override
    public boolean bannerExistsInDPS(DPSProject project, String name) throws DPSException {
        return this.doesEntityExistInDPS(project, name, EntityType.BANNER);
    }

    public void uploadBanner(DPSBanner dpsBanner, boolean createIfMissing, boolean includeContent) throws DPSException {
        try {
            this.LOGGER.info("Uploading banner {}:{}", (Object)dpsBanner.getName(), (Object)dpsBanner.getPath());
            this.LOGGER.debug("Uploading banner params {}", (Object)("createIfMissing=" + createIfMissing + ", includeContent=" + includeContent));
            if (dpsBanner.getId() == null && !createIfMissing) {
                throw new DPSException("Banner does not exist in Experience Manager Mobile.");
            }
            this.uploadBannerToDPSImpl(dpsBanner, createIfMissing, includeContent);
        }
        catch (DPSException dpsEx) {
            throw dpsEx;
        }
        catch (Exception ex) {
            DPSException dpsEx = new DPSException("Failed to upload: " + dpsBanner.getPath(), ex);
            throw dpsEx;
        }
    }

    @Override
    public void addContentToCollection(DPSCollection dpsCollection, DPSEntity entity) throws DPSException {
        this.LOGGER.info("Add {} to collection {}", (Object)entity.getPath(), (Object)dpsCollection.getPath());
        if (entity instanceof DPSCollection && entity.getName().equals(dpsCollection.getName())) {
            throw new DPSException("A Collection cannot have itself as content.");
        }
        if (entity.getId() == null) {
            throw new DPSException("Item has not been uploaded yet " + entity.getName(), new Throwable("Item has not been uploaded yet " + entity.getName()));
        }
        if (dpsCollection != null && (dpsCollection.getLastDPSUpload() != null || dpsCollection.isImported())) {
            try {
                ArrayList<String> entityURIs = new ArrayList<String>();
                entityURIs.add(entity.getId());
                this.updateCollectionContents(dpsCollection, entityURIs, true);
            }
            catch (Exception ex) {
                if (ex instanceof DPSException) {
                    throw (DPSException)ex;
                }
                throw new DPSException("Failed to add content to Experience Manager Mobile collection " + dpsCollection.getPath(), ex);
            }
        } else {
            throw new DPSException("Collection not found. Collection has not been uploaded or imported yet " + (dpsCollection != null ? dpsCollection.getName() : ""));
        }
    }

    @Override
    public void updateCollectionContents(DPSCollection dpsCollection, List<String> entityURIs, boolean appendRatherThanReplace) throws DPSException {
        try {
            CollectionEntity collection;
            String entityURL;
            this.LOGGER.info("Update collection contents {}", (Object)dpsCollection.getPath());
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsCollection, DPSConnection.class);
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            AccessToken accessToken = dpsConnection.getAccessToken();
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            ArrayList<EntityLink> entityLinks = new ArrayList<EntityLink>();
            if (entityURIs != null) {
                for (String entityURL2 : entityURIs) {
                    String versionLessEntityURL = MetadataJSONUtil.stripVersionFromURI(entityURL2);
                    URI href = new URI(versionLessEntityURL);
                    EntityLink entityLink = new EntityLink();
                    entityLink.setHref(href);
                    entityLinks.add(entityLink);
                }
            }
            if ((collection = (CollectionEntity)entityAccess.readEntity(accessToken, entityURL = DPSUtil.getEntityURI(dpsCollection), session.generateNewRequestId())) == null) {
                throw new DPSException("Collection " + dpsCollection.getName() + "  not found in Experience Manager Mobile.");
            }
            this.updateDPSCollectionContentImpl(entityAccess, accessToken, session, entityLinks, collection, appendRatherThanReplace);
        }
        catch (Exception ex) {
            if (ex instanceof DPSException) {
                throw (DPSException)ex;
            }
            throw new DPSException("Failed to add content to Experience Manager Mobile collection " + dpsCollection.getPath(), ex);
        }
    }

    private void updateDPSCollectionContentImpl(EntityProducerDAO entityAccess, AccessToken accessToken, com.adobe.dps.client.producer.utils.Session session, List<EntityLink> entityLinksToAdd, CollectionEntity collection, boolean appendRatherThanReplace) throws DPSException {
        try {
            EntityList contentElements = entityAccess.getContentElements(accessToken, EntityUtils.getEntityUrl((EntityResponse)collection), session.generateNewRequestId());
            if (!appendRatherThanReplace) {
                contentElements.clear();
            }
            for (EntityLink entityLinkToAdd : entityLinksToAdd) {
                if (appendRatherThanReplace) {
                    Set<String> existingContents = this.buildSet(contentElements);
                    if (!existingContents.contains(MetadataJSONUtil.stripVersionFromURI(entityLinkToAdd.getHref().toString()))) {
                        contentElements.add(0, (Object)entityLinkToAdd);
                        continue;
                    }
                    this.LOGGER.debug("Skipping adding entity ot collection, it already is part of collection: " + (Object)entityLinkToAdd);
                    continue;
                }
                contentElements.add((Object)entityLinkToAdd);
            }
            String collectionContentElementsUrl = EntityUtils.getEntityUrl((EntityResponse)collection);
            collection = (CollectionEntity)entityAccess.updateContentElements(accessToken, collectionContentElementsUrl, (List)contentElements, session.generateNewRequestId());
        }
        catch (Exception ex) {
            String action = appendRatherThanReplace ? "append" : "set";
            throw new DPSException("Failed to " + action + " collection contents " + collection.getEntityName(), ex);
        }
    }

    private Set<String> buildSet(EntityList contentElements) {
        HashSet<String> contentSet = new HashSet<String>();
        for (int i = 0; i < contentElements.size(); ++i) {
            EntityLink entityLink = (EntityLink)contentElements.get(i);
            String versionLessEntityURL = MetadataJSONUtil.stripVersionFromURI(entityLink.getHref().toString());
            contentSet.add(versionLessEntityURL);
        }
        return contentSet;
    }

    private void uploadArticleToDPSImpl(DPSArticle dpsArticle, boolean createIfMissing, boolean includeContent) throws DPSException {
        File articleFolioFile = null;
        File articleFolioRootFolder = null;
        File thumbnail = null;
        File socialImageFile = null;
        try {
            String socialImagePath;
            String publicationId = this.getAndAssertProjectId(dpsArticle);
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsArticle, DPSConnection.class);
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            ProducerApi producerAPI = dpsConnection.getProducerAPI(publicationId);
            AccessToken accessToken = dpsConnection.getAccessToken();
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            String entityName = dpsArticle.getName();
            ArticleEntity article = null;
            if (dpsArticle.getId() == null && createIfMissing) {
                this.LOGGER.info("Creating article {} for project {}", (Object)entityName, (Object)publicationId);
                try {
                    article = producerAPI.createArticleEntity(entityName, dpsArticle.getTitle(), session);
                }
                catch (EntityVersionConflictException ex) {
                    throw new DPSException("Article " + entityName + " already exists in AEM Mobile On Demand.", (Throwable)ex);
                }
                if (dpsArticle.getProject().getLastHTMLResourceDPSUpload() != null) {
                    String sharedContentURI = this.getSharedContentURI(publicationId);
                    SharedContentEntity sharedContentEntity = (SharedContentEntity)entityAccess.readEntity(accessToken, sharedContentURI, session);
                    Future future = this.threadPool.submit((Callable)new LinkArticleToSharedResourceEntity(entityAccess, producerAPI, accessToken, session, EntityUtils.getEntityUrl((EntityResponse)article), sharedContentEntity));
                    article = (ArticleEntity)future.get();
                }
                this.updateEntityNodesMetaData(dpsArticle, EntityUtils.getEntityUrl((EntityResponse)article), true);
            } else {
                String articleURI = DPSUtil.getEntityURI(dpsArticle);
                article = (ArticleEntity)entityAccess.readEntity(accessToken, articleURI, session.generateNewRequestId());
                if (article == null) {
                    throw new DPSException("Article not found in Experience Manager Mobile for entity " + entityName + " at uri " + articleURI);
                }
            }
            if (includeContent && !dpsArticle.isImported()) {
                articleFolioFile = this.getArticleFolio(dpsArticle);
                articleFolioRootFolder = this.unzip(articleFolioFile);
                article = producerAPI.uploadArticleContent(article, articleFolioRootFolder, "article", session);
            }
            ModelConversionUtil.updateEntity(article, dpsArticle);
            article = producerAPI.updateArticleEntity(article, session);
            String thumbnailURI = dpsArticle.getImagePath();
            if (thumbnailURI != null) {
                thumbnail = this.downloadImage(this.resourceResolver, this.slingRequestProcessor, this.requestResponseFactory, thumbnailURI, "toc", this.getExtension(thumbnailURI));
            }
            if ((socialImagePath = dpsArticle.getSocialImagePath()) != null) {
                socialImageFile = this.downloadImage(this.resourceResolver, this.slingRequestProcessor, this.requestResponseFactory, socialImagePath, "social", this.getExtension(socialImagePath));
            }
            article = producerAPI.uploadArticleAll(article, null, thumbnail, "images/thumbnail", null, null, socialImageFile, "images/social", session);
            this.updateEntityNodesMetaData(dpsArticle, EntityUtils.getEntityUrl((EntityResponse)article), true);
            this.LOGGER.debug(" Upload to Experience Manager Mobile SUCCESSFUL");
        }
        catch (Throwable ex) {
            this.LOGGER.error("Upload to Experience Manager Mobile FAILED", ex);
            throw new DPSException("Failed to upload article: " + dpsArticle.getPath(), ex);
        }
        finally {
            try {
                if (this.userSession.hasPendingChanges()) {
                    this.userSession.save();
                }
            }
            catch (RepositoryException repEx) {
                this.LOGGER.error("Could not save user session while uploading article: " + dpsArticle.getName());
            }
            if (articleFolioFile != null && !articleFolioFile.delete()) {
                this.LOGGER.error("Failed to delete file " + articleFolioFile);
            }
            if (articleFolioRootFolder != null) {
                try {
                    FileUtils.deleteDirectory((File)articleFolioRootFolder);
                }
                catch (IOException ex) {
                    this.LOGGER.error("Failed to delete folder " + articleFolioRootFolder, (Throwable)ex);
                }
            }
            if (thumbnail != null && !thumbnail.delete()) {
                this.LOGGER.error("Failed to delete file " + thumbnail);
            }
            if (socialImageFile != null && !socialImageFile.delete()) {
                this.LOGGER.error("Failed to delete file " + socialImageFile);
            }
        }
    }

    private void uploadBannerToDPSImpl(DPSBanner dpsBanner, boolean createIfMissing, boolean includeContentNOTUSEDYET) throws DPSException {
        File thumbnail = null;
        try {
            String publicationId = this.getAndAssertProjectId(dpsBanner);
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsBanner, DPSConnection.class);
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            ProducerApi producerAPI = dpsConnection.getProducerAPI(publicationId);
            AccessToken accessToken = dpsConnection.getAccessToken();
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            String entityName = dpsBanner.getName();
            BannerEntity entity = null;
            String thumbnailURI = dpsBanner.getImagePath();
            if (thumbnailURI != null) {
                thumbnail = this.downloadImage(this.resourceResolver, this.slingRequestProcessor, this.requestResponseFactory, thumbnailURI, "toc", this.getExtension(thumbnailURI));
            }
            if (dpsBanner.getId() == null && createIfMissing) {
                this.LOGGER.info("Creating banner {} for project {}", (Object)entityName, (Object)publicationId);
                try {
                    entity = producerAPI.createBannerEntity(entityName, dpsBanner.getTitle(), thumbnail, session);
                }
                catch (EntityVersionConflictException ex) {
                    throw new DPSException("Banner " + entityName + " already exists in AEM Mobile On Demand.", (Throwable)ex);
                }
                this.updateEntityNodesMetaData(dpsBanner, EntityUtils.getEntityUrl((EntityResponse)entity), true);
                ModelConversionUtil.updateEntity(entity, dpsBanner);
                entity = producerAPI.updateBannerEntity(entity, session);
            } else {
                String entityURI = DPSUtil.getEntityURI(dpsBanner);
                entity = (BannerEntity)entityAccess.readEntity(accessToken, entityURI, session.generateNewRequestId());
                if (entity == null) {
                    throw new DPSException("Banner not found in Experience Manager Mobile for entity " + entityName + " at uri " + entityURI);
                }
                ModelConversionUtil.updateEntity(entity, dpsBanner);
                entity = producerAPI.updateBannerEntity(entity, session);
                entity = producerAPI.uploadBannerThumbnail(entity, thumbnail, session);
            }
            this.updateEntityNodesMetaData(dpsBanner, EntityUtils.getEntityUrl((EntityResponse)entity), true);
            this.userSession.save();
            this.LOGGER.debug(" Upload to Experience Manager Mobile SUCCESSFUL");
        }
        catch (Throwable ex) {
            this.LOGGER.error("Upload to Experience Manager Mobile FAILED", ex);
            throw new DPSException("Failed to upload banner: " + dpsBanner.getPath(), ex);
        }
        finally {
            try {
                if (this.userSession.hasPendingChanges()) {
                    this.userSession.save();
                }
            }
            catch (RepositoryException repEx) {
                this.LOGGER.error("Could not save user session while uploading banner: " + dpsBanner.getName());
            }
            if (thumbnail != null && !thumbnail.delete()) {
                this.LOGGER.error("Failed to delete file " + thumbnail);
            }
        }
    }

    private void updateEntityNodesMetaData(DPSEntity dpsEntity, String id, boolean autosave) throws RepositoryException {
        Node entityContentNode = ((Node)dpsEntity.adaptTo(Node.class)).getNode("jcr:content");
        entityContentNode.setProperty("dps-lastUploaded", Calendar.getInstance());
        entityContentNode.setProperty("dps-lastUploadedBy", this.userSession.getUserID());
        entityContentNode.setProperty("dps-id", id);
        if (autosave) {
            this.userSession.save();
        }
    }

    private void uploadHTMLResourcesToDPSImpl(DPSProject dpsProject) throws DPSException {
        File htmlResourcesZipFile = null;
        File htmlResourcesContentRootFolder = null;
        try {
            String projectId = this.getAndAssertProjectId(dpsProject);
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsProject, DPSConnection.class);
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            AccessToken accessToken = dpsConnection.getAccessToken();
            ProducerApi producerAPI = dpsConnection.getProducerAPI(projectId);
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            htmlResourcesZipFile = this.getSharedHTMLResources(dpsProject);
            htmlResourcesContentRootFolder = this.unzip(htmlResourcesZipFile);
            SharedContentEntity sharedContentEntity = null;
            try {
                sharedContentEntity = (SharedContentEntity)entityAccess.readEntity(accessToken, this.getSharedContentURI(projectId), session);
            }
            catch (Exception ex) {
                // empty catch block
            }
            sharedContentEntity = sharedContentEntity == null ? producerAPI.createSharedContentEntity("SHARED_HTML_RESOURCES", htmlResourcesContentRootFolder, session) : producerAPI.uploadSharedContentEntityContent(sharedContentEntity, htmlResourcesContentRootFolder, session);
            Node projectContentNode = ((Node)dpsProject.adaptTo(Node.class)).getNode("jcr:content");
            projectContentNode.setProperty("dps-sharedHTMLResources-lastUploaded", Calendar.getInstance());
            projectContentNode.setProperty("dps-sharedHTMLResources-lastUploadedBy", this.userSession.getUserID());
            this.linkArticlesToHTMLResources(dpsConnection, dpsProject, sharedContentEntity);
            this.LOGGER.debug(" Upload to Experience Manager Mobile SUCCESSFUL");
        }
        catch (Throwable ex) {
            this.LOGGER.error("Upload to Experience Manager Mobile FAILED", ex);
            throw new DPSException("Failed to upload shared HTMLResources for: " + dpsProject.getPath(), ex);
        }
        finally {
            if (htmlResourcesZipFile != null && !htmlResourcesZipFile.delete()) {
                this.LOGGER.error("Failed to delete file " + htmlResourcesZipFile);
            }
            if (htmlResourcesContentRootFolder != null) {
                try {
                    FileUtils.deleteDirectory((File)htmlResourcesContentRootFolder);
                }
                catch (IOException ex) {
                    this.LOGGER.error("Failed to delete folder " + htmlResourcesContentRootFolder, (Throwable)ex);
                }
            }
        }
    }

    private void linkArticlesToHTMLResources(DPSConnection dpsConnection, DPSProject dpsProject, SharedContentEntity sharedContentEntity) throws DPSException {
        try {
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            AccessToken accessToken = dpsConnection.getAccessToken();
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            String projectId = this.getAndAssertProjectId(dpsProject);
            ProducerApi producerAPI = dpsConnection.getProducerAPI(projectId);
            ArrayList<Future> futureList = new ArrayList<Future>();
            List<DPSArticle> aemArticles = dpsProject.getArticles();
            for (DPSArticle dpsArticle : aemArticles) {
                if (dpsArticle.getId() != null) {
                    String articleEntityURI = DPSUtil.getEntityURI(dpsArticle);
                    Future future = this.threadPool.submit((Callable)new LinkArticleToSharedResourceEntity(entityAccess, producerAPI, accessToken, session, articleEntityURI, sharedContentEntity));
                    futureList.add(future);
                    continue;
                }
                this.LOGGER.debug("Article not uploaded, skipping linking it to new shared resources for " + dpsArticle.getPath());
            }
            for (Future future : futureList) {
                try {
                    future.get();
                    continue;
                }
                catch (Exception ex) {
                    throw new DPSException("Failed result inclusion.", ex);
                }
            }
        }
        catch (Throwable ex) {
            String errorMsg = "Failed to link articles to latest shared resources " + sharedContentEntity.getEntityId();
            this.LOGGER.error(errorMsg, ex);
            throw new DPSException(errorMsg, ex);
        }
    }

    private void uploadCollectionToDPSImpl(DPSCollection dpsCollection, boolean createIfMissing, boolean includeContent) throws DPSException {
        File thumbnail = null;
        File background = null;
        try {
            String backgroundURI;
            String publicationId = this.getAndAssertProjectId(dpsCollection);
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsCollection, DPSConnection.class);
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            ProducerApi producerAPI = dpsConnection.getProducerAPI(publicationId);
            AccessToken accessToken = dpsConnection.getAccessToken();
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            String entityName = dpsCollection.getName();
            CollectionEntity collectionEntity = null;
            if (dpsCollection.getId() == null && createIfMissing) {
                this.LOGGER.info("Creating collection {} for project {}", (Object)entityName, (Object)publicationId);
                try {
                    collectionEntity = producerAPI.createCollectionEntity(entityName, dpsCollection.getTitle(), session);
                }
                catch (EntityVersionConflictException ex) {
                    throw new DPSException("Collection " + entityName + " already exists in AEM Mobile On Demand.", (Throwable)ex);
                }
                this.updateEntityNodesMetaData(dpsCollection, EntityUtils.getEntityUrl((EntityResponse)collectionEntity), true);
            } else {
                String collectionURI = DPSUtil.getEntityURI(dpsCollection);
                collectionEntity = (CollectionEntity)entityAccess.readEntity(accessToken, collectionURI, session);
                if (collectionEntity == null) {
                    throw new DPSException("Collection not found in Experience Manager Mobile for entity " + entityName + " at uri " + collectionURI);
                }
            }
            ModelConversionUtil.updateEntity(collectionEntity, dpsCollection);
            collectionEntity = producerAPI.updateCollectionEntity(collectionEntity, session);
            String thumbnailURI = dpsCollection.getImagePath();
            if (thumbnailURI != null) {
                thumbnail = this.downloadImage(this.resourceResolver, this.slingRequestProcessor, this.requestResponseFactory, thumbnailURI, "toc", this.getExtension(thumbnailURI));
            }
            if ((backgroundURI = dpsCollection.getBackgroundImagePath()) != null) {
                background = this.downloadImage(this.resourceResolver, this.slingRequestProcessor, this.requestResponseFactory, backgroundURI, "background", this.getExtension(backgroundURI));
            }
            collectionEntity = producerAPI.uploadCollectionAll(collectionEntity, null, thumbnail, "images/thumbnail", background, "images/background", session);
            if (dpsCollection.getLayout() != null) {
                LayoutEntity layoutEntity = (LayoutEntity)entityAccess.readEntity(accessToken, dpsCollection.getLayout(), session);
                producerAPI.linkCollectionToLayout(collectionEntity, layoutEntity, session);
            }
            this.updateEntityNodesMetaData(dpsCollection, EntityUtils.getEntityUrl((EntityResponse)collectionEntity), true);
            this.LOGGER.debug(" Upload to Experience Manager Mobile SUCCESSFUL");
        }
        catch (Throwable ex) {
            this.LOGGER.error("Upload to Experience Manager Mobile FAILED", ex);
            throw new DPSException("Failed to upload collection: " + dpsCollection.getPath(), ex);
        }
        finally {
            try {
                if (this.userSession.hasPendingChanges()) {
                    this.userSession.save();
                }
            }
            catch (RepositoryException repEx) {
                this.LOGGER.error("Could not save user session while uploading collection: " + dpsCollection.getName());
            }
            if (thumbnail != null && !thumbnail.delete()) {
                this.LOGGER.error("Failed to delete file " + thumbnail);
            }
            if (background != null && !background.delete()) {
                this.LOGGER.error("Failed to delete file " + thumbnail);
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private File unzip(File file) throws Exception {
        File tempFolder;
        this.LOGGER.debug("unzip article " + file.getCanonicalPath());
        ZipInputStream in = null;
        tempFolder = null;
        try {
            ZipEntry entry;
            BufferedOutputStream out = null;
            in = new ZipInputStream(new FileInputStream(file));
            boolean isDirectory = false;
            String tempFolderPath = new StringBuffer().append(file.getParentFile().getPath()).append(File.separator).append(String.valueOf(System.currentTimeMillis())).toString();
            tempFolder = new File(tempFolderPath);
            this.LOGGER.debug("unzip tmp folder " + tempFolder.getCanonicalPath());
            tempFolder.mkdirs();
            while ((entry = in.getNextEntry()) != null) {
                byte[] data = new byte[16384];
                String entryName = entry.getName();
                File newFile = new File(tempFolder, entryName);
                this.LOGGER.debug("unzip  " + newFile.getCanonicalPath());
                if (entryName.endsWith("/")) {
                    isDirectory = true;
                    newFile.mkdir();
                } else {
                    newFile.getParentFile().mkdirs();
                    newFile.createNewFile();
                }
                if (!isDirectory) {
                    try {
                        int count;
                        out = new BufferedOutputStream(new FileOutputStream(newFile), 16384);
                        while ((count = in.read(data, 0, 16384)) != -1) {
                            out.write(data, 0, count);
                        }
                    }
                    catch (IOException e) {
                        this.LOGGER.warn("failed to write file " + newFile);
                    }
                    finally {
                        out.flush();
                        out.close();
                    }
                }
                isDirectory = false;
            }
        }
        catch (Exception e) {
            this.LOGGER.error("failed to unzip ", (Throwable)e);
            throw e;
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        this.LOGGER.debug("unzipped article " + tempFolder.getCanonicalPath());
        return tempFolder;
    }

    private File getArticleFolio(DPSArticle dpsArticle) throws DPSException, IOException {
        this.LOGGER.debug("Exporting article from AEM " + dpsArticle.getPath());
        File articleFolioFile = this.getContentSyncExport((Page)dpsArticle.adaptTo(Page.class), ".folio", new ExportOptions(ExportOptions.ExportMode.EXPORT_ARTICLE));
        this.LOGGER.debug("Article exported to " + articleFolioFile.getCanonicalPath() + " : " + articleFolioFile.exists());
        return articleFolioFile;
    }

    private File getSharedHTMLResources(DPSProject dpsProject) throws DPSException, IOException {
        this.LOGGER.debug("Exporting shared HTMLResources from AEM " + dpsProject.getPath());
        File zipFile = this.getContentSyncExport((Page)dpsProject.adaptTo(Page.class), ".zip", new ExportOptions(ExportOptions.ExportMode.EXPORT_RESOURCES));
        this.LOGGER.debug("Shared HTMLResources exported to " + zipFile.getCanonicalPath() + " : " + zipFile.exists());
        return zipFile;
    }

    private File getContentSyncExport(Page page, String fileExtension, ExportOptions exportOptions) throws DPSException {
        File file = null;
        FileOutputStream out = null;
        try {
            file = DPSUtil.createTempFile(page.getName(), "export", fileExtension);
            out = new FileOutputStream(file);
            this.exporterService.export(page, this.userSession, out, exportOptions);
        }
        catch (Exception ex) {
            throw new DPSException("Failed to export content (" + (Object)((Object)exportOptions.getExportMode()) + ") content for " + page.getPath(), ex);
        }
        finally {
            if (out != null) {
                try {
                    out.close();
                }
                catch (IOException ex) {
                    this.LOGGER.warn("Could not close file stream ", (Throwable)ex);
                }
            }
        }
        return file;
    }

    private void cleanIds(Node node) throws RepositoryException {
        String[] keys;
        for (String key : keys = new String[]{"dps-id", "dps-lastUploaded", "dps-lastUploadedBy"}) {
            if (!node.hasProperty(key)) continue;
            node.getProperty(key).setValue((String)null);
            this.LOGGER.debug("Cleaned up {} for {}", (Object)key, (Object)node.getPath());
        }
        String contentPath = "jcr:content";
        if (node.hasNode(contentPath)) {
            this.cleanIds(node.getNode(contentPath));
        }
    }

    private boolean doesEntityExistInDPS(DPSProject project, String name, EntityType entityType) throws DPSException {
        if (!(entityType.equals((Object)EntityType.ARTICLE) || entityType.equals((Object)EntityType.COLLECTION) || entityType.equals((Object)EntityType.BANNER))) {
            throw new DPSException("doesEntityExist() does not support entity type " + entityType.name());
        }
        DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(project, DPSConnection.class);
        EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
        AccessToken accessToken = dpsConnection.getAccessToken();
        com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
        String entityURI = DPSUtil.getEntityURI(project.getId(), entityType, name);
        Entity entity = null;
        try {
            entity = entityAccess.readEntity(accessToken, entityURI, session.generateNewRequestId());
        }
        catch (Exception ex) {
            throw new DPSException("Error reading entity while determining if it exists.", ex);
        }
        return entity != null;
    }

    @Override
    public JSONArray getDPSArticles(DPSProject dpsProject, boolean includeReferrers, boolean incStatus) throws DPSException {
        return this.getDPSEntities(dpsProject, EntityType.ARTICLE, includeReferrers, incStatus);
    }

    @Override
    public JSONArray getDPSBanners(DPSProject dpsProject, boolean includeReferrers, boolean incStatus) throws DPSException {
        return this.getDPSEntities(dpsProject, EntityType.BANNER, includeReferrers, incStatus);
    }

    @Override
    public JSONArray getDPSCollections(DPSProject dpsProject, boolean includeReferrers, boolean incStatus, boolean incContent) throws DPSException {
        return this.getDPSEntities(dpsProject, EntityType.COLLECTION, includeReferrers, incStatus);
    }

    @Override
    public JSONArray getDPSLayouts(DPSProject dpsProject, boolean includeReferrers, boolean incStatus) throws DPSException {
        return this.getDPSEntities(dpsProject, EntityType.LAYOUT, includeReferrers, incStatus);
    }

    private JSONArray getDPSEntities(DPSProject dpsProject, EntityType entityType, boolean includeReferrers, boolean incStatus) throws DPSException {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "getDPSEntities-" + entityType.name());
        try {
            perfTimer.startInterim("setup");
            JSONArray entitiesJSON = new JSONArray();
            String publicationId = dpsProject.getProjectId();
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsProject, DPSConnection.class);
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            ProducerApi producerAPI = dpsConnection.getProducerAPI(publicationId);
            AccessToken accessToken = dpsConnection.getAccessToken();
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            EntityListOptions filter = new EntityListOptions(entityType);
            filter.setPageSize(100);
            EntityList entityList = producerAPI.listEntities(filter, session);
            int pagecount = 0;
            perfTimer.endInterim();
            while (entityList != null) {
                perfTimer.startInterim("listNextEntities");
                boolean incContent = entityType.equals((Object)EntityType.COLLECTION);
                JSONArray fetchedEntityJSON = this.getDPSEntities(dpsProject, entityType, entityList, entityAccess, accessToken, session, includeReferrers, incStatus, incContent);
                JSONUtil.appendJSONArrays(entitiesJSON, fetchedEntityJSON);
                ++pagecount;
                perfTimer.endInterim();
                perfTimer.startInterim("listNextEntities");
                entityList = producerAPI.listNextEntites(entityList, session);
                perfTimer.endInterim();
            }
            this.LOGGER.debug("Loaded #pages: " + pagecount);
            perfTimer.end();
            return entitiesJSON;
        }
        catch (Exception ex) {
            throw new DPSException("Failed to get any " + entityType.name() + " items for project: " + dpsProject.getName(), ex);
        }
    }

    @Override
    public JSONObject getReferences(DPSEntity dpsEntity) throws DPSException {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "getReferences");
        try {
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsEntity, DPSConnection.class);
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            AccessToken accessToken = dpsConnection.getAccessToken();
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            String entityURI = dpsEntity.getId();
            Future future = this.threadPool.submit((Callable)new GetReferences(entityAccess, accessToken, session, entityURI));
            JSONObject referencesJSONResponse = (JSONObject)future.get();
            JSONObject referencesJSON = new JSONObject();
            referencesJSON.put(referencesJSONResponse.getString("id"), (Object)referencesJSONResponse.getJSONArray("references"));
            perfTimer.end();
            return referencesJSON;
        }
        catch (Exception ex) {
            throw new DPSException("Failed to get statuses for collection contents: " + dpsEntity.getName(), ex);
        }
    }

    @Override
    public JSONObject getStatuses(DPSCollection dpsCollection) throws DPSException {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "getStatuses-forCollection");
        try {
            ArrayList<String> entityURIs = new ArrayList<String>();
            JSONArray dpsContentLinks = dpsCollection.getContentLinks();
            if (dpsContentLinks.length() > 0) {
                for (int i = 0; i < dpsContentLinks.length(); ++i) {
                    Object next = dpsContentLinks.get(i);
                    if (next instanceof JSONObject) {
                        JSONObject linkJSON = (JSONObject)next;
                        String uri = linkJSON.getString("href");
                        entityURIs.add(uri);
                        continue;
                    }
                    this.LOGGER.warn("Invalid link entry " + next);
                }
            }
            JSONObject statuses = this.getStatuses(dpsCollection.getProject(), entityURIs);
            perfTimer.end();
            return statuses;
        }
        catch (Exception ex) {
            throw new DPSException("Failed to get statuses for collection contents: " + dpsCollection.getName(), ex);
        }
    }

    @Override
    public JSONObject getStatuses(DPSProject dpsProject, List<String> entityURIs) throws DPSException {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "getStatuses-forEntityList");
        JSONObject statuses = new JSONObject();
        try {
            DPSConnection dpsConnection = this.dpsConnectionAdapterFactory.getAdapter(dpsProject, DPSConnection.class);
            EntityProducerDAO entityAccess = dpsConnection.getEntityAccess();
            AccessToken accessToken = dpsConnection.getAccessToken();
            com.adobe.dps.client.producer.utils.Session session = dpsConnection.getSession();
            if (entityURIs == null) {
                ProducerApi producerAPI = dpsConnection.getProducerAPI(this.getAndAssertProjectId(dpsProject));
                StatusList status = producerAPI.getEntityStatus(dpsProject.getId(), EntityType.PUBLICATION, session);
                JSONObject statusJSON = new JSONObject();
                statuses.put(dpsProject.getId(), (Object)MetadataJSONUtil.getStatusJSON(status));
            } else {
                ArrayList<Future> futureList = new ArrayList<Future>();
                for (String link : entityURIs) {
                    Future future = this.threadPool.submit((Callable)new GetStatus(entityAccess, accessToken, session, link));
                    futureList.add(future);
                }
                for (Future future : futureList) {
                    try {
                        JSONObject statusJSON = (JSONObject)future.get();
                        statuses.put(statusJSON.getString("id"), (Object)statusJSON.getJSONObject("status"));
                        continue;
                    }
                    catch (Exception ex) {
                        throw new DPSException("Failed result inclusion.", ex);
                    }
                }
            }
            perfTimer.end();
            return statuses;
        }
        catch (Exception ex) {
            throw new DPSException("Failed to get statuses for entities contents: " + entityURIs, ex);
        }
    }

    private JSONArray getDPSEntities(DPSProject dpsProject, EntityType entityType, EntityList entityList, EntityProducerDAO entityAccess, AccessToken accessToken, com.adobe.dps.client.producer.utils.Session session, boolean includeReferrers, boolean incStatus, boolean incContent) throws Exception {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "getDPSEntities-" + entityType.name());
        JSONArray entities = new JSONArray();
        ArrayList<Future> futureList = new ArrayList<Future>();
        for (EntityLink link : entityList) {
            Future future = this.threadPool.submit((Callable)new GetEntity(entityAccess, accessToken, session, link.getHref().toString(), includeReferrers, incStatus, incContent, entityType));
            futureList.add(future);
        }
        for (Future future : futureList) {
            try {
                entities.put(future.get());
                continue;
            }
            catch (Exception ex) {
                throw new DPSException("Failed result inclusion.", ex);
            }
        }
        perfTimer.end();
        return entities;
    }

    private File downloadImage(ResourceResolver resourceResolver, SlingRequestProcessor slingRequestProcessor, RequestResponseFactory requestResponseFactory, String uri, String name, String fileExtension) throws DPSException {
        FileOutputStream out = null;
        try {
            File file = DPSUtil.createTempFile(name, "imageexport", fileExtension);
            out = new FileOutputStream(file);
            HttpServletRequest request1 = requestResponseFactory.createRequest("GET", uri);
            HttpServletResponse response = requestResponseFactory.createResponse((OutputStream)out);
            slingRequestProcessor.processRequest(request1, response, resourceResolver);
            response.getWriter().flush();
            File file2 = file;
            return file2;
        }
        catch (Exception ex) {
            throw new DPSException("Failed to export " + name, ex);
        }
        finally {
            if (out != null) {
                try {
                    out.close();
                }
                catch (IOException ex) {
                    this.LOGGER.warn("Could not close file stream ", (Throwable)ex);
                }
            }
        }
    }

    private String getExtension(String name) {
        String extension = FilenameUtils.getExtension((String)name);
        if (extension.length() > 0) {
            extension = "." + extension;
        }
        return extension;
    }
}