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

import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.crypto.CryptoSupport;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.scene7.api.S7Config;
import com.day.cq.dam.scene7.api.S7ConfigResolver;
import com.day.cq.dam.scene7.api.Scene7AssetMimetypeService;
import com.day.cq.dam.scene7.api.Scene7EndpointsManager;
import com.day.cq.dam.scene7.api.Scene7FileMetadataService;
import com.day.cq.dam.scene7.api.Scene7Service;
import com.day.cq.dam.scene7.api.Scene7UploadService;
import com.day.cq.dam.scene7.api.constants.Scene7AssetType;
import com.day.cq.dam.scene7.api.model.Scene7Asset;
import com.day.cq.dam.scene7.api.model.UploadJobDetail;
import com.day.cq.dam.scene7.impl.DAMAssetPartSource;
import com.day.cq.dam.scene7.impl.model.FolderAssets;
import com.day.cq.dam.scene7.impl.utils.FolderAssetsUtils;
import com.day.cq.dam.scene7.impl.utils.RequestUtils;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.Replicator;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.Hit;
import com.day.cq.search.result.SearchResult;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.jcr.AccessDeniedException;
import javax.jcr.Binary;
import javax.jcr.InvalidItemStateException;
import javax.jcr.ItemExistsException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.ReferentialIntegrityException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ValueFactory;
import javax.jcr.ValueFormatException;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.version.VersionException;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScheme;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.osgi.services.HttpClientBuilderFactory;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.jcr.api.SlingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

