HtmlLibraryManagerImpl.java 61.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 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.annotation.Nonnull
 *  javax.jcr.Binary
 *  javax.jcr.Item
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.ValueFactory
 *  javax.jcr.Workspace
 *  javax.jcr.observation.Event
 *  javax.jcr.observation.EventIterator
 *  javax.jcr.observation.EventListener
 *  javax.jcr.observation.ObservationManager
 *  javax.jcr.query.Query
 *  javax.jcr.query.QueryManager
 *  javax.jcr.query.QueryResult
 *  javax.servlet.ServletOutputStream
 *  javax.servlet.http.HttpServletRequest
 *  javax.servlet.http.HttpServletResponse
 *  org.apache.commons.io.IOUtils
 *  org.apache.commons.lang.StringUtils
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Deactivate
 *  org.apache.felix.scr.annotations.Modified
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.api.observation.JackrabbitEventFilter
 *  org.apache.jackrabbit.api.observation.JackrabbitObservationManager
 *  org.apache.jackrabbit.commons.JcrUtils
 *  org.apache.jackrabbit.util.Text
 *  org.apache.sling.api.SlingHttpServletRequest
 *  org.apache.sling.api.SlingHttpServletResponse
 *  org.apache.sling.api.request.RequestPathInfo
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.io.JSONWriter
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.apache.sling.jcr.resource.JcrPropertyMap
 *  org.apache.sling.settings.SlingSettingsService
 *  org.osgi.service.event.Event
 *  org.osgi.service.event.EventAdmin
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.granite.ui.clientlibs.impl;