@Component
@Service
public class Scene7UploadServiceImpl
implements Scene7UploadService {
    private static final int ACTIVE_JOB_TIMEOUT = 2100000;
    private static final long ACTIVE_JOB_WAITING_INTERVAL = 10000;
    private static final String SYNC_FLAG = "newRendition";
    private static final int NODE_CHECKED_IN_WAIT = 10000;
    private static final long NODE_CHECKED_IN_WAIT_INTERVAL = 1000;
    private static final int HTTP_SOCKET_TIMEOUT_SECONDS = 180;
    private final Logger log;
    private static final Object lock = new Object();
    @Reference
    private QueryBuilder queryBuilder;
    @Reference
    private Scene7Service scene7Service;
    @Reference
    private S7ConfigResolver s7configResolver;
    @Reference
    private Scene7EndpointsManager scene7EndpointsManager;
    @Reference
    private Scene7FileMetadataService scene7FileMetadataService;
    @Reference
    private Scene7AssetMimetypeService scene7MimeTypeService;
    @Reference
    CryptoSupport cryptoSupport;
    @Reference
    private Replicator replicator;
    @Reference
    private SlingRepository slingRepository;
    @Reference
    private HttpClientBuilderFactory httpClientBuilderFactory;
    @Reference
    private ResourceResolverFactory resolverFactory;

    public Scene7UploadServiceImpl() {
        this.log = LoggerFactory.getLogger(this.getClass());
    }

    @Override
    public String uploadFolder(String path, String cloudServiceConfigPath, ResourceResolver resolver) {
        try {
            S7Config s7Config = this.s7configResolver.getS7Config(resolver, cloudServiceConfigPath);
            Node folderNode = (Node)resolver.getResource(path).adaptTo(Node.class);
            Boolean uploadSubFolders = FolderAssetsUtils.isFolderNodeDeepScene7Managed(folderNode);
            int assetsTotal = 0;
            ArrayList<FolderAssets> folderAssetsList = FolderAssetsUtils.getFolderAssetsList(folderNode, uploadSubFolders);
            for (FolderAssets folderAssets : folderAssetsList) {
                Iterator<String> pathIter = folderAssets.getAssets().iterator();
                this.log.debug("folder path " + folderAssets.getFolderNode().getPath());
                while (pathIter.hasNext()) {
                    this.log.debug(" uploadFolder paths " + pathIter.next());
                    ++assetsTotal;
                }
            }
            this.log.debug(" total Assets to upload =  " + assetsTotal);
            if (assetsTotal > 0) {
                return this.internalUploadFolder(folderAssetsList, s7Config, resolver);
            }
            this.log.debug("uploadFolder no files found to upload for " + path);
            return "success";
        }
        catch (Exception e) {
            this.log.error("storing scene7 upload metadata to asset (" + path + ") failed", (Object)e.getMessage());
            return "failed";
        }
    }

    private String internalUploadFolder(ArrayList<FolderAssets> folderAssetsList, S7Config s7Config, ResourceResolver resolver) {
        HttpClient client = null;
        try {
            client = this.getHttpClientWithAuth(s7Config);
        }
        catch (CryptoException e) {
            this.log.error("uploadFolderFiles failed", (Object)e.getMessage());
        }
        String result = "failed";
        ArrayList<String> uploadedPaths = new ArrayList<String>();
        String publishedServer = s7Config.getPublishServer();
        if (publishedServer == null) {
            this.log.error("upload failed, unable  to retrieve publishedServer");
            return "failed";
        }
        try {
            Node jcrContent;
            SimpleDateFormat ISO8601Local = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss-SSSS");
            String now = ISO8601Local.format(new Date());
            String uploadJobname = "CQ5_folder_upload_" + now;
            String jobHandle = this.startUploadJob(client, uploadJobname, s7Config);
            if (jobHandle.startsWith("failed")) {
                this.log.error("upload failed, unable  to start upload job");
                return jobHandle;
            }
            HashMap<String, String> filePathUploadNameMap = new HashMap<String, String>();
            Iterator<FolderAssets> folderIter = folderAssetsList.iterator();
            boolean defaultMarkForPublish = this.isMarkForPublish(s7Config);
            while (folderIter.hasNext()) {
                FolderAssets folder = folderIter.next();
                for (String path : folder.getAssets()) {
                    String ipsUploadFilePath = s7Config.getRootPath() + path.replaceAll(s7Config.getTargetPath(), "");
                    filePathUploadNameMap.put(path, ipsUploadFilePath);
                    String ipsRootPath = ipsUploadFilePath.substring(0, ipsUploadFilePath.lastIndexOf("/") + 1);
                    String uploadFilename = ipsUploadFilePath.substring(ipsUploadFilePath.lastIndexOf("/") + 1);
                    jcrContent = (Node)resolver.getResource(path + "/jcr:content/metadata").adaptTo(Node.class);
                    this.setS7FileStatusProp("UploadStart", jcrContent);
                    String mimeType = this.getMimeType(resolver, path);
                    String uploadResult = this.doUploadJob(client, jobHandle, path, ipsRootPath, resolver, defaultMarkForPublish, uploadFilename, uploadJobname, s7Config, mimeType);
                    uploadedPaths.add(path);
                    this.log.debug("uploadFolderFiles path " + path + " " + uploadResult);
                }
            }
            result = this.finishUploadJob(client, jobHandle, uploadJobname, s7Config);
            if (result.equals("success")) {
                ArrayList<UploadJobDetail> jobDetailsList = this.scene7Service.getMultiFileJobLogDetails(jobHandle, s7Config);
                for (String path : uploadedPaths) {
                    String assetHandle = this.getAssetHandle(jobDetailsList, (String)filePathUploadNameMap.get(path));
                    Resource damAssetResource = resolver.getResource(path);
                    Asset damAsset = (Asset)damAssetResource.adaptTo(Asset.class);
                    jcrContent = this.getOrAddMetadataNode(path, resolver);
                    if (!assetHandle.startsWith("failed")) {
                        Scene7Asset asset = this.getScene7Asset(assetHandle, s7Config);
                        this.waitOnAssetAvailable(asset, client, s7Config);
                        String publishStatus = "PublishComplete";
                        this.setAssetMetadataOnSync(jcrContent, damAsset, asset, s7Config, publishStatus);
                        if ("on".equalsIgnoreCase(s7Config.isPublishEnabled())) {
                            publishStatus = this.checkScene7AssetPublishState(damAsset, jcrContent);
                            this.scene7FileMetadataService.setAssetMetadataProperty(damAsset, "dam:scene7FileStatus", publishStatus);
                        }
                        if (asset.getAssetType() != Scene7AssetType.VIDEO && asset.getAssetType() != Scene7AssetType.MASTER_VIDEO) continue;
                        this.generateVideoThumb(resolver, path);
                        continue;
                    }
                    this.setS7FileStatusProp("UploadFailed", jcrContent);
                }
            } else {
                this.log.debug("uploadFolderFiles job completion failed");
                result = "failed";
                this.batchSetS7StatusProps(folderAssetsList, "UploadFailed", resolver);
            }
        }
        catch (Exception e) {
            this.log.error("uploadFolderFiles failed", (Object)e.getMessage());
            result = "failed";
            this.batchSetS7StatusProps(folderAssetsList, "UploadFailed", resolver);
        }
        return result;
    }

    private boolean isMarkForPublish(S7Config s7Config) {
        String markForPublishStr = s7Config.isPublishEnabled();
        boolean defaultMarkForPublish = true;
        if ("on".equalsIgnoreCase(markForPublishStr)) {
            defaultMarkForPublish = false;
        }
        return defaultMarkForPublish;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public String uploadFile(String path, String cloudServiceConfigPath, ResourceResolver resolver) {
        S7Config s7Config = this.s7configResolver.getS7Config(resolver, cloudServiceConfigPath);
        HttpClient client = null;
        try {
            client = this.getHttpClientWithAuth(s7Config);
        }
        catch (CryptoException e) {
            this.log.error("scene7 upload asset (" + path + ") failed", (Object)e.getMessage());
        }
        this.log.debug("Cloud Service Config Path = " + cloudServiceConfigPath);
        String publishedServer = s7Config.getPublishServer();
        if (publishedServer == null) {
            this.log.error("upload failed, unable  to retrieve publishedServer");
            return "failed";
        }
        if (path.indexOf("renditions/") != -1) {
            path = path.substring(0, path.indexOf("/jcr:content"));
        }
        Resource damAssetResource = resolver.getResource(path);
        Asset damAsset = (Asset)damAssetResource.adaptTo(Asset.class);
        Node jcrContent = (Node)resolver.getResource(path + "/jcr:content/metadata").adaptTo(Node.class);
        String result = "failed";
        try {
            String uploadFilename;
            String ipsRootPath;
            String uploadJobname;
            String mimeType;
            block20 : {
                mimeType = this.getMimeType(resolver, path);
                if (!this.isTypeSupported(mimeType)) {
                    this.setS7FileStatusProp("NotSupported", jcrContent);
                    this.log.error("upload failed, type not supported: " + mimeType);
                    return "failed";
                }
                uploadFilename = URLEncoder.encode(path.substring(path.lastIndexOf("/") + 1), "UTF-8");
                uploadJobname = "CQ5_upload-" + uploadFilename;
                ipsRootPath = null;
                S7Config resourceConfig = null;
                String scene7ConfigPath = this.s7configResolver.getS7ConfigPathForResource(damAssetResource.getResourceResolver(), damAssetResource);
                ResourceResolver configResolver = null;
                try {
                    configResolver = this.resolverFactory.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "scene7configservice"));
                    resourceConfig = this.s7configResolver.getS7Config(configResolver, scene7ConfigPath);
                    if (resourceConfig != null && path.startsWith(resourceConfig.getTargetPath())) {
                        String ipsUploadFilePath = path.replaceAll(s7Config.getTargetPath(), "");
                        ipsRootPath = s7Config.getRootPath() + ipsUploadFilePath.substring(0, ipsUploadFilePath.lastIndexOf("/") + 1);
                        break block20;
                    }
                    ipsRootPath = s7Config.getAdhocFolder();
                }
                catch (Exception e) {
                    this.log.error("Could not access a S7Config for resource {}", (Object)(damAssetResource != null ? damAssetResource.getPath() : "null"));
                }
                finally {
                    if (configResolver != null) {
                        configResolver.close();
                        configResolver = null;
                    }
                }
            }
            String jobHandle = this.startUploadJob(client, uploadJobname, s7Config);
            if (jobHandle.startsWith("failed")) {
                this.log.error("upload failed, unable  to start upload job");
                return jobHandle;
            }
            this.setS7FileStatusProp("UploadStart", jcrContent);
            this.doUploadJob(client, jobHandle, path, ipsRootPath, resolver, this.isMarkForPublish(s7Config), uploadFilename, uploadJobname, s7Config, mimeType);
            result = this.finishUploadJob(client, jobHandle, uploadJobname, s7Config);
            if (result.equals("success")) {
                String assetHandle = this.getAssetHandle(jobHandle, s7Config);
                if (StringUtils.isNotBlank((String)assetHandle)) {
                    Scene7Asset asset = this.getScene7Asset(assetHandle, s7Config);
                    this.waitOnAssetAvailable(asset, client, s7Config);
                    String publishStatus = "PublishComplete";
                    this.setAssetMetadataOnSync(jcrContent, damAsset, asset, s7Config, publishStatus);
                    if ("on".equalsIgnoreCase(s7Config.isPublishEnabled())) {
                        publishStatus = this.checkScene7AssetPublishState(damAsset, jcrContent);
                        this.scene7FileMetadataService.setAssetMetadataProperty(damAsset, "dam:scene7FileStatus", publishStatus);
                    }
                    if (asset.getAssetType() == Scene7AssetType.VIDEO || asset.getAssetType() == Scene7AssetType.MASTER_VIDEO) {
                        this.generateVideoThumb(resolver, path);
                    }
                } else {
                    this.setS7FileStatusProp("UploadFailed", jcrContent);
                }
            }
        }
        catch (Exception e) {
            this.log.error("scene7 upload asset (" + path + ") failed", (Object)e.getMessage());
            this.clearS7NodeProps(jcrContent);
        }
        return result;
    }

    private String checkScene7AssetPublishState(Asset damAsset, Node metadataNode) throws RepositoryException, ValueFormatException, PathNotFoundException, VersionException, LockException, ConstraintViolationException, AccessDeniedException, ItemExistsException, ReferentialIntegrityException, InvalidItemStateException, NoSuchNodeTypeException, ItemNotFoundException, ReplicationException {
        this.waitOnNodeAvailability(metadataNode);
        if (metadataNode.hasProperty("dam:scene7PublishPending") && metadataNode.getProperty("dam:scene7PublishPending").getBoolean()) {
            metadataNode.getProperty("dam:scene7PublishPending").remove();
            metadataNode.getSession().save();
            Node assetJcrContentNode = metadataNode.getParent();
            if (assetJcrContentNode.hasProperty("cq:lastReplicationAction") && ReplicationActionType.ACTIVATE.toString().equalsIgnoreCase(assetJcrContentNode.getProperty("cq:lastReplicationAction").getString())) {
                this.replicator.replicate(metadataNode.getSession(), ReplicationActionType.ACTIVATE, damAsset.getPath());
                return "PublishComplete";
            }
        }
        return "PublishIncomplete";
    }

    private void waitOnAssetAvailable(Scene7Asset asset, HttpClient client, S7Config s7Config) {
        String serverMethod = "/is/image/";
        if (asset.getAssetType() == Scene7AssetType.IMAGE) {
            serverMethod = "is/image/";
        } else if (asset.getAssetType() == Scene7AssetType.VIDEO || asset.getAssetType() == Scene7AssetType.MASTER_VIDEO) {
            serverMethod = "is/content/";
        } else {
            return;
        }
        long start = System.currentTimeMillis();
        try {
            HttpGet request = new HttpGet(s7Config.getPublishServer() + serverMethod + s7Config.getRootPath() + URLEncoder.encode(asset.getName(), "UTF-8") + "?req=exists&cache=off");
            do {
                HttpEntity entity;
                String response;
                HttpResponse httpResponse;
                if ((response = EntityUtils.toString((HttpEntity)(entity = (httpResponse = client.execute((HttpUriRequest)request)).getEntity()))).contains("catalogRecord.exists=1")) {
                    this.log.info("[{}] is available on edge server", (Object)asset.getName());
                    break;
                }
                if (System.currentTimeMillis() - start > 2100000) {
                    this.log.warn("Timed out waiting for asset available on edge server");
                    break;
                }
                this.wait(10000);
            } while (true);
        }
        catch (Exception e) {
            this.log.warn("[{}] failed waiting for availability on edge server [{}]", (Object)asset.getName(), (Object)e.getMessage());
        }
    }

    @Override
    public String moveFolder(String dstPath, String srcPath, ResourceResolver resolver) {
        try {
            Node dstNode = (Node)resolver.getResource(dstPath).adaptTo(Node.class);
            if (dstPath == null || srcPath == null) {
                return "failed";
            }
            this.deleteSrcFolderPath(dstPath, srcPath, true, resolver);
            if (FolderAssetsUtils.folderNodeHasSetForDeepPublish(dstNode)) {
                String cloudServiceConfigPath = FolderAssetsUtils.getScene7CloudConfigPath(dstNode);
                if (this.isScene7CloudConfigSyncEnabled(resolver, cloudServiceConfigPath)) {
                    this.uploadFolder(dstPath, cloudServiceConfigPath, resolver);
                }
            } else if (FolderAssetsUtils.isFolderNodeDeepScene7Managed(dstNode)) {
                String cloudServiceConfigPath = FolderAssetsUtils.getScene7CloudConfigPath(dstNode);
                if (this.isScene7CloudConfigSyncEnabled(null, cloudServiceConfigPath)) {
                    FolderAssetsUtils.setFolderNodeForDeepPublish(dstNode, "true", resolver);
                    this.uploadFolder(dstPath, cloudServiceConfigPath, resolver);
                    FolderAssetsUtils.setFolderNodeForDeepPublish(dstNode, null, resolver);
                }
            } else {
                String srcParentPath = StringUtils.substringBeforeLast((String)srcPath, (String)"/");
                Node srcParentNode = (Node)resolver.getResource(srcParentPath).adaptTo(Node.class);
                if (FolderAssetsUtils.isFolderNodeDeepScene7Managed(srcParentNode)) {
                    String cloudServiceConfigPath = FolderAssetsUtils.getScene7CloudConfigPath(srcParentNode);
                    if (this.isScene7CloudConfigSyncEnabled(null, cloudServiceConfigPath)) {
                        FolderAssetsUtils.setFolderNodeForDeepPublish(dstNode, "true", resolver);
                        this.uploadFolder(dstPath, cloudServiceConfigPath, resolver);
                    }
                } else {
                    long timestamp = System.currentTimeMillis();
                    ArrayList<FolderAssets> folderAssetsList = FolderAssetsUtils.getFolderAssetsList(dstNode, true);
                    for (FolderAssets folderAssets : folderAssetsList) {
                        String cloudServiceConfigPath;
                        Node folderNode = folderAssets.getFolderNode();
                        if (!FolderAssetsUtils.nodeHasScene7CloudConfig(folderNode) || !this.isScene7CloudConfigSyncEnabled(null, cloudServiceConfigPath = FolderAssetsUtils.getScene7CloudConfigPath(folderNode))) continue;
                        this.uploadFolder(folderNode.getPath(), cloudServiceConfigPath, resolver);
                    }
                    this.batchSyncFilesByDate(dstPath, timestamp, resolver);
                }
            }
        }
        catch (Exception e) {
            this.log.error("synchronizeFolder failed for (" + dstPath + ") failed ", (Throwable)e);
        }
        return "failed";
    }

    private void deleteSrcFolderPath(String dstPath, String srcPath, boolean checkCloudConfigEnabled, ResourceResolver resolver) {
        try {
            String folderHandle;
            Node dstNode = (Node)resolver.getResource(dstPath).adaptTo(Node.class);
            String srcParentPath = StringUtils.substringBeforeLast((String)srcPath, (String)"/");
            Node srcParentNode = (Node)resolver.getResource(srcParentPath).adaptTo(Node.class);
            String cloudConfigPath = null;
            if (FolderAssetsUtils.nodeHasScene7CloudConfig(dstNode)) {
                cloudConfigPath = FolderAssetsUtils.getScene7CloudConfigPath(dstNode);
            } else if (FolderAssetsUtils.isFolderNodeDeepScene7Managed(srcParentNode)) {
                cloudConfigPath = FolderAssetsUtils.getScene7CloudConfigPath(srcParentNode);
            }
            if (cloudConfigPath != null && (!checkCloudConfigEnabled || checkCloudConfigEnabled && this.isScene7CloudConfigSyncEnabled(resolver, cloudConfigPath)) && (folderHandle = this.scene7Service.getFolderHandle(srcPath, this.s7configResolver.getS7Config(resolver, cloudConfigPath))) != null) {
                this.scene7Service.deleteFolder(folderHandle, this.s7configResolver.getS7Config(resolver, cloudConfigPath));
            }
        }
        catch (Exception e) {
            this.log.error("error processing deleteSrcPath: ", (Throwable)e);
        }
    }

    @Override
    public String moveFile(String dstPath, ResourceResolver resolver) {
        String assetHandle = null;
        Node node = (Node)resolver.getResource(dstPath).adaptTo(Node.class);
        Node jcrContent = (Node)resolver.getResource(dstPath + "/jcr:content/metadata").adaptTo(Node.class);
        try {
            if (jcrContent.hasProperty("dam:scene7ID")) {
                assetHandle = jcrContent.getProperty("dam:scene7ID").getString();
            }
            if (assetHandle != null) {
                String cloudConfigPath = FolderAssetsUtils.getScene7CloudConfigPath(node);
                if (cloudConfigPath != null && this.isScene7CloudConfigSyncEnabled(resolver, cloudConfigPath)) {
                    this.scene7Service.deleteAsset(assetHandle, this.s7configResolver.getS7Config(resolver, cloudConfigPath));
                }
                return this.synchronizeFile(dstPath, resolver);
            }
        }
        catch (Exception e) {
            this.log.error("Error accessing S7 ref to metadata Scene7 Asset ID", (Object)e.getMessage());
        }
        return "failed";
    }

    @Override
    public String synchronizeFile(String path, ResourceResolver resolver) {
        try {
            String cloudServiceConfigPath;
            Node node = (Node)resolver.getResource(path).adaptTo(Node.class);
            if (FolderAssetsUtils.isAssetNodeScene7Managed(node) && this.isScene7CloudConfigSyncEnabled(resolver, cloudServiceConfigPath = FolderAssetsUtils.getScene7CloudConfigPath(node))) {
                return this.uploadFile(path, cloudServiceConfigPath, resolver);
            }
        }
        catch (Exception e) {
            this.log.error("retrieving cloud config path for (" + path + ") failed ", (Throwable)e);
        }
        return "failed";
    }

    private boolean isScene7CloudConfigSyncEnabled(ResourceResolver resolver, String cloudConfigPath) {
        try {
            S7Config s7Config = this.s7configResolver.getS7Config(resolver, cloudConfigPath);
            return "on".equals(s7Config.isSyncEnabled());
        }
        catch (Exception e) {
            this.log.error("isNodeScene7Managed failed with ", (Object)e.getMessage());
            return false;
        }
    }

    private Node getOrAddMetadataNode(String path, ResourceResolver resolver) throws RepositoryException {
        Node node = (Node)resolver.getResource(path).adaptTo(Node.class);
        return FolderAssetsUtils.getOrAddNode(node, "jcr:content/metadata", "nt:unstructured");
    }

    private void batchSyncFilesByDate(String searchPath, long publishTime, ResourceResolver resolver) {
        try {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("path", searchPath);
            map.put("daterange.property", "dam:scene7UploadTimeStamp");
            map.put("daterange.upperBound", Long.toString(publishTime));
            map.put("3_property", "dam:scene7FileStatus");
            map.put("3_property.value", "PublishComplete");
            Session session = (Session)resolver.adaptTo(Session.class);
            Query query = this.queryBuilder.createQuery(PredicateGroup.create(map), session);
            query.setHitsPerPage(0);
            query.setStart(0);
            SearchResult result = query.getResult();
            this.log.debug("batchSyncFilesByDate - pending matches ", (Object)result.getTotalMatches());
            for (Hit hit : result.getHits()) {
                String path = "";
                try {
                    path = hit.getPath();
                    String assetPath = StringUtils.substringBefore((String)path, (String)"/jcr:content");
                    this.synchronizeFile(assetPath, resolver);
                }
                catch (Exception e) {
                    this.log.error("Exception when during batch synchronization of s7 files " + path, (Throwable)e);
                }
            }
        }
        catch (Exception e) {
            this.log.error("s7 batch synchronization of s7 files failed ", (Object)e.getMessage());
        }
    }

    private Scene7Asset getScene7Asset(String assetHandle, S7Config s7Config) {
        try {
            List<Scene7Asset> assets = this.scene7Service.getAssets(new String[]{assetHandle}, null, null, s7Config);
            if (assets.size() > 0) {
                Scene7Asset scene7Asset = assets.get(0);
                if (scene7Asset.isPublished()) {
                    this.log.debug("image is available at /is/" + scene7Asset.getAssetTypeStr().toLowerCase() + "/" + scene7Asset.getName());
                    return scene7Asset;
                }
                this.log.debug("image is not yet published");
                return scene7Asset;
            }
        }
        catch (Exception e) {
            this.log.error("getAssetPublishPath, failed to get scene7 assets: " + e.getMessage());
        }
        return null;
    }

    private void batchSetS7StatusProps(ArrayList<FolderAssets> folderAssetsList, String status, ResourceResolver resolver) {
        Iterator<FolderAssets> folderIter = folderAssetsList.iterator();
        while (folderIter.hasNext()) {
            try {
                FolderAssets folder = folderIter.next();
                Iterator<String> pathIter = folder.getAssets().iterator();
                while (pathIter.hasNext()) {
                    Node jcrContent = (Node)resolver.getResource(pathIter.next() + "/jcr:content/metadata").adaptTo(Node.class);
                    try {
                        this.setS7FileStatusProp(status, jcrContent);
                    }
                    catch (Exception e) {
                        this.log.error("clearing asset properties failed.", (Object)e.getMessage());
                    }
                }
                continue;
            }
            catch (Exception e) {
                this.log.error("clearing asset properties failed.", (Object)e.getMessage());
                continue;
            }
        }
    }

    private void setSync(Node content) {
        try {
            if (content.getName().equals("jcr:content")) {
                content.setProperty("newRendition", true);
            }
        }
        catch (Exception e) {
            this.log.error("clearing asset properties failure Ignored", (Object)e.getMessage());
        }
    }

    private void clearS7NodeProps(Node metadataNode) {
        try {
            this.waitOnNodeAvailability(metadataNode);
            this.setSync(metadataNode.getParent());
            if (metadataNode.hasProperty("dam:scene7Name")) {
                metadataNode.setProperty("dam:scene7Name", (String)null);
            }
            if (metadataNode.hasProperty("dam:scene7Type")) {
                metadataNode.setProperty("dam:scene7Type", (String)null);
            }
            if (metadataNode.hasProperty("dam:scene7ID")) {
                metadataNode.setProperty("dam:scene7ID", (String)null);
            }
            if (metadataNode.hasProperty("dam:scene7FileStatus")) {
                metadataNode.setProperty("dam:scene7FileStatus", (String)null);
            }
            if (metadataNode.hasProperty("dam:scene7CompanyID")) {
                metadataNode.setProperty("dam:scene7CompanyID", (String)null);
            }
            if (metadataNode.hasProperty("dam:scene7Folder")) {
                metadataNode.setProperty("dam:scene7Folder", (String)null);
            }
            if (metadataNode.hasProperty("dam:scene7Domain")) {
                metadataNode.setProperty("dam:scene7Domain", (String)null);
            }
            if (metadataNode.hasProperty("dam:scene7UploadTimeStamp")) {
                metadataNode.setProperty("dam:scene7UploadTimeStamp", (String)null);
            }
            if (metadataNode.hasProperty("dam:scene7LastModified")) {
                metadataNode.setProperty("dam:scene7LastModified", (String)null);
            }
            if (metadataNode.hasProperty("dam:scene7APIServer")) {
                metadataNode.setProperty("dam:scene7APIServer", (String)null);
            }
            if (metadataNode.hasProperty("dam:scene7CloudConfigPath")) {
                metadataNode.setProperty("dam:scene7CloudConfigPath", (String)null);
            }
            metadataNode.getSession().save();
        }
        catch (Exception e) {
            this.log.error("clearing asset properties failure Ignored", (Object)e.getMessage());
        }
    }

    private void setS7FileStatusProp(String status, Node metadataNode) throws Exception {
        try {
            this.waitOnNodeAvailability(metadataNode);
            this.setSync(metadataNode.getParent());
            metadataNode.setProperty("dam:scene7FileStatus", status);
            metadataNode.getSession().save();
        }
        catch (VersionException e) {
            this.log.error("setS7FileStatusProps failure (ignored) to write out PN_S7_FILE_STATUS " + status + " for " + metadataNode.getPath() + " " + e.getMessage());
        }
    }

    private void setAssetMetadataOnSync(Node metadataNode, Asset damAsset, Scene7Asset asset, S7Config s7Config, String status) throws Exception {
        try {
            this.waitOnNodeAvailability(metadataNode);
            this.setSync(metadataNode.getParent());
            metadataNode.setProperty("dam:scene7UploadTimeStamp", Calendar.getInstance());
            this.scene7FileMetadataService.setAssetMetadataOnSync(damAsset, asset, s7Config, status);
            this.scene7FileMetadataService.setAssetMetadataProperty(damAsset, "dam:scene7ImportProcessed", String.valueOf(true));
            metadataNode.getSession().save();
        }
        catch (VersionException e) {
            this.log.error("setS7FileUploadTimestampProp  (ignored) failed to write out PN_S7_UPLOAD_TIMESTAMP for " + metadataNode.getPath() + " " + e.getMessage());
        }
    }

    private synchronized Boolean waitOnNodeAvailability(Node jcrNode) {
        long start = System.currentTimeMillis();
        try {
            while (!jcrNode.isCheckedOut()) {
                try {
                    if (System.currentTimeMillis() - start > 10000) {
                        this.log.error("path " + jcrNode.getPath() + " did not relase ");
                        return false;
                    }
                    this.wait(1000);
                    continue;
                }
                catch (InterruptedException e) {
                    this.log.error("path " + jcrNode.getPath() + " did not release ", (Object)e.getMessage());
                    return false;
                }
            }
        }
        catch (RepositoryException e) {
            this.log.error("waitOnNodesAvailability - repository access error ", (Object)e.getMessage());
            return false;
        }
        this.log.debug("Node is checked out and is writeable");
        return true;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private String waitOnUploadJobComplete(String jobHandle, S7Config s7Config) {
        long start = System.currentTimeMillis();
        Object object = lock;
        synchronized (object) {
            while (this.scene7Service.isJobActiveByJobHandle(jobHandle, s7Config)) {
                try {
                    if (System.currentTimeMillis() - start > 2100000) {
                        this.log.warn("Timed out waiting for active Scene7 upload job complete");
                        return "failed";
                    }
                    lock.wait(10000);
                    continue;
                }
                catch (InterruptedException e) {
                    this.log.error("error waiting for Scene7 upload job to complete", (Throwable)e);
                    return "failed";
                }
            }
        }
        this.log.debug("Scene7 upload job completed");
        return "success";
    }

    private HttpClient getHttpClientWithAuth(S7Config s7Config) throws CryptoException {
        URL ipsServerURL = this.scene7EndpointsManager.getIPSServer(s7Config.getRegion());
        int ipsServerPort = ipsServerURL.getPort() == -1 ? 80 : ipsServerURL.getPort();
        String password = this.cryptoSupport.unprotect(s7Config.getPassword());
        SocketConfig sc = SocketConfig.custom().setSoTimeout(180000).build();
        BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(ipsServerURL.getHost(), ipsServerPort), (Credentials)new UsernamePasswordCredentials(s7Config.getEmail(), password));
        PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager();
        CloseableHttpClient client = null;
        if (this.httpClientBuilderFactory != null && this.httpClientBuilderFactory.newBuilder() != null) {
            HttpClientBuilder httpClientBuilder = this.httpClientBuilderFactory.newBuilder();
            httpClientBuilder.setDefaultSocketConfig(sc);
            httpClientBuilder.setDefaultCredentialsProvider((CredentialsProvider)credsProvider);
            httpClientBuilder.setConnectionManager((HttpClientConnectionManager)clientConnectionManager);
            client = httpClientBuilder.build();
        } else {
            client = HttpClients.custom().setDefaultCredentialsProvider((CredentialsProvider)credsProvider).build();
        }
        return client;
    }

    private HttpClientContext getHttpClientContext(S7Config s7Config) {
        URL ipsServerURL = this.scene7EndpointsManager.getIPSServer(s7Config.getRegion());
        int ipsServerPort = ipsServerURL.getPort() == -1 ? 80 : ipsServerURL.getPort();
        BasicAuthCache authCache = new BasicAuthCache();
        authCache.put(new HttpHost(ipsServerURL.getHost(), ipsServerPort, ipsServerURL.getProtocol()), (AuthScheme)new BasicScheme());
        HttpClientContext context = HttpClientContext.create();
        context.setAuthCache((AuthCache)authCache);
        return context;
    }

    protected String startUploadJob(HttpClient client, String uploadJobname, S7Config s7Config) {
        try {
            URL ipsServerURL = this.scene7EndpointsManager.getIPSServer(s7Config.getRegion());
            HttpPost request = new HttpPost(ipsServerURL + "/scene7/IPSAccessServlet" + "?threadClass=com.scene7.upload.UploadThread" + "&companyHandle=" + URIUtil.encodeQuery((String)s7Config.getCompanyHandle()));
            String data = "uploadStarted=true&email=" + URIUtil.encodeQuery((String)s7Config.getEmail()) + "&job=" + uploadJobname + "&userHandle=" + URIUtil.encodeQuery((String)s7Config.getUserHandle());
            StringEntity requestEntity = new StringEntity(data, "UTF-8");
            request.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            request.addHeader("Accept-Charset", "UTF-8");
            request.setEntity((HttpEntity)requestEntity);
            HttpClientContext context = this.getHttpClientContext(s7Config);
            HttpResponse response = client.execute((HttpUriRequest)request, (HttpContext)context);
            HttpEntity responseEntity = response.getEntity();
            String responseBody = EntityUtils.toString((HttpEntity)responseEntity);
            this.log.debug(responseBody);
            Document document = RequestUtils.getResponseDOM(IOUtils.toInputStream((String)responseBody));
            if (document != null) {
                NodeList jobs = document.getElementsByTagName("job");
                if (jobs.getLength() > 0) {
                    Element job = (Element)jobs.item(0);
                    String originalJobname = URLDecoder.decode(uploadJobname, "UTF-8");
                    return job.getAttribute("handle").replace(originalJobname, uploadJobname);
                }
                NodeList exceptions = document.getElementsByTagName("exception");
                if (exceptions.getLength() > 0) {
                    this.log.error("error while starting scene7 job: " + ((Element)exceptions.item(0)).getAttribute("value"));
                    return "failed: " + ((Element)exceptions.item(0)).getAttribute("value");
                }
            }
        }
        catch (Exception e) {
            this.log.error("error while processing scene7 start job", (Throwable)e);
            return "failed: " + e.getMessage();
        }
        return "failed";
    }

    protected String doUploadJob(HttpClient client, String jobHandle, String path, String rootPath, ResourceResolver resolver, boolean doPublish, String uploadFilename, String uploadJobname, S7Config s7Config, String mimeType) {
        try {
            String[] propNames;
            URL ipsServerURL = this.scene7EndpointsManager.getIPSServer(s7Config.getRegion());
            HttpPost request = new HttpPost(ipsServerURL + "/scene7/IPSAccessServlet" + "?threadClass=com.scene7.upload.UploadThread" + "&companyHandle=" + URIUtil.encodeQuery((String)s7Config.getCompanyHandle()) + "&emailPref=4");
            this.log.debug("doUploadJob for path = " + path);
            Asset asset = (Asset)resolver.getResource(path).adaptTo(Asset.class);
            String encodingPresets = "";
            String encValue = null;
            for (String propName : propNames = new String[]{"adaptiveVideoEncodingPresets", "desktopVideoEncodingPresets", "mobileVideoEncodingPresets", "tabletVideoEncodingPresets"}) {
                encValue = s7Config.get(propName);
                if (encValue == null || encValue.length() <= 0) continue;
                encodingPresets = encodingPresets + (encodingPresets != "" ? "," : "") + encValue;
            }
            Properties props = new Properties(this.getDefaultOptions());
            if (encodingPresets.length() > 0) {
                props.put("videoEncodingPresets", encodingPresets);
            }
            Charset charsetUtf8 = Charset.forName("UTF-8");
            ContentType contentTypeUtf8 = ContentType.create((String)ContentType.MULTIPART_FORM_DATA.getMimeType(), (Charset)charsetUtf8);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            HashMap<String, StringBody> parts = new HashMap<String, StringBody>();
            parts.put("email", new StringBody(URIUtil.encodeQuery((String)s7Config.getEmail()), ContentType.MULTIPART_FORM_DATA));
            parts.put("userHandle", new StringBody(URIUtil.encodeQuery((String)s7Config.getUserHandle()), ContentType.MULTIPART_FORM_DATA));
            parts.put("job", new StringBody(URIUtil.encodeQuery((String)uploadJobname), contentTypeUtf8));
            parts.put("jobHandle", new StringBody(URIUtil.encodeQuery((String)jobHandle), contentTypeUtf8));
            parts.put("strPath", new StringBody(URIUtil.encodeQuery((String)rootPath), contentTypeUtf8));
            parts.put("filename", new StringBody(URIUtil.encodeQuery((String)uploadFilename), contentTypeUtf8));
            parts.put("publish", new StringBody(Boolean.toString(doPublish), ContentType.MULTIPART_FORM_DATA));
            if ("on".equalsIgnoreCase(s7Config.isPublishEnabled())) {
                parts.put("preserve", new StringBody(URIUtil.encodeQuery((String)Integer.toString(1)), ContentType.MULTIPART_FORM_DATA));
            }
            HashMap existingParts = new HashMap();
            for (String existingPart : parts.keySet()) {
                existingParts.put(existingPart, parts.get(existingPart));
            }
            String jobParams = s7Config.getMimeTypeJobParams(mimeType);
            if (jobParams != null && jobParams.length() > 0) {
                String[] jobParamPairs;
                for (String pair : jobParamPairs = jobParams.split("&")) {
                    int idx = pair.indexOf("=");
                    String key = URLDecoder.decode(pair.substring(0, idx), "UTF-8");
                    String value = URLDecoder.decode(pair.substring(idx + 1), "UTF-8");
                    if (existingParts.containsKey(key)) continue;
                    parts.put(key, new StringBody(value, ContentType.MULTIPART_FORM_DATA));
                }
            }
            Set<String> names = props.stringPropertyNames();
            for (String key : names) {
                String value = props.getProperty(key);
                if (value == null) continue;
                parts.put(key, new StringBody(value, ContentType.MULTIPART_FORM_DATA));
            }
            for (String partKey : parts.keySet()) {
                StringBody partValue = (StringBody)parts.get(partKey);
                builder.addPart(partKey, (ContentBody)partValue);
            }
            DAMAssetPartSource partSource = new DAMAssetPartSource(asset);
            builder.addPart("file", (ContentBody)new InputStreamBody(partSource.createInputStream(), contentTypeUtf8, URLEncoder.encode(partSource.getFileName(), "UTF-8")));
            HttpEntity requestEntity = builder.build();
            request.setEntity(requestEntity);
            HttpClientContext context = this.getHttpClientContext(s7Config);
            HttpResponse response = client.execute((HttpUriRequest)request, (HttpContext)context);
            HttpEntity responseEntity = response.getEntity();
            String responseBody = EntityUtils.toString((HttpEntity)responseEntity);
            this.log.debug(responseBody);
            Document document = RequestUtils.getResponseDOM(IOUtils.toInputStream((String)responseBody));
            if (document != null) {
                NodeList exceptions = document.getElementsByTagName("exception");
                if (exceptions.getLength() > 0) {
                    this.log.error("error while doing scene7 job: " + ((Element)exceptions.item(0)).getAttribute("value"));
                    return "failed: " + ((Element)exceptions.item(0)).getAttribute("value");
                }
                return "success";
            }
        }
        catch (Exception e) {
            this.log.error("error while processing scene7 do upload job", (Throwable)e);
            return "failed" + e.getMessage();
        }
        return "failed";
    }

    private Properties getDefaultOptions() {
        Properties props = new Properties();
        props.setProperty("overwrite", "true");
        return props;
    }

    protected String finishUploadJob(HttpClient client, String jobHandle, String uploadJobname, S7Config s7Config) {
        try {
            URL ipsServerURL = this.scene7EndpointsManager.getIPSServer(s7Config.getRegion());
            HttpPost request = new HttpPost(ipsServerURL + "/scene7/IPSAccessServlet" + "?threadClass=com.scene7.upload.UploadThread" + "&companyHandle=" + URIUtil.encodeQuery((String)s7Config.getCompanyHandle()));
            String data = "uploadFinished=true&email=" + URIUtil.encodeQuery((String)s7Config.getEmail()) + "&job=" + uploadJobname + "&userHandle=" + URIUtil.encodeQuery((String)s7Config.getUserHandle()) + "&jobHandle=" + URIUtil.encodeQuery((String)jobHandle);
            StringEntity requestEntity = new StringEntity(data, "UTF-8");
            request.addHeader("Content-Type", "application/x-www-form-urlencoded");
            request.setEntity((HttpEntity)requestEntity);
            HttpClientContext context = this.getHttpClientContext(s7Config);
            HttpResponse response = client.execute((HttpUriRequest)request, (HttpContext)context);
            HttpEntity responseEntity = response.getEntity();
            String responseBody = EntityUtils.toString((HttpEntity)responseEntity);
            this.log.debug(responseBody);
            Document document = RequestUtils.getResponseDOM(IOUtils.toInputStream((String)responseBody));
            if (document != null) {
                NodeList exceptions = document.getElementsByTagName("exception");
                if (exceptions.getLength() > 0) {
                    this.log.error("error while finishing scene7 job: " + ((Element)exceptions.item(0)).getAttribute("value"));
                    return "failed: " + ((Element)exceptions.item(0)).getAttribute("value");
                }
                return this.waitOnUploadJobComplete(jobHandle, s7Config);
            }
        }
        catch (Exception e) {
            this.log.error("error while processing scene7 finish job", (Throwable)e);
            return "failed: " + e.getMessage();
        }
        return "success";
    }

    private String getAssetHandle(String jobHandle, S7Config s7Config) {
        String assetHandle = "";
        List<String> assetHandles = this.scene7Service.getJobLogDetails(jobHandle, s7Config);
        if (assetHandles.size() > 0) {
            assetHandle = assetHandles.get(0);
            return assetHandle;
        }
        return assetHandle;
    }

    private String getAssetHandle(ArrayList<UploadJobDetail> jobDetailsList, String fileName) {
        if (jobDetailsList.size() > 0) {
            for (int i = jobDetailsList.size() - 1; i >= 0; --i) {
                UploadJobDetail detail = jobDetailsList.get(i);
                if (!StringUtils.containsIgnoreCase((String)detail.getLogMessage(), (String)fileName)) continue;
                return detail.getAssetHandle();
            }
        }
        return "failed";
    }

    private String getMimeType(ResourceResolver resolver, String path) throws RepositoryException {
        Node original = (Node)resolver.getResource(path + "/jcr:content/renditions/original/jcr:content").adaptTo(Node.class);
        String mimeType = original.getProperty("jcr:mimeType").getString();
        return mimeType;
    }

    private boolean isTypeSupported(String mimeType) {
        String mimeTypeEncoded = mimeType.replace("/", "_");
        mimeTypeEncoded = mimeTypeEncoded.replace("*", "");
        mimeTypeEncoded = mimeTypeEncoded.toLowerCase();
        for (String element : this.scene7MimeTypeService.getSupportedMimeTypes()) {
            if (!mimeTypeEncoded.startsWith(element)) continue;
            return true;
        }
        return false;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void generateVideoThumb(ResourceResolver resolver, String path) {
        Node metaNode = (Node)resolver.getResource(path + "/" + "jcr:content" + "/" + "metadata").adaptTo(Node.class);
        Node renditionsNode = (Node)resolver.getResource(path + "/" + "jcr:content" + "/" + "renditions").adaptTo(Node.class);
        Session session = (Session)resolver.adaptTo(Session.class);
        int tries = 0;
        try {
            while (tries++ < 5) {
                try {
                    Thread.sleep(1000);
                    String[] sizes = new String[]{"48", "48", "319", "319", "140", "100"};
                    String fmtStr = "png";
                    for (int i = 0; i < sizes.length; i += 2) {
                        String widStr = sizes[i];
                        String heiStr = sizes[i + 1];
                        URL url = new URL(metaNode.getProperty("dam:scene7Domain").getString() + "is/image/" + metaNode.getProperty("dam:scene7File").getString() + "?wid=" + widStr + "&hei=" + heiStr + "&fmt=" + "png");
                        InputStream in = url.openStream();
                        Binary bin = session.getValueFactory().createBinary(in);
                        String nodeName = "cq5dam.thumbnail." + widStr + "." + heiStr + "." + "png";
                        Node thumbNode = null;
                        thumbNode = renditionsNode.hasNode(nodeName) ? renditionsNode.getNode(nodeName) : renditionsNode.addNode(nodeName, "nt:file");
                        Node contentNode = null;
                        contentNode = thumbNode.hasNode("jcr:content") ? thumbNode.getNode("jcr:content") : thumbNode.addNode("jcr:content", "nt:resource");
                        contentNode.setProperty("jcr:mimeType", "image/png");
                        contentNode.setProperty("jcr:data", bin);
                        in.close();
                    }
                    continue;
                }
                catch (Exception e) {
                    this.log.error("generateVideoThumb: " + e.getMessage());
                    continue;
                }
            }
        }
        finally {
            try {
                if (session != null && session.isLive()) {
                    session.save();
                }
            }
            catch (Exception e) {
                this.log.error("generateVideoThumb: failed to close session " + e.getMessage());
            }
        }
    }

    protected void bindQueryBuilder(QueryBuilder queryBuilder) {
        this.queryBuilder = queryBuilder;
    }

    protected void unbindQueryBuilder(QueryBuilder queryBuilder) {
        if (this.queryBuilder == queryBuilder) {
            this.queryBuilder = null;
        }
    }

    protected void bindScene7Service(Scene7Service scene7Service) {
        this.scene7Service = scene7Service;
    }

    protected void unbindScene7Service(Scene7Service scene7Service) {
        if (this.scene7Service == scene7Service) {
            this.scene7Service = null;
        }
    }

    protected void bindS7configResolver(S7ConfigResolver s7ConfigResolver) {
        this.s7configResolver = s7ConfigResolver;
    }

    protected void unbindS7configResolver(S7ConfigResolver s7ConfigResolver) {
        if (this.s7configResolver == s7ConfigResolver) {
            this.s7configResolver = null;
        }
    }

    protected void bindScene7EndpointsManager(Scene7EndpointsManager scene7EndpointsManager) {
        this.scene7EndpointsManager = scene7EndpointsManager;
    }

    protected void unbindScene7EndpointsManager(Scene7EndpointsManager scene7EndpointsManager) {
        if (this.scene7EndpointsManager == scene7EndpointsManager) {
            this.scene7EndpointsManager = null;
        }
    }

    protected void bindScene7FileMetadataService(Scene7FileMetadataService scene7FileMetadataService) {
        this.scene7FileMetadataService = scene7FileMetadataService;
    }

    protected void unbindScene7FileMetadataService(Scene7FileMetadataService scene7FileMetadataService) {
        if (this.scene7FileMetadataService == scene7FileMetadataService) {
            this.scene7FileMetadataService = null;
        }
    }

    protected void bindScene7MimeTypeService(Scene7AssetMimetypeService scene7AssetMimetypeService) {
        this.scene7MimeTypeService = scene7AssetMimetypeService;
    }

    protected void unbindScene7MimeTypeService(Scene7AssetMimetypeService scene7AssetMimetypeService) {
        if (this.scene7MimeTypeService == scene7AssetMimetypeService) {
            this.scene7MimeTypeService = null;
        }
    }

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

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

    protected void bindReplicator(Replicator replicator) {
        this.replicator = replicator;
    }

    protected void unbindReplicator(Replicator replicator) {
        if (this.replicator == replicator) {
            this.replicator = null;
        }
    }

    protected void bindSlingRepository(SlingRepository slingRepository) {
        this.slingRepository = slingRepository;
    }

    protected void unbindSlingRepository(SlingRepository slingRepository) {
        if (this.slingRepository == slingRepository) {
            this.slingRepository = null;
        }
    }

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

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

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

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