import com.adobe.granite.ui.clientlibs.ClientLibrary;
import com.adobe.granite.ui.clientlibs.HtmlLibrary;
import com.adobe.granite.ui.clientlibs.HtmlLibraryManager;
import com.adobe.granite.ui.clientlibs.LibraryType;
import com.adobe.granite.ui.clientlibs.impl.AbstractBuilder;
import com.adobe.granite.ui.clientlibs.impl.ClientLibraryImpl;
import com.adobe.granite.ui.clientlibs.impl.CompilerProvider;
import com.adobe.granite.ui.clientlibs.impl.CssFileBuilder;
import com.adobe.granite.ui.clientlibs.impl.FileBundle;
import com.adobe.granite.ui.clientlibs.impl.HtmlLibraryImpl;
import com.adobe.granite.ui.clientlibs.impl.JsFileBuilder;
import com.adobe.granite.ui.clientlibs.impl.LibraryCacheImpl;
import com.adobe.granite.ui.clientlibs.impl.LongCacheConfig;
import com.adobe.granite.ui.clientlibs.impl.ProcessorConfig;
import com.adobe.granite.ui.clientlibs.impl.ProcessorProvider;
import com.adobe.granite.ui.clientlibs.script.ScriptResource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Collection;
import java.util.Dictionary;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.zip.GZIPOutputStream;
import javax.annotation.Nonnull;
import javax.jcr.Binary;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
import javax.jcr.observation.Event;
import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventListener;
import javax.jcr.observation.ObservationManager;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.api.observation.JackrabbitEventFilter;
import org.apache.jackrabbit.api.observation.JackrabbitObservationManager;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestPathInfo;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.io.JSONWriter;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.resource.JcrPropertyMap;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.service.event.EventAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1, immediate=1)
@Service(value={HtmlLibraryManager.class})
public class HtmlLibraryManagerImpl
implements HtmlLibraryManager,
EventListener {
    private static final Logger log = LoggerFactory.getLogger(HtmlLibraryManagerImpl.class);
    private static final String INCLUDED_SET_ATTR_NAME = HtmlLibraryManager.class.getName() + ".included";
    private static final String INCLUDES_TXT = "includes.txt";
    public static String WRITE_LOCATION = "/var/clientlibs";
    private static final String CQ_CLIENT_LIBRARY_FOLDER = "cq:ClientLibraryFolder";
    private static final String DEFAULT_FIREBUG_LITE_PATH = "/libs/granite/ui/content/firebug-lite/source/firebug-lite.js#startOpened=true";
    private static final String TOPIC_INVALIDATED = "com/adobe/granite/ui/librarymanager/INVALIDATED";
    @Reference
    protected SlingRepository repository;
    @Reference
    protected SlingSettingsService settingsService;
    @Reference
    private EventAdmin eventAdmin = null;
    @Reference
    private CompilerProvider compilerProvider = null;
    @Reference
    private ProcessorProvider processorProvider = null;
    @org.apache.felix.scr.annotations.Property(boolValue={0})
    protected static final String CONFIG_PROPERTY_MINIFY = "htmllibmanager.minify";
    @org.apache.felix.scr.annotations.Property(boolValue={0})
    protected static final String CONFIG_PROPERTY_DEBUG = "htmllibmanager.debug";
    @org.apache.felix.scr.annotations.Property(boolValue={1})
    protected static final String CONFIG_PROPERTY_GZIP = "htmllibmanager.gzip";
    @org.apache.felix.scr.annotations.Property(longValue={-1})
    protected static final String CONFIG_PROPERTY_MAX_AGE = "htmllibmanager.maxage";
    @org.apache.felix.scr.annotations.Property(boolValue={0})
    protected static final String CONFIG_PROPERTY_TIMING = "htmllibmanager.timing";
    @org.apache.felix.scr.annotations.Property(boolValue={0})
    protected static final String CONFIG_FORCE_CQ_URLINFO = "htmllibmanager.forceCQUrlInfo";
    @org.apache.felix.scr.annotations.Property(longValue={0})
    protected static final String CONFIG_PROPERTY_MAX_DATA_URI_SIZE = "htmllibmanager.maxDataUriSize";
    @org.apache.felix.scr.annotations.Property(value={"/libs/granite/ui/content/firebug-lite/source/firebug-lite.js#startOpened=true"})
    protected static final String CONFIG_PROPERTY_FIREBUG_LITE_PATH = "htmllibmanager.firebuglite.path";
    @org.apache.felix.scr.annotations.Property(boolValue={0})
    protected static final String CONFIG_PROPERTY_DEBUG_CONSOLE = "htmllibmanager.debug.console";
    @org.apache.felix.scr.annotations.Property(value={"window.CQ_initial_log_level='INFO';"})
    protected static final String CONFIG_PROPERTY_DEBUG_INIT_JS = "htmllibmanager.debug.init.js";
    @org.apache.felix.scr.annotations.Property(value={"default"})
    protected static final String CONFIG_PROPERTY_DEFAULT_THEME_NAME = "htmllibmanager.defaultthemename";
    @org.apache.felix.scr.annotations.Property(value={"default"})
    protected static final String CONFIG_PROPERTY_DEFAULT_USER_THEME_NAME = "htmllibmanager.defaultuserthemename";
    @org.apache.felix.scr.annotations.Property(value={"granite.clientlibrarymanager"})
    protected static final String CONFIG_CLIENT_MANAGER_CATEGORY = "htmllibmanager.clientmanager";
    @org.apache.felix.scr.annotations.Property(value={"/apps", "/libs", "/etc"})
    protected static final String CONFIG_PROPERTY_PATH_LIST = "htmllibmanager.path.list";
    @org.apache.felix.scr.annotations.Property(value={"/etc/workflow/instances", "/etc/taskmanagement"})
    protected static final String CONFIG_PROPERTY_EXCLUDED_PATH_LIST = "htmllibmanager.excluded.path.list";
    @org.apache.felix.scr.annotations.Property(cardinality=Integer.MAX_VALUE)
    protected static final String CONFIG_LONG_CACHE_PATTERNS = "htmllibmanager.longcache.patterns";
    @org.apache.felix.scr.annotations.Property(value={"lc-%s-lc"})
    protected static final String CONFIG_LONG_CACHE_FORMAT = "htmllibmanager.longcache.format";
    private static final String CONFIG_PROCESSOR_DEFAULT = "min:yui";
    @org.apache.felix.scr.annotations.Property(value={"min:yui"}, cardinality=Integer.MAX_VALUE)
    protected static final String CONFIG_JS_PROCESSOR = "htmllibmanager.processor.js";
    @org.apache.felix.scr.annotations.Property(value={"min:yui"}, cardinality=Integer.MAX_VALUE)
    protected static final String CONFIG_CSS_PROCESSOR = "htmllibmanager.processor.css";
    private static final String CUSTOM_JAVA_SCRIPT_PATH = "customJavaScriptPath";
    private static final String[] EMPTY_STRING_ARRAY = new String[0];
    private static final String CSS = "css";
    private static final String JS = "js";
    private static final String PN_CATEGORIES = "categories";
    private static final String PN_DEPENDENCIES = "dependencies";
    private static final String PN_EMBED = "embed";
    private static final String PN_CHANNELS = "channels";
    private static final String PN_ALLOW_PROXY = "allowProxy";
    private static final String PN_LONG_CACHE_KEY = "longCacheKey";
    private static final String PN_CSS_PROCESSOR = "cssProcessor";
    private static final String PN_JS_PROCESSOR = "jsProcessor";
    private final LibraryCacheImpl cache = new LibraryCacheImpl();
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private Session listenerSession;
    private boolean enableTiming;
    private boolean enableDebugConsole;
    private String firebugLiteJSPath;
    private String debugInitJS;
    private boolean enableMinify;
    private boolean enableDebug;
    private boolean enableGzip;
    private long maxDataUriSize;
    private long maxAge;
    private boolean forceCQUrlInfo;
    private boolean isLoaded;
    private boolean isResolved;
    private String defaultThemeName = "default";
    private String defaultUserThemeName = "default";
    private String clientMgrCategory;
    private String[] allowedPaths;
    private String[] excludedPaths;
    private LongCacheConfig longCacheConfig = new LongCacheConfig();
    private List<ProcessorConfig> jsDefaultProcessorConfig;
    private List<ProcessorConfig> cssDefaultProcessorConfig;
    private static final String CLIENTLIBS_SERVICE = "clientlibs-service";

    @Nonnull
    public Session getServiceSession() throws RepositoryException {
        return this.repository.loginService("clientlibs-service", null);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Activate
    protected void activate(Map<String, Object> properties) {
        this.lock.writeLock().lock();
        try {
            this.update(properties);
            JackrabbitEventFilter eventFilter = new JackrabbitEventFilter().setEventTypes(31).setAbsPath(this.allowedPaths[0]).setIsDeep(true).setNoLocal(true);
            if (this.allowedPaths.length > 0) {
                eventFilter.setAdditionalPaths(this.allowedPaths);
            }
            if (this.excludedPaths != null && this.excludedPaths.length > 0) {
                eventFilter.setExcludedPaths(this.excludedPaths);
            }
            this.listenerSession = this.getServiceSession();
            JackrabbitObservationManager observationManager = (JackrabbitObservationManager)this.listenerSession.getWorkspace().getObservationManager();
            observationManager.addEventListener((EventListener)this, eventFilter);
        }
        catch (RepositoryException e) {
            log.error("Error during initialization of component.", (Throwable)e);
        }
        finally {
            this.lock.writeLock().unlock();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Modified
    protected void update(Map<String, Object> properties) {
        this.lock.writeLock().lock();
        try {
            this.enableMinify = (Boolean)properties.get("htmllibmanager.minify");
            this.enableTiming = (Boolean)properties.get("htmllibmanager.timing");
            this.firebugLiteJSPath = (String)properties.get("htmllibmanager.firebuglite.path");
            this.enableDebugConsole = (Boolean)properties.get("htmllibmanager.debug.console");
            this.enableDebug = (Boolean)properties.get("htmllibmanager.debug");
            this.maxDataUriSize = (Long)properties.get("htmllibmanager.maxDataUriSize");
            this.maxAge = (Long)properties.get("htmllibmanager.maxage");
            this.debugInitJS = (String)properties.get("htmllibmanager.debug.init.js");
            this.defaultThemeName = (String)properties.get("htmllibmanager.defaultthemename");
            this.defaultUserThemeName = (String)properties.get("htmllibmanager.defaultuserthemename");
            this.clientMgrCategory = (String)properties.get("htmllibmanager.clientmanager");
            this.enableGzip = (Boolean)properties.get("htmllibmanager.gzip");
            this.forceCQUrlInfo = (Boolean)properties.get("htmllibmanager.forceCQUrlInfo");
            this.allowedPaths = PropertiesUtil.toStringArray((Object)properties.get("htmllibmanager.path.list"));
            this.excludedPaths = PropertiesUtil.toStringArray((Object)properties.get("htmllibmanager.excluded.path.list"));
            this.longCacheConfig = new LongCacheConfig(PropertiesUtil.toStringArray((Object)properties.get("htmllibmanager.longcache.patterns")), null, PropertiesUtil.toString((Object)properties.get("htmllibmanager.longcache.format"), (String)null));
            this.jsDefaultProcessorConfig = ProcessorConfig.parse(PropertiesUtil.toStringArray((Object)properties.get("htmllibmanager.processor.js"), (String[])new String[]{"min:yui"}));
            this.cssDefaultProcessorConfig = ProcessorConfig.parse(PropertiesUtil.toStringArray((Object)properties.get("htmllibmanager.processor.css"), (String[])new String[]{"min:yui"}));
            this.isLoaded = false;
            this.isResolved = false;
            this.cache.clear();
        }
        finally {
            this.lock.writeLock().unlock();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Deactivate
    protected void deactivate() {
        block5 : {
            this.lock.writeLock().lock();
            try {
                if (this.listenerSession == null) break block5;
                try {
                    this.listenerSession.getWorkspace().getObservationManager().removeEventListener((EventListener)this);
                }
                catch (RepositoryException e) {
                    // empty catch block
                }
                this.listenerSession.logout();
            }
            finally {
                this.listenerSession = null;
                this.lock.writeLock().unlock();
            }
        }
    }

    @Override
    public /* varargs */ void writeIncludes(SlingHttpServletRequest request, Writer out, String ... categories) throws IOException {
        this.internalWriteIncludes(request, out, null, this.getDefaultThemeName(request), null, categories);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private /* varargs */ void internalWriteIncludes(SlingHttpServletRequest request, Writer out, Boolean themed, String theme, LibraryType reqType, String ... categories) throws IOException {
        Map<String, ClientLibrary> libs;
        boolean minify;
        this.lock.readLock().lock();
        try {
            libs = this.lockedGetLibs(categories, reqType, themed, theme, true);
        }
        finally {
            this.lock.readLock().unlock();
        }
        boolean dynamic = false;
        for (ClientLibrary lib : libs.values()) {
            if (lib.getChannels().length <= 0) continue;
            dynamic = true;
            break;
        }
        if (this.forceCQUrlInfo || "true".equals(String.valueOf(request.getAttribute("com.day.cq.widget.htmllibrarymanager.forceurlinfo")))) {
            this.writeURLInfo(request, out, dynamic);
        }
        this.writeDebugConsole(request, out);
        boolean isDebug = this.debugClientLibs(request);
        boolean bl = minify = this.enableMinify && !isDebug;
        if (dynamic) {
            this.internalWriteJsInclude(request, out, null, null, new String[]{this.clientMgrCategory});
            StringWriter buffer = new StringWriter();
            JSONWriter json = new JSONWriter((Writer)buffer);
            json.setTidy(isDebug);
            int numLibs = 0;
            try {
                json.array();
                for (ClientLibrary lib2 : libs.values()) {
                    for (LibraryType type : lib2.getTypes()) {
                        if (reqType != null && type != reqType) continue;
                        String rawPath = lib2.getIncludePath(type);
                        String path = this.getIncludePath(request, lib2, type, minify);
                        if (path != null && !this.isIncluded(request, rawPath)) {
                            ++numLibs;
                            if (isDebug) {
                                path = path + "?debug=true";
                            }
                            json.object();
                            json.key("p").value((Object)(request.getContextPath() + path));
                            json.key("c").array();
                            for (String c : lib2.getChannels()) {
                                json.value((Object)c);
                            }
                            json.endArray();
                            json.endObject();
                        }
                        for (ClientLibrary emb : lib2.getEmbedded(type).values()) {
                            this.isIncluded(request, emb.getIncludePath(type));
                        }
                    }
                }
                json.endArray();
            }
            catch (JSONException e) {
                IOException io = new IOException("Error while generating JSON object");
                io.initCause((Throwable)e);
                throw io;
            }
            if (numLibs > 0) {
                out.write("<script type=\"text/javascript\">\n");
                out.write("GraniteClientLibraryManager.write(");
                out.write(buffer.toString());
                out.write("," + isDebug + ");\n</script>\n");
            }
        } else {
            if (reqType == null || reqType == LibraryType.CSS) {
                for (ClientLibrary lib3 : libs.values()) {
                    if (!lib3.getTypes().contains((Object)LibraryType.CSS)) continue;
                    this.writeCssInclude(request, lib3.getIncludePath(LibraryType.CSS), out, this.getIncludePath(request, lib3, LibraryType.CSS, minify), isDebug);
                    for (ClientLibrary emb : lib3.getEmbedded(LibraryType.CSS).values()) {
                        this.isIncluded(request, emb.getIncludePath(LibraryType.CSS));
                    }
                }
            }
            if (this.enableTiming) {
                this.internalWriteJsInclude(request, out, null, null, new String[]{this.clientMgrCategory});
            }
            if (reqType == null || reqType == LibraryType.JS) {
                for (ClientLibrary lib2 : libs.values()) {
                    if (!lib2.getTypes().contains((Object)LibraryType.JS)) continue;
                    this.writeJsInclude(request, lib2.getIncludePath(LibraryType.JS), out, this.getIncludePath(request, lib2, LibraryType.JS, minify), this.enableTiming, isDebug);
                    for (ClientLibrary emb : lib2.getEmbedded(LibraryType.JS).values()) {
                        this.isIncluded(request, emb.getIncludePath(LibraryType.JS));
                    }
                }
            }
        }
    }

    private String getIncludePath(SlingHttpServletRequest request, ClientLibrary lib, LibraryType type, boolean minify) {
        String path = lib.getIncludePath(type, minify);
        if (lib.allowProxy() && (path.startsWith("/libs/") || path.startsWith("/apps/"))) {
            path = "/etc.clientlibs" + path.substring(5);
        } else if (request.getResourceResolver().getResource(lib.getPath()) == null) {
            path = null;
        }
        return path;
    }

    private void writeURLInfo(SlingHttpServletRequest request, Writer out, boolean dynamic) throws IOException {
        if (this.getIncludedSet(request).size() <= 1) {
            RequestPathInfo info = request.getRequestPathInfo();
            String path = StringUtils.removeEnd((String)info.getResourcePath(), (String)"/jcr:content");
            String systemId = StringUtils.defaultIfEmpty((String)this.repository.getDescriptor("crx.cluster.id"), (String)this.repository.getDescriptor("crx.repository.systemid"));
            out.write("<script type=\"text/javascript\">");
            out.write("CQURLInfo=");
            JSONWriter w = new JSONWriter(out);
            try {
                w.object();
                if (StringUtils.isNotBlank((String)request.getContextPath())) {
                    w.key("contextPath").value((Object)request.getContextPath());
                }
                if (StringUtils.isNotBlank((String)path)) {
                    w.key("requestPath").value((Object)path);
                }
                if (StringUtils.isNotBlank((String)info.getSelectorString())) {
                    w.key("selectorString").value((Object)info.getSelectorString());
                }
                if (StringUtils.isNotBlank((String)info.getExtension())) {
                    w.key("extension").value((Object)info.getExtension());
                }
                if (StringUtils.isNotBlank((String)info.getSuffix())) {
                    w.key("suffix").value((Object)info.getSuffix());
                }
                w.key("selectors").array();
                for (String s : info.getSelectors()) {
                    w.value((Object)s);
                }
                w.endArray();
                w.key("systemId").value((Object)systemId);
                w.key("runModes").value((Object)StringUtils.join((Collection)this.settingsService.getRunModes(), (String)","));
                w.endObject();
            }
            catch (JSONException e) {
                IOException io = new IOException("Error while creating CQURLInfo");
                io.initCause((Throwable)e);
                throw io;
            }
            out.write(";");
            out.write("</script>\n");
        }
    }

    @Override
    public /* varargs */ void writeJsInclude(SlingHttpServletRequest request, Writer out, String ... categories) throws IOException {
        this.internalWriteIncludes(request, out, null, this.getDefaultThemeName(request), LibraryType.JS, categories);
        try {
            String customJsPath;
            ResourceResolver resolver = request.getResourceResolver();
            Node node = (Node)request.getResource().adaptTo(Node.class);
            if (node != null && node.hasProperty("customJavaScriptPath") && (customJsPath = node.getProperty("customJavaScriptPath").getString()) != null && customJsPath.length() > 0 && resolver.getResource(customJsPath) != null) {
                this.writeJsInclude(request, customJsPath, out, customJsPath, this.enableTiming, this.debugClientLibs(request));
            }
        }
        catch (RepositoryException e) {
            log.error("Error during include custom js for {}: {}", (Object)request.getResource().getPath(), (Object)e.toString());
        }
    }

    @Override
    public /* varargs */ void writeJsInclude(SlingHttpServletRequest request, Writer out, boolean themed, String ... categories) throws IOException {
        String themeName = themed ? this.getDefaultThemeName(request) : null;
        this.internalWriteIncludes(request, out, themed, themeName, LibraryType.JS, categories);
        try {
            String customJsPath;
            ResourceResolver resolver = request.getResourceResolver();
            Node node = (Node)request.getResource().adaptTo(Node.class);
            if (node != null && node.hasProperty("customJavaScriptPath") && (customJsPath = node.getProperty("customJavaScriptPath").getString()) != null && customJsPath.length() > 0 && resolver.getResource(customJsPath) != null) {
                this.writeJsInclude(request, customJsPath, out, customJsPath, this.enableTiming, this.debugClientLibs(request));
            }
        }
        catch (RepositoryException e) {
            log.error("Error during include custom js for {}: {}", (Object)request.getResource().getPath(), (Object)e.toString());
        }
    }

    @Override
    public /* varargs */ void writeCssInclude(SlingHttpServletRequest request, Writer out, String ... categories) throws IOException {
        this.internalWriteIncludes(request, out, null, this.getDefaultThemeName(request), LibraryType.CSS, categories);
    }

    @Override
    public /* varargs */ void writeCssInclude(SlingHttpServletRequest request, Writer out, boolean themed, String ... categories) throws IOException {
        String themeName = themed ? this.getDefaultThemeName(request) : null;
        this.internalWriteIncludes(request, out, themed, themeName, LibraryType.CSS, categories);
    }

    @Override
    public /* varargs */ void writeThemeInclude(SlingHttpServletRequest request, Writer out, String ... categories) throws IOException {
        String themeName = this.getDefaultThemeName(request);
        this.internalWriteIncludes(request, out, true, themeName, LibraryType.JS, categories);
        this.internalWriteIncludes(request, out, null, themeName, LibraryType.CSS, categories);
    }

    private void writeDebugConsole(SlingHttpServletRequest request, Writer out) throws IOException {
        if (this.showDebugConsole(request)) {
            this.writeJsInclude(request, this.firebugLiteJSPath, out, this.firebugLiteJSPath, false, this.debugClientLibs(request));
            if (this.debugInitJS != null && this.debugInitJS.length() > 0 && !this.isIncluded(request, this.debugInitJS)) {
                out.write("<script type=\"text/javascript\">\n");
                out.write(this.debugInitJS + "\n");
                out.write("</script>\n");
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void internalWriteJsInclude(SlingHttpServletRequest request, Writer out, Boolean themed, String themeName, String[] categories) throws IOException {
        Map<String, ClientLibrary> libs;
        this.writeDebugConsole(request, out);
        this.lock.readLock().lock();
        try {
            libs = this.lockedGetLibs(categories, LibraryType.JS, themed, themeName, true);
        }
        finally {
            this.lock.readLock().unlock();
        }
        boolean isDebug = this.debugClientLibs(request);
        boolean minify = this.enableMinify && !isDebug;
        for (ClientLibrary lib : libs.values()) {
            this.writeJsInclude(request, lib.getIncludePath(LibraryType.JS), out, this.getIncludePath(request, lib, LibraryType.JS, minify), this.enableTiming, isDebug);
            for (ClientLibrary emb : lib.getEmbedded(LibraryType.JS).values()) {
                this.isIncluded(request, emb.getIncludePath(LibraryType.JS));
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private /* varargs */ void internalWriteCssInclude(SlingHttpServletRequest request, Writer out, Boolean themed, String themeName, String ... categories) throws IOException {
        Map<String, ClientLibrary> libs;
        this.lock.readLock().lock();
        try {
            libs = this.lockedGetLibs(categories, LibraryType.CSS, themed, themeName, true);
        }
        finally {
            this.lock.readLock().unlock();
        }
        for (ClientLibrary lib : libs.values()) {
            this.writeCssInclude(request, out, lib.getIncludePath(LibraryType.CSS));
            for (ClientLibrary emb : lib.getEmbedded(LibraryType.CSS).values()) {
                this.isIncluded(request, emb.getIncludePath(LibraryType.CSS));
            }
        }
    }

    @Override
    public HtmlLibrary getLibrary(SlingHttpServletRequest request) {
        LibraryType type = LibraryType.fromRequest(request);
        if (type == null) {
            log.error("Unable to determine library type for request.");
            return null;
        }
        return this.getLibrary(type, request.getResource().getPath());
    }

    @Override
    public HtmlLibrary getLibrary(LibraryType type, String path) {
        return this.getLibrary(type, path, false);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected HtmlLibrary getLibrary(LibraryType type, String path, boolean suppressErrors) {
        this.lock.readLock().lock();
        try {
            this.assertResolved();
            ClientLibraryImpl e = this.cache.getLibrary(path);
            if (e == null) {
                if (!suppressErrors) {
                    log.warn("No library configured at {}", (Object)path);
                }
                HtmlLibrary htmlLibrary = null;
                return htmlLibrary;
            }
            FileBundle bundle = e.getBundle(type);
            if (bundle == null) {
                if (!suppressErrors) {
                    log.warn("Library at {} does not provide type {}", (Object)path, (Object)type);
                }
                HtmlLibrary htmlLibrary = null;
                return htmlLibrary;
            }
            LinkedList<FileBundle> bundles = new LinkedList<FileBundle>();
            for (ClientLibraryImpl lib22 : e.getEmbedded(type).values()) {
                FileBundle embedBundle = lib22.getBundle(type);
                if (embedBundle == null) continue;
                bundles.add(embedBundle);
            }
            FileBundle[] embedded = bundles.isEmpty() ? null : bundles.toArray(new FileBundle[bundles.size()]);
            HtmlLibraryImpl lib22 = new HtmlLibraryImpl(this, e, type, bundle, embedded);
            return lib22;
        }
        finally {
            this.lock.readLock().unlock();
        }
    }

    @Override
    public boolean isMinifyEnabled() {
        return this.enableMinify;
    }

    @Override
    public boolean isDebugEnabled() {
        return this.enableDebug;
    }

    @Override
    public boolean isGzipEnabled() {
        return this.enableGzip;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public Collection<ClientLibrary> getLibraries(String[] categories, LibraryType type, boolean ignoreThemed, boolean transitive) {
        this.lock.readLock().lock();
        try {
            Collection<ClientLibrary> collection = this.lockedGetLibs(categories, type, ignoreThemed ? Boolean.valueOf(false) : null, null, transitive).values();
            return collection;
        }
        finally {
            this.lock.readLock().unlock();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public Collection<ClientLibrary> getThemeLibraries(String[] categories, LibraryType type, String themeName, boolean transitive) {
        this.lock.readLock().lock();
        try {
            Collection<ClientLibrary> collection = this.lockedGetLibs(categories, type, true, themeName, transitive).values();
            return collection;
        }
        finally {
            this.lock.readLock().unlock();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public Map<String, ClientLibrary> getLibraries() {
        this.lock.readLock().lock();
        try {
            this.assertResolved();
            Map<String, ClientLibrary> map = this.cache.getLibraries();
            return map;
        }
        finally {
            this.lock.readLock().unlock();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected Boolean proxyAllowed(String relPath, String[] searchPath) {
        if (relPath.startsWith("/")) {
            relPath = relPath.substring(1);
        }
        if (searchPath == null || searchPath.length == 0) {
            searchPath = new String[]{"/"};
        }
        this.lock.readLock().lock();
        try {
            this.assertResolved();
            for (String s : searchPath) {
                ClientLibraryImpl e = this.cache.getLibrary(s + relPath);
                if (e == null) continue;
                Boolean bl = e.allowProxy();
                return bl;
            }
            String[] arr$ = null;
            return arr$;
        }
        finally {
            this.lock.readLock().unlock();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public void onEvent(EventIterator iter) {
        HashSet<String> modified;
        HashSet<String> paths = new HashSet<String>();
        HashSet<String> added = new HashSet<String>();
        while (iter.hasNext()) {
            Event e = iter.nextEvent();
            try {
                String path = e.getPath();
                if (e.getType() == 4 || e.getType() == 16 || e.getType() == 8) {
                    path = Text.getRelativeParent((String)path, (int)1);
                }
                if (path.endsWith("/jcr:content")) {
                    path = Text.getRelativeParent((String)path, (int)1);
                }
                paths.add(path);
                if (e.getType() == 1) {
                    added.add(path);
                } else if (e.getType() == 2 && this.cache.isAncestor(path)) {
                    this.isResolved = false;
                    this.isLoaded = false;
                    log.info("Invalidating client library cache due to (re)move of {}", (Object)path);
                    return;
                }
                if (path.startsWith("/apps/")) {
                    path = "/libs/" + path.substring(6);
                }
                paths.add(path);
                if (e.getType() != 1) continue;
                added.add(path);
            }
            catch (RepositoryException e1) {}
        }
        modified = new HashSet<String>();
        Session session = null;
        this.lock.readLock().lock();
        try {
            session = this.getServiceSession();
            for (String p2 : paths) {
                Set<String> depPaths = this.cache.getLibsPathsFromSource(p2);
                if (depPaths == null) continue;
                modified.addAll(depPaths);
            }
            Iterator i$ = added.iterator();
            while (i$.hasNext()) {
                String p2;
                p2 = (String)i$.next();
                try {
                    ClientLibrary lib;
                    Node n;
                    int idx = p2.lastIndexOf(47);
                    String name = p2.substring(idx + 1);
                    if ("js.txt".equals(name) || "css.txt".equals(name)) {
                        p2 = p2.substring(0, idx);
                    }
                    if ((n = (Node)session.getItem(p2)).isNodeType("cq:ClientLibraryFolder")) {
                        modified.add(p2);
                        continue;
                    }
                    if (!n.isNodeType("{http://www.jcp.org/jcr/nt/1.0}file") || (lib = this.cache.getClosesLib(p2)) == null) continue;
                    modified.add(lib.getPath());
                }
                catch (RepositoryException e) {}
            }
            added.clear();
            added.addAll(modified);
            for (String p2 : added) {
                ClientLibraryImpl lib = this.cache.getLibrary(p2);
                if (lib == null) continue;
                modified.addAll(lib.getEmbedders());
            }
        }
        catch (RepositoryException e) {
            log.error("error while accessing the repository", (Throwable)e);
        }
        finally {
            this.lock.readLock().unlock();
            if (session != null) {
                session.logout();
            }
        }
        if (!modified.isEmpty()) {
            this.lock.writeLock().lock();
            try {
                for (String p2 : modified) {
                    this.invalidate(p2);
                }
                this.cache.rebuildAncestorPaths();
            }
            finally {
                this.lock.writeLock().unlock();
            }
        }
    }

    private boolean debugClientLibs(SlingHttpServletRequest request) {
        return this.enableDebug || "true".equals(request.getParameter("debugClientLibs"));
    }

    private boolean showDebugConsole(SlingHttpServletRequest request) {
        return this.enableDebugConsole || "true".equals(request.getParameter("debugConsole"));
    }

    private void writeJsInclude(SlingHttpServletRequest request, String rawPath, Writer out, String path, boolean timing, boolean isDebug) throws IOException {
        if (this.isIncluded(request, rawPath)) {
            return;
        }
        if (path == null) {
            return;
        }
        out.write("<script type=\"text/javascript\" src=\"");
        out.write(request.getContextPath() + path);
        if (isDebug) {
            out.write("?debug=true");
        }
        out.write("\"></script>\n");
        if (timing) {
            out.write("<script type=\"text/javascript\">\n");
            out.write("  GraniteTiming.stamp('loaded " + request.getContextPath() + path + "');\n");
            out.write("</script>\n");
        }
    }

    private void writeCssInclude(SlingHttpServletRequest request, String rawPath, Writer out, String path, boolean isDebug) throws IOException {
        if (this.isIncluded(request, rawPath)) {
            return;
        }
        if (path == null) {
            return;
        }
        String end = HtmlLibraryManagerImpl.isXHTMLRequest(request) ? "/>\n" : ">\n";
        out.write("<link rel=\"stylesheet\" href=\"");
        out.write(request.getContextPath() + path);
        if (isDebug) {
            out.write("?debug=true");
        }
        out.write("\" type=\"text/css\"");
        out.write(end);
    }

    private static boolean isXHTMLRequest(SlingHttpServletRequest request) {
        try {
            Object name;
            Object doctype = request.getAttribute("com.day.cq.widget.Doctype");
            if (doctype != null && (name = doctype.getClass().getMethod("name", new Class[0]).invoke(doctype, new Object[0])) != null) {
                return name.toString().startsWith("XHTML_");
            }
        }
        catch (Exception e) {
            // empty catch block
        }
        return false;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void assertLoaded() {
        block6 : {
            if (!this.isLoaded) {
                this.lock.readLock().unlock();
                this.lock.writeLock().lock();
                try {
                    if (this.isLoaded) break block6;
                    try {
                        this.loadLibs();
                        this.isLoaded = true;
                    }
                    catch (RepositoryException e) {
                        log.error("Cannot load js libraries", (Throwable)e);
                    }
                }
                finally {
                    this.lock.readLock().lock();
                    this.lock.writeLock().unlock();
                }
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void assertResolved() {
        this.assertLoaded();
        if (!this.isResolved) {
            this.lock.readLock().unlock();
            this.lock.writeLock().lock();
            try {
                if (!this.isResolved) {
                    this.cache.resolveLibraries();
                    this.isResolved = true;
                }
            }
            finally {
                this.lock.readLock().lock();
                this.lock.writeLock().unlock();
            }
        }
    }

    private Map<String, ClientLibrary> lockedGetLibs(String[] categories, LibraryType type, Boolean themed, String themeName, boolean transitive) {
        this.assertResolved();
        if ("".equals(themeName)) {
            themeName = this.defaultThemeName;
        }
        LinkedHashMap candidates = new LinkedHashMap<String, ClientLibrary>();
        for (ClientLibraryImpl lib : this.cache.getLibsByCategory(categories, null).values()) {
            if (transitive) {
                candidates.putAll(lib.getDependencies(true));
            }
            candidates.put(lib.getPath(), lib);
        }
        HashSet<String> embedded = new HashSet<String>();
        Iterator iter = candidates.values().iterator();
        while (iter.hasNext()) {
            ClientLibrary lib2 = (ClientLibrary)iter.next();
            if (type != null && !lib2.getTypes().contains((Object)type)) {
                iter.remove();
                continue;
            }
            if (themed != null && !themed.booleanValue() && lib2.getThemeName() != null) {
                iter.remove();
                continue;
            }
            if (themed != null && themed.booleanValue() && lib2.getThemeName() == null) {
                iter.remove();
                continue;
            }
            embedded.addAll(lib2.getEmbedded(null).keySet());
        }
        candidates.keySet().removeAll(embedded);
        if (themed == null || themed.booleanValue()) {
            LinkedHashMap<String, ClientLibrary> ret = new LinkedHashMap<String, ClientLibrary>();
            Iterator<ClientLibrary> iter2 = candidates.values().iterator();
            while (iter2.hasNext()) {
                ClientLibrary lib32 = iter2.next();
                if (lib32.getThemeName() != null) continue;
                ret.put(lib32.getPath(), lib32);
                iter2.remove();
            }
            if (themeName != null && themeName.equals(this.defaultThemeName)) {
                ret.putAll(candidates);
            } else {
                for (ClientLibrary lib32 : candidates.values()) {
                    if (!this.defaultThemeName.equals(lib32.getThemeName())) continue;
                    ret.put(lib32.getThemeLibId(), lib32);
                }
                for (ClientLibrary lib32 : candidates.values()) {
                    if (this.defaultThemeName.equals(lib32.getThemeName())) continue;
                    ret.put(lib32.getThemeLibId(), lib32);
                }
            }
            candidates = ret;
        }
        return candidates;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void loadLibs() throws RepositoryException {
        this.cache.clear();
        Session session = null;
        try {
            session = this.getServiceSession();
            String queryString = "/jcr:root//element(*, cq:ClientLibraryFolder)";
            Query query = session.getWorkspace().getQueryManager().createQuery(queryString, "xpath");
            QueryResult result = query.execute();
            NodeIterator itr = result.getNodes();
            while (itr.hasNext()) {
                Node n = itr.nextNode();
                if (this.isPathAllowed(n.getPath())) {
                    this.loadLibrary(n, false);
                    continue;
                }
                log.debug("Client Library {} excluded because it is not in an allowed path.", (Object)n.getPath());
            }
            this.cache.rebuildAncestorPaths();
        }
        finally {
            if (session != null) {
                session.logout();
            }
        }
        this.cache.logStatus();
    }

    private boolean isPathAllowed(String path) {
        for (String allowedPath : this.allowedPaths) {
            if ("".equals(allowedPath) || !Text.isDescendantOrEqual((String)allowedPath, (String)path)) continue;
            return true;
        }
        return false;
    }

    private void loadLibrary(Node n, boolean forceRecreate) throws RepositoryException {
        String longCacheKey;
        JcrPropertyMap props = new JcrPropertyMap(n);
        String path = n.getPath();
        String ext = "";
        boolean isLegacy = false;
        int idx = path.lastIndexOf(46);
        if (idx > 0) {
            ext = path.substring(idx + 1);
        }
        if (ext.equals("js") || ext.equals("css")) {
            isLegacy = true;
        } else {
            ext = "";
        }
        String type = (String)props.get("type", (Object)ext);
        EnumSet<LibraryType> types = EnumSet.noneOf(LibraryType.class);
        if (n.hasNode("js.txt") || "js".equals(type)) {
            types.add(LibraryType.JS);
        }
        if (n.hasNode("css.txt") || "css".equals(type)) {
            types.add(LibraryType.CSS);
        }
        if (types.isEmpty()) {
            log.debug("Client Library {} does not specify a type.", (Object)path);
        }
        String theme = null;
        String libId = path;
        if ("themes".equals(n.getParent().getName())) {
            theme = n.getName();
            libId = n.getParent().getPath();
        }
        longCacheKey = (longCacheKey = (String)props.get("longCacheKey", String.class)) == null ? this.longCacheConfig.getCacheKey(path) : this.longCacheConfig.formatCacheKey(longCacheKey);
        log.debug("Long Cache key for {} is {} ", (Object)path, (Object)longCacheKey);
        ClientLibraryImpl entry = new ClientLibraryImpl.Builder(path).withCategories((String[])props.get("categories", (Object)EMPTY_STRING_ARRAY)).withDependencies((String[])props.get("dependencies", (Object)EMPTY_STRING_ARRAY)).withEmbeds((String[])props.get("embed", (Object)EMPTY_STRING_ARRAY)).withChannels((String[])props.get("channels", (Object)EMPTY_STRING_ARRAY)).withIsLegacy(isLegacy).withThemeName(theme).withLibId(libId).withAllowProxy((Boolean)props.get("allowProxy", (Object)false)).withCacheKey(longCacheKey).withCssProcessors(ProcessorConfig.parse((String[])props.get("cssProcessor", String[].class), this.cssDefaultProcessorConfig)).withJsProcessors(ProcessorConfig.parse((String[])props.get("jsProcessor", String[].class), this.jsDefaultProcessorConfig)).build();
        for (LibraryType t : types) {
            FileBundle bundle = isLegacy ? new FileBundle(n, "includes.txt", "/files", this.compilerProvider) : new FileBundle(n, t.name().toLowerCase() + ".txt", "", this.compilerProvider);
            bundle.setDirty(forceRecreate);
            entry.addBundle(t, bundle);
        }
        this.cache.add(entry);
        if (theme == null) {
            log.info("detected {} library: {}, sourced from {} files.", new Object[]{types, path, entry.getSourcePaths().size()});
        } else {
            log.info("detected {} theme library: {}, sourced from {} files.", new Object[]{types, path, entry.getSourcePaths().size()});
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void invalidate(String path) {
        this.cache.remove(path);
        Session session = null;
        try {
            Node node;
            session = this.getServiceSession();
            if (session.itemExists(path) && (node = (Node)session.getItem(path)).isNodeType("cq:ClientLibraryFolder")) {
                this.loadLibrary(node, true);
            }
        }
        catch (RepositoryException e1) {
            log.error("Error while loading library {}", (Object)path);
        }
        finally {
            if (session != null) {
                session.logout();
            }
        }
        this.isResolved = false;
        this.sendInvalidateEvent(path);
    }

    private void sendInvalidateEvent(String libraryPath) {
        Hashtable<String, String> props = new Hashtable<String, String>();
        props.put("path", libraryPath);
        org.osgi.service.event.Event event = new org.osgi.service.event.Event("com/adobe/granite/ui/librarymanager/INVALIDATED", props);
        this.eventAdmin.postEvent(event);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected long getLastModified(HtmlLibraryImpl lib, boolean minified) {
        this.lock.readLock().lock();
        Session session = null;
        try {
            session = this.getServiceSession();
            long l = this.getOrCreateCacheNode(session, lib, minified).getProperty("jcr:lastModified").getLong();
            return l;
        }
        catch (RepositoryException e) {
            log.error("Error occurred while reading the last modified date of the generated library");
            long l = -1;
            return l;
        }
        finally {
            this.lock.readLock().unlock();
            if (session != null) {
                session.logout();
            }
        }
    }

    protected void send(HtmlLibraryImpl lib, SlingHttpServletRequest request, SlingHttpServletResponse response, boolean minified) throws IOException {
        if (this.maxAge >= 0) {
            response.setHeader("Cache-Control", "max-age=" + this.maxAge + ", public");
        }
        if (HtmlLibraryManagerImpl.unmodified((HttpServletRequest)request, lib.getLastModified(minified))) {
            response.setStatus(304);
        } else {
            this.send(lib, (HttpServletResponse)response, this.isGzipEnabled(), minified);
        }
    }

    private static boolean unmodified(HttpServletRequest request, long modifTime) {
        if (modifTime > 0) {
            long modTime = modifTime / 1000;
            long ims = request.getDateHeader("If-Modified-Since") / 1000;
            return modTime <= ims;
        }
        return false;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void send(HtmlLibraryImpl lib, HttpServletResponse response, boolean gzip, boolean minified) throws IOException {
        block11 : {
            InputStream is = null;
            Binary binary = null;
            Session session = null;
            try {
                session = this.getServiceSession();
                this.lock.readLock().lock();
                try {
                    Node node = this.getOrCreateCacheNode(session, lib, minified);
                    response.setDateHeader("Last-Modified", node.getProperty("jcr:lastModified").getLong());
                    response.setContentType(node.getProperty("jcr:mimeType").getString());
                    response.setCharacterEncoding("utf-8");
                    binary = node.getProperty("jcr:data").getBinary();
                    is = binary.getStream();
                }
                finally {
                    this.lock.readLock().unlock();
                }
                if (gzip) {
                    response.setHeader("Content-Encoding", "gzip");
                    GZIPOutputStream gzipOut = new GZIPOutputStream((OutputStream)response.getOutputStream());
                    IOUtils.copy((InputStream)is, (OutputStream)gzipOut);
                    gzipOut.finish();
                    break block11;
                }
                IOUtils.copy((InputStream)is, (OutputStream)response.getOutputStream());
            }
            catch (RepositoryException e) {
                log.error("Error while sending cached library: {}", (Object)e.toString());
                throw new IOException("Error while sending cached library: " + (Object)e);
            }
            finally {
                IOUtils.closeQuietly((InputStream)is);
                if (binary != null) {
                    binary.dispose();
                }
                if (session != null) {
                    session.logout();
                }
            }
        }
    }

    protected InputStream getInputStream(HtmlLibraryImpl lib, boolean minified) throws IOException {
        this.lock.readLock().lock();
        Session session = null;
        try {
            session = this.getServiceSession();
            InputStream inputStream = this.getOrCreateCacheNode(session, lib, minified).getProperty("jcr:data").getBinary().getStream();
            return inputStream;
        }
        catch (RepositoryException e) {
            log.error("Cannot read input stream", (Throwable)e);
            throw new IOException("Error while reading cached library: " + (Object)e);
        }
        finally {
            this.lock.readLock().unlock();
            if (session != null) {
                session.logout();
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private Node getOrCreateCacheNode(Session session, HtmlLibraryImpl lib, boolean minified) throws RepositoryException {
        try {
            Node node;
            block18 : {
                String path = WRITE_LOCATION + lib.getPath(minified) + "/" + "jcr:content";
                if (session.nodeExists(path)) {
                    node = session.getNode(path);
                } else {
                    String parentPath = Text.getRelativeParent((String)path, (int)2);
                    String name = lib.getName(minified);
                    this.lock.readLock().unlock();
                    this.lock.writeLock().lock();
                    try {
                        String relativeFilePath = lib.getPath(minified).substring(1);
                        Node baseNode = session.getNode(WRITE_LOCATION);
                        String relativePath = Text.getRelativeParent((String)relativeFilePath, (int)1);
                        Node tmpLocation = JcrUtils.getOrCreateByPath((Node)baseNode, (String)relativePath, (boolean)false, (String)"sling:Folder", (String)"sling:Folder", (boolean)true);
                        if (tmpLocation.hasNode(name)) {
                            node = tmpLocation.getNode(name + "/" + "jcr:content");
                            break block18;
                        }
                        Node fileNode = tmpLocation.addNode(name, "{http://www.jcp.org/jcr/nt/1.0}file");
                        node = fileNode.addNode("jcr:content", "{http://www.jcp.org/jcr/nt/1.0}resource");
                        node.setProperty("jcr:data", node.getSession().getValueFactory().createBinary((InputStream)new ByteArrayInputStream(new byte[0])));
                        node.setProperty("jcr:lastModified", 0);
                        node.setProperty("jcr:mimeType", lib.getType().contentType);
                        session.save();
                    }
                    finally {
                        this.lock.readLock().lock();
                        this.lock.writeLock().unlock();
                    }
                }
            }
            if (lib.getBundle().isDirty() || lib.getBundleLastModified() > node.getProperty("jcr:lastModified").getLong()) {
                this.lock.readLock().unlock();
                this.lock.writeLock().lock();
                ClientLibraryImpl entry = null;
                try {
                    entry = this.cache.getLibrary(lib.getLibraryPath());
                    if (entry != null) {
                        this.cache.removeSourcePaths(entry);
                        entry.invalidateSourcePaths();
                    }
                    this.update(lib, node, minified);
                    if (entry != null) {
                        this.cache.addSourcePaths(entry);
                    }
                    session.save();
                }
                catch (RepositoryException e) {
                    this.invalidate(lib.getLibraryPath());
                    if (entry != null) {
                        Map<String, ClientLibraryImpl> embedders = this.cache.getEmbeddersByCategory(entry.getCategories(), null);
                        for (String embedder : embedders.keySet()) {
                            this.invalidate(embedder);
                        }
                    }
                    throw e;
                }
                finally {
                    this.lock.readLock().lock();
                    this.lock.writeLock().unlock();
                }
            }
            return node;
        }
        catch (RepositoryException e) {
            log.error("Error while saving changes: {}. reverting.", (Object)e.toString());
            throw e;
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void update(HtmlLibraryImpl lib, Node node, boolean minified) throws RepositoryException {
        ByteArrayInputStream in;
        Object[] arrobject = new Object[3];
        arrobject[0] = lib.getType();
        arrobject[1] = lib.getLibraryPath();
        arrobject[2] = minified ? " (minified)" : "";
        log.info("Start building {} library: {}{}", arrobject);
        Session session = node.getSession();
        LinkedList<ScriptResource> resources = new LinkedList<ScriptResource>();
        FileBundle[] embedded = lib.getEmbedded();
        if (embedded != null && embedded.length > 0) {
            for (FileBundle bundle : embedded) {
                bundle.addResources(session, this.compilerProvider, resources);
            }
        }
        lib.getBundle().addResources(session, this.compilerProvider, resources);
        long lastMod = lib.getBundleLastModified();
        AbstractBuilder builder = lib.getType() == LibraryType.JS ? new JsFileBuilder(lib.getLibraryPath()) : new CssFileBuilder(lib.getLibraryPath(), session, this.maxDataUriSize);
        builder.setDoMinify(minified);
        builder.setProcessorProvider(this.processorProvider);
        builder.setProcessorConfigs(lib.getProcessorConfigs());
        try {
            String source = builder.build(resources);
            byte[] bytes = source.getBytes("utf-8");
            in = new ByteArrayInputStream(bytes);
        }
        catch (Exception e) {
            log.error("Error during assembly of library.", (Throwable)e);
            throw new RepositoryException("Error during assembly of " + lib.getPath(), (Throwable)e);
        }
        try {
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(lastMod);
            node.setProperty("jcr:data", (InputStream)in);
            node.setProperty("jcr:lastModified", cal);
            node.setProperty("jcr:mimeType", lib.getType().contentType);
            node.setProperty("jcr:encoding", "utf-8");
        }
        finally {
            IOUtils.closeQuietly((InputStream)in);
        }
        lib.getBundle().setDirty(false);
        log.info("finished building library {}", (Object)lib.getPath());
    }

    private String getDefaultThemeName(SlingHttpServletRequest request) {
        String theme = request.getParameter("forceTheme");
        if (theme == null) {
            theme = this.defaultUserThemeName;
        }
        return theme;
    }

    private Set<String> getIncludedSet(SlingHttpServletRequest request) {
        HashSet set = (HashSet)request.getAttribute(INCLUDED_SET_ATTR_NAME);
        if (set == null) {
            set = new HashSet();
            request.setAttribute(INCLUDED_SET_ATTR_NAME, set);
        }
        return set;
    }

    private boolean isIncluded(SlingHttpServletRequest request, String path) {
        if (path == null) {
            return true;
        }
        Set<String> set = this.getIncludedSet(request);
        if (set.contains(path)) {
            return true;
        }
        set.add(path);
        return false;
    }

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

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

    protected void bindSettingsService(SlingSettingsService slingSettingsService) {
        this.settingsService = slingSettingsService;
    }

    protected void unbindSettingsService(SlingSettingsService slingSettingsService) {
        if (this.settingsService == slingSettingsService) {
            this.settingsService = null;
        }
    }

    protected void bindEventAdmin(EventAdmin eventAdmin) {
        this.eventAdmin = eventAdmin;
    }

    protected void unbindEventAdmin(EventAdmin eventAdmin) {
        if (this.eventAdmin == eventAdmin) {
            this.eventAdmin = null;
        }
    }

    protected void bindCompilerProvider(CompilerProvider compilerProvider) {
        this.compilerProvider = compilerProvider;
    }

    protected void unbindCompilerProvider(CompilerProvider compilerProvider) {
        if (this.compilerProvider == compilerProvider) {
            this.compilerProvider = null;
        }
    }

    protected void bindProcessorProvider(ProcessorProvider processorProvider) {
        this.processorProvider = processorProvider;
    }

    protected void unbindProcessorProvider(ProcessorProvider processorProvider) {
        if (this.processorProvider == processorProvider) {
            this.processorProvider = null;
        }
    }
}