LiveRelationshipManagerImpl.java 44.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.api.PageManager
 *  com.day.cq.wcm.api.WCMException
 *  com.day.cq.wcm.msm.api.Blueprint
 *  com.day.cq.wcm.msm.api.BlueprintManager
 *  com.day.cq.wcm.msm.api.BlueprintManagerFactory
 *  com.day.cq.wcm.msm.api.LiveCopy
 *  com.day.cq.wcm.msm.api.LiveRelationship
 *  com.day.cq.wcm.msm.api.LiveRelationshipManager
 *  com.day.cq.wcm.msm.api.LiveStatus
 *  com.day.cq.wcm.msm.api.RolloutConfig
 *  com.day.cq.wcm.msm.api.RolloutManager
 *  com.day.cq.wcm.msm.api.RolloutManager$Trigger
 *  com.day.text.Text
 *  javax.jcr.ItemNotFoundException
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RangeIterator
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.ValueFactory
 *  org.apache.commons.collections.IteratorUtils
 *  org.apache.commons.collections.ResettableIterator
 *  org.apache.commons.collections.Transformer
 *  org.apache.commons.collections.map.ListOrderedMap
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.commons.iterator.RangeIteratorAdapter
 *  org.apache.sling.api.adapter.AdapterFactory
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.NonExistingResource
 *  org.apache.sling.api.resource.PersistenceException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.SyntheticResource
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.wcm.msm.impl;

import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.api.WCMException;
import com.day.cq.wcm.msm.api.Blueprint;
import com.day.cq.wcm.msm.api.BlueprintManager;
import com.day.cq.wcm.msm.api.BlueprintManagerFactory;
import com.day.cq.wcm.msm.api.LiveCopy;
import com.day.cq.wcm.msm.api.LiveRelationship;
import com.day.cq.wcm.msm.api.LiveRelationshipManager;
import com.day.cq.wcm.msm.api.LiveStatus;
import com.day.cq.wcm.msm.api.RolloutConfig;
import com.day.cq.wcm.msm.api.RolloutManager;
import com.day.cq.wcm.msm.impl.LiveCopyManagerImpl;
import com.day.cq.wcm.msm.impl.LiveCopyServiceImpl;
import com.day.cq.wcm.msm.impl.LiveRelationshipImpl;
import com.day.cq.wcm.msm.impl.LiveStatusImpl;
import com.day.cq.wcm.msm.impl.StatusUtil;
import com.day.cq.wcm.msm.impl.Utils;
import com.day.text.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RangeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import org.apache.commons.collections.IteratorUtils;
import org.apache.commons.collections.ResettableIterator;
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.commons.iterator.RangeIteratorAdapter;
import org.apache.sling.api.adapter.AdapterFactory;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.NonExistingResource;
import org.apache.sling.api.resource.PersistenceException;
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.api.resource.ResourceUtil;
import org.apache.sling.api.resource.SyntheticResource;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(label="%liverelationshipmgr.name", description="%liverelationshipmgr.description", metatype=1)
@Service
public class LiveRelationshipManagerImpl
implements LiveRelationshipManager,
AdapterFactory {
    private static final Logger log = LoggerFactory.getLogger(LiveRelationshipManagerImpl.class);
    public static final String PATTERN_ALL = ".*";
    static final String DEFAULT_ROLLOUT_CONFIG = "/etc/msm/rolloutconfigs/default";
    public static final String RT_GHOST = "wcm/msm/components/ghost";
    @Reference
    private BlueprintManagerFactory blueprintManagerFactory = null;
    @Reference
    private ResourceResolverFactory resolverFactory = null;
    @Reference
    private LiveCopyServiceImpl liveCopyService = null;
    @org.apache.felix.scr.annotations.Property(name="adapters", propertyPrivate=1)
    public static final String[] ADAPTER_CLASSES = new String[]{LiveRelationshipManager.class.getName()};
    @org.apache.felix.scr.annotations.Property(name="adaptables", propertyPrivate=1)
    public static final String[] ADAPTABLE_CLASSES = new String[]{ResourceResolver.class.getName()};
    @org.apache.felix.scr.annotations.Property(value={"/etc/msm/rolloutconfigs/default"})
    static final String RELATIONS_DEFAULT_ROLLOUT_CONFIG = "liverelationshipmgr.relationsconfig.default";
    private static final String VERSION_QUERY = String.format("/jcr:root//element(*,%s)[%s/@%s='%%s' and %s/@%s='%%s'] order by @%s descending", "nt:version", "jcr:frozenNode", "cq:parentPath", "jcr:frozenNode", "cq:name", "jcr:created");
    private String defaultRolloutConfigPath;

    @Activate
    protected void activate(ComponentContext context) throws RepositoryException, WCMException, LoginException {
        Dictionary props = context.getProperties();
        this.defaultRolloutConfigPath = (String)props.get("liverelationshipmgr.relationsconfig.default");
    }

    public <AdapterType> AdapterType getAdapter(Object adaptable, Class<AdapterType> type) {
        if (LiveRelationshipManager.class.isAssignableFrom(type) && ResourceResolver.class.isInstance(adaptable)) {
            return (AdapterType)this;
        }
        return null;
    }

    public boolean hasLiveRelationship(Resource resource) {
        try {
            Node node = Utils.getWorkingNode((Node)resource.adaptTo(Node.class));
            return !this.isManuallyCreated(node);
        }
        catch (ItemNotFoundException ine) {
            return false;
        }
        catch (RepositoryException e) {
            log.error("Failed to access Node for Resource at {}:{}", (Object)resource.getPath(), (Object)e);
            return false;
        }
    }

    public RangeIterator getLiveRelationships(Resource source, String targetPathFilter, RolloutManager.Trigger triggerFilter) throws WCMException {
        try {
            return new LiveRelationshipIterator(source, this.liveCopyService, targetPathFilter, triggerFilter);
        }
        catch (RepositoryException e) {
            throw new WCMException((Throwable)e);
        }
    }

    public RangeIterator getChildren(LiveRelationship relationship, ResourceResolver resolver) throws WCMException {
        Resource source;
        ListOrderedMap merged = new ListOrderedMap();
        Resource target = resolver.getResource(relationship.getTargetPath());
        if (target != null) {
            Iterator<Resource> targetChildren = LiveRelationshipManagerImpl.pageToResourceIterator(target);
            while (targetChildren.hasNext()) {
                Resource child = targetChildren.next();
                LiveRelationship ship = this.getLiveRelationship(child, true);
                if (ship == null) {
                    log.debug("Found a Child of a shallow LiveCopy at {}, end roll-out for branch", (Object)child.getPath());
                    continue;
                }
                merged.put((Object)ship, (Object)ship.getSourcePath());
            }
        }
        if ((source = resolver.getResource(relationship.getSourcePath())) != null) {
            Iterator<Resource> srcChildren = LiveRelationshipManagerImpl.pageToResourceIterator(source);
            while (srcChildren.hasNext()) {
                Resource child = srcChildren.next();
                if (merged.containsValue((Object)child.getPath())) continue;
                String targetChildPath = relationship.getTargetPath().concat("/").concat(child.getName());
                Resource resource = resolver.getResource(targetChildPath);
                if (resource == null) {
                    NonExistingResource nonResource = new NonExistingResource(resolver, targetChildPath);
                    LiveRelationship ship = this.getLiveRelationship((Resource)nonResource, true);
                    if (ship == null) continue;
                    merged.put((Object)ship, (Object)child.getPath());
                    continue;
                }
                LiveRelationship ship = this.getLiveRelationship(resource, true);
                if (ship == null) {
                    log.debug("Found a child outside the Parent-LiveCopy at {}", (Object)resource.getPath());
                    continue;
                }
                log.debug("Found a child from {} to shadow current source {}", (Object)ship.getSourcePath(), (Object)child.getPath());
            }
        }
        return new RangeIteratorAdapter(merged.keySet().iterator(), (long)merged.size());
    }

    public LiveRelationship getLiveRelationship(Resource target, boolean advancedStatus) throws WCMException {
        String path = target.getPath();
        LiveCopyManagerImpl.LiveCopyImpl lc = null;
        try {
            lc = this.getContainingLiveCopy(target, target.getResourceResolver());
        }
        catch (RepositoryException e) {
            log.warn("Failed to access LiveCopy for {}", (Object)path);
        }
        if (lc != null) {
            String lcRoot = lc.getPath();
            String relPath = path.substring(lcRoot.length());
            LiveRelationship relation = this.buildRelationship(target.getResourceResolver(), lc, relPath, advancedStatus);
            log.debug("found relation for {}: {}", (Object)path, (Object)relation);
            return relation;
        }
        log.debug("no relation for {} found.", (Object)path);
        return null;
    }

    public /* varargs */ LiveRelationship establishRelationship(Page source, Page copy, boolean deep, boolean autoSave, RolloutConfig ... rolloutConfig) throws WCMException {
        Resource content = copy.getContentResource();
        if (content == null) {
            log.warn("Call to establish Relation from {} to a Page {} that has no content: skip", (Object)source.getPath(), (Object)copy.getPath());
            return null;
        }
        try {
            this.checkCircularRelationship(source.getPath(), content.getPath(), deep);
            Node contentNode = (Node)content.adaptTo(Node.class);
            LiveCopyManagerImpl usersLiveCopyMgr = this.liveCopyService.createLiveCopyManager(content.getResourceResolver());
            LiveCopyManagerImpl.LiveCopyImpl lc = usersLiveCopyMgr.create(contentNode.getParent(), source.getPath(), deep, rolloutConfig);
            LiveRelationshipManagerImpl.markRelationship((Node)copy.adaptTo(Node.class), true, deep);
            if (autoSave) {
                contentNode.getSession().save();
            }
            return this.buildRelationship(content.getResourceResolver(), lc, "/" + content.getName(), true);
        }
        catch (RepositoryException e) {
            Session session = (Session)content.getResourceResolver().adaptTo(Session.class);
            try {
                if (autoSave && session != null && session.hasPendingChanges()) {
                    session.refresh(false);
                }
            }
            catch (RepositoryException e1) {
                log.error("Failed to revert changes {}", (Throwable)e1);
            }
            throw new WCMException((Throwable)e);
        }
    }

    public void endRelationship(Resource resource, boolean autoSave) throws WCMException {
        Node node = (Node)resource.adaptTo(Node.class);
        if (node != null) {
            try {
                LiveCopyManagerImpl usersLiveCopyMgr = this.liveCopyService.createLiveCopyManager(resource.getResourceResolver());
                if (usersLiveCopyMgr.remove(node.getPath())) {
                    LiveRelationshipManagerImpl.removeMarker(node);
                } else {
                    Utils.detachLiveCopy(node, true, false);
                }
                if (autoSave) {
                    node.getSession().save();
                }
                log.debug("detached Resource at {} from LiveRelationship", (Object)resource.getPath());
            }
            catch (RepositoryException e) {
                throw new WCMException((Throwable)e);
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public boolean isSource(Resource source) {
        ResourceResolver sysView = null;
        try {
            if (source != null) {
                sysView = this.resolverFactory.getServiceResourceResolver(null);
                boolean bl = this.liveCopyService.createLiveCopyManager(sysView).getDependentLiveCopies(source.getPath()).hasNext();
                return bl;
            }
        }
        catch (RepositoryException e) {
            log.error("Failed to check isSource status of source at {}", (Object)source.getPath(), (Object)e);
        }
        catch (WCMException e) {
            log.error("Failed to check isSource status of source at {}", (Object)source.getPath(), (Object)e);
        }
        catch (LoginException e) {
            log.error("Failed to check isSource status of source at {}", (Object)source.getPath(), (Object)e);
        }
        finally {
            if (sysView != null && sysView.isLive()) {
                sysView.close();
            }
        }
        return false;
    }

    public void detach(Resource resource, boolean autoSave) throws WCMException {
        this.endRelationship(resource, autoSave);
    }

    public void cancelRelationship(ResourceResolver resolver, LiveRelationship relation, boolean deep, boolean autoSave) throws WCMException {
        if (resolver == null || relation == null) {
            throw new IllegalArgumentException("Relation must exist");
        }
        LiveStatus status = relation.getStatus();
        if (Boolean.TRUE.equals(status.getAdvancedStatus("msm:isTargetManuallyCreated"))) {
            throw new IllegalStateException("Relation must not be manually created");
        }
        Node slave = Utils.getNode(resolver, relation.getTargetPath());
        if (slave == null) {
            String msg = String.format("Call to cancelRelation on non-existing Resource '%s: use skipPages instead", relation.getTargetPath());
            throw new IllegalArgumentException(msg);
        }
        if (Boolean.TRUE.equals(status.getAdvancedStatus("msm:isTargetDeleted")) || status.isCancelled() && status.isCancelledForChildren() == deep) {
            log.debug("Nothing to do, Relationship from [0]->[1] already cancelled", (Object)relation.getSourcePath(), (Object)relation.getTargetPath());
            return;
        }
        try {
            if (!slave.isNodeType("cq:LiveSyncCancelled")) {
                slave.addMixin("cq:LiveSyncCancelled");
            }
            if (deep) {
                slave.setProperty("cq:isCancelledForChildren", true);
            } else if (slave.hasProperty("cq:isCancelledForChildren")) {
                slave.getProperty("cq:isCancelledForChildren").remove();
            }
            if (autoSave) {
                resolver.commit();
            }
        }
        catch (RepositoryException re) {
            throw new WCMException("Error while cancelling relationship", (Throwable)re);
        }
        catch (PersistenceException e) {
            throw new WCMException("Error while committing changes to cancel relationship", (Throwable)e);
        }
    }

    public void reenableRelationship(ResourceResolver resolver, LiveRelationship relation, boolean autoSave) throws WCMException {
        if (relation == null || resolver == null) {
            throw new IllegalArgumentException("Relation and ResourceResolver must exist");
        }
        if (!relation.getStatus().isCancelled()) {
            throw new IllegalStateException("The relation given is not cancelled, can not reenable");
        }
        try {
            Node slave = Utils.getNode(resolver, relation.getTargetPath());
            if (slave != null && slave.isNodeType("cq:LiveSyncCancelled")) {
                if (slave.hasProperty("cq:isCancelledForChildren")) {
                    slave.getProperty("cq:isCancelledForChildren").remove();
                }
                slave.removeMixin("cq:LiveSyncCancelled");
                if (autoSave) {
                    resolver.commit();
                }
            }
        }
        catch (RepositoryException re) {
            throw new WCMException("Error while enabling relationship", (Throwable)re);
        }
        catch (PersistenceException e) {
            throw new WCMException("Error while committing changes to cancel relationship", (Throwable)e);
        }
    }

    public void cancelPropertyRelationship(ResourceResolver resolver, LiveRelationship relation, String[] names, boolean autoSave) throws WCMException {
        if (relation == null || names.length == 0) {
            throw new IllegalArgumentException("Relation and names required");
        }
        Resource target = resolver.getResource(relation.getTargetPath());
        if (target == null || !this.hasLiveRelationship(target)) {
            throw new IllegalStateException("Relation must not be manually created");
        }
        try {
            Node slave = Utils.getWorkingNode((Node)target.adaptTo(Node.class));
            if (slave != null) {
                if (!slave.isNodeType("cq:PropertyLiveSyncCancelled")) {
                    slave.addMixin("cq:PropertyLiveSyncCancelled");
                }
                ArrayList<Value> values = new ArrayList<Value>();
                if (slave.hasProperty("cq:propertyInheritanceCancelled")) {
                    Property prop = slave.getProperty("cq:propertyInheritanceCancelled");
                    values.addAll(Arrays.asList(prop.getValues()));
                }
                ValueFactory vf = slave.getSession().getValueFactory();
                for (String name : names) {
                    boolean found = false;
                    for (Value v : values) {
                        if (!v.getString().equals(name)) continue;
                        found = true;
                        break;
                    }
                    if (found) continue;
                    values.add(vf.createValue(name));
                }
                slave.setProperty("cq:propertyInheritanceCancelled", values.toArray((T[])new Value[values.size()]));
                if (autoSave) {
                    resolver.commit();
                }
            }
        }
        catch (RepositoryException re) {
            throw new WCMException("Error while cancelling property relationship", (Throwable)re);
        }
        catch (PersistenceException e) {
            throw new WCMException("Error while saving changes", (Throwable)e);
        }
    }

    public void reenablePropertyRelationship(ResourceResolver resolver, LiveRelationship relation, String[] names, boolean autoSave) throws WCMException {
        if (relation == null || names.length == 0) {
            throw new IllegalArgumentException("Relation and names required");
        }
        Resource target = resolver.getResource(relation.getTargetPath());
        if (target == null || !this.hasLiveRelationship(target)) {
            throw new IllegalStateException("Relation must not be manually created");
        }
        try {
            Node slave = Utils.getWorkingNode((Node)target.adaptTo(Node.class));
            if (slave != null) {
                Property prop = null;
                ArrayList<Value> values = new ArrayList<Value>();
                if (slave.hasProperty("cq:propertyInheritanceCancelled")) {
                    prop = slave.getProperty("cq:propertyInheritanceCancelled");
                    values.addAll(Arrays.asList(prop.getValues()));
                }
                for (String name : names) {
                    Value value = null;
                    for (Value v : values) {
                        if (!v.getString().equals(name)) continue;
                        value = v;
                        break;
                    }
                    if (value == null) continue;
                    values.remove((Object)value);
                }
                if (prop != null) {
                    if (values.size() == 0) {
                        prop.remove();
                        if (slave.isNodeType("cq:PropertyLiveSyncCancelled")) {
                            slave.removeMixin("cq:PropertyLiveSyncCancelled");
                        }
                    } else {
                        prop.setValue(values.toArray((T[])new Value[values.size()]));
                    }
                }
                if (autoSave) {
                    resolver.commit();
                }
            }
        }
        catch (RepositoryException re) {
            throw new WCMException("Error while reenabling relationship", (Throwable)re);
        }
        catch (PersistenceException e) {
            throw new WCMException("Error while saving changes", (Throwable)e);
        }
    }

    public Map<String, Page> getSkippedSourcePages(Page parentTargetPage) throws WCMException {
        LinkedHashMap<String, Page> ret = new LinkedHashMap<String, Page>();
        Node contentNode = (Node)parentTargetPage.getContentResource().adaptTo(Node.class);
        try {
            if (contentNode != null && contentNode.hasProperty("cq:skippedPages")) {
                Value[] skippedPages;
                LiveRelationship lr = this.getLiveRelationship(parentTargetPage.getContentResource(), true);
                if (lr == null) {
                    throw new WCMException("Target page is not a Live Copy");
                }
                if (!lr.getStatus().isSourceExisting()) {
                    throw new WCMException("Source page must exist to compute skipped pages");
                }
                PageManager pm = parentTargetPage.getPageManager();
                Page parentSourcePage = pm.getContainingPage(lr.getSourcePath());
                for (Value v : skippedPages = contentNode.getProperty("cq:skippedPages").getValues()) {
                    String skippedPageName = v.getString();
                    if (!parentSourcePage.hasChild(skippedPageName) || parentTargetPage.hasChild(skippedPageName)) continue;
                    ret.put(parentTargetPage.getPath() + "/" + skippedPageName, pm.getPage(parentSourcePage.getPath() + "/" + skippedPageName));
                }
            }
        }
        catch (RepositoryException e) {
            throw new WCMException("Error while reading repository", (Throwable)e);
        }
        return ret;
    }

    public void addSkippedPages(Page parentPage, String[] childrenNames, boolean autoSave) throws WCMException {
        if (parentPage == null) {
            throw new WCMException("Cannot skip a page if parent page does not exist.");
        }
        Node node = (Node)parentPage.getContentResource().adaptTo(Node.class);
        if (node == null) {
            throw new WCMException("Cannot skip a page if parent page does not exist.");
        }
        try {
            StatusUtil.skipPages(node, childrenNames);
            if (autoSave && node.getSession().hasPendingChanges()) {
                node.getSession().save();
            }
        }
        catch (RepositoryException e) {
            throw new WCMException((Throwable)e);
        }
    }

    public void removeSkippedPages(Page parentPage, String[] childrenNames, boolean autoSave) throws WCMException {
        if (parentPage == null) {
            throw new WCMException("Cannot unskip a page if parent page does not exist.");
        }
        Node node = (Node)parentPage.getContentResource().adaptTo(Node.class);
        if (node == null) {
            throw new WCMException("Cannot unskip a page if parent page does not exist.");
        }
        try {
            StatusUtil.unskipPages(node, childrenNames);
            if (autoSave && node.getSession().hasPendingChanges()) {
                node.getSession().save();
            }
        }
        catch (RepositoryException re) {
            throw new WCMException("Error while reading the repository", (Throwable)re);
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public Map<String, LiveCopy> getLiveCopies() {
        ResourceResolver sysResolver = null;
        try {
            LiveCopy lc;
            sysResolver = this.resolverFactory.getServiceResourceResolver(null);
            RangeIterator itr = this.liveCopyService.createLiveCopyManager(sysResolver).getAll();
            HashMap<String, LiveCopy> result = new HashMap<String, LiveCopy>();
            while (itr.hasNext()) {
                lc = (LiveCopy)itr.next();
                result.put(lc.getPath(), lc);
            }
            lc = Collections.unmodifiableMap(result);
            return lc;
        }
        catch (RepositoryException e) {
            log.error("Failed to access LiveCopies {}", (Throwable)e);
        }
        catch (WCMException e) {
            log.error("Failed to access LiveCopies {}", (Throwable)e);
        }
        catch (LoginException e) {
            log.error("Failed to access LiveCopies {}", (Throwable)e);
        }
        finally {
            if (sysResolver != null && sysResolver.isLive()) {
                sysResolver.close();
            }
        }
        return Collections.emptyMap();
    }

    public LiveCopy getLiveCopy(Resource target) {
        if (target == null || target instanceof SyntheticResource) {
            return null;
        }
        try {
            LiveCopyManagerImpl.LiveCopyImpl lc = this.getContainingLiveCopy(target, target.getResourceResolver());
            if (lc != null) {
                log.debug("Found LiveCopy in inheritance that is applicable for {}", (Object)target.getPath());
                return lc;
            }
        }
        catch (RepositoryException e) {
            log.error("Could not access LiveCopy for Resoruce{}: {}", (Object)target.getPath(), (Object)e);
        }
        catch (WCMException e) {
            log.error("Could not access LiveCopy for Resoruce{}: {}", (Object)target.getPath(), (Object)e);
        }
        return null;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public boolean isInBlueprint(Resource resource) {
        Blueprint blueprint = null;
        ResourceResolver sysView = null;
        if (resource != null) {
            String absPath = resource.getPath();
            try {
                sysView = this.resolverFactory.getServiceResourceResolver(null);
                BlueprintManager sysBpMgr = this.blueprintManagerFactory.getBlueprintManager(sysView);
                blueprint = sysBpMgr.getContainingBlueprint(absPath);
            }
            catch (WCMException e) {
                log.error("Failed to access Blueprint at {}: {}", (Object)absPath, (Object)e);
            }
            catch (LoginException e) {
                log.error("Failed to access Blueprint at {}: {}", (Object)absPath, (Object)e);
            }
            finally {
                if (sysView != null && sysView.isLive()) {
                    sysView.close();
                }
            }
        }
        return blueprint != null;
    }

    public boolean isLiveCopy(Resource target) {
        return this.hasLiveRelationship(target);
    }

    public Collection<LiveRelationship> getLiveRelationships(Page master, RolloutManager.Trigger trigger, String[] targets, boolean advancedStatus) throws WCMException {
        return this.getLiveRelationships(master.hasContent() ? master.getContentResource() : (Resource)master.adaptTo(Resource.class), trigger, targets, advancedStatus);
    }

    public Collection<LiveRelationship> getLiveRelationships(Resource source, RolloutManager.Trigger trigger, String[] targets, boolean advancedStatus) throws WCMException {
        String sourcePath = source.getPath();
        log.debug("Get LiveRelationships for {}", (Object)sourcePath);
        HashMap<String, LiveRelationship> relations = new HashMap<String, LiveRelationship>();
        try {
            LiveCopyManagerImpl userLcManager = this.liveCopyService.createLiveCopyManager(source.getResourceResolver());
            Iterator<LiveCopyManagerImpl.LiveCopyImpl> deps = userLcManager.getDependentLiveCopies(source.getPath());
            while (deps.hasNext()) {
                LiveRelationship lr;
                LiveCopyManagerImpl.LiveCopyImpl lc = deps.next();
                String relPath = sourcePath.substring(lc.getBlueprintPath().length());
                String targetPath = lc.getPath() + relPath;
                if (targets != null && targets.length > 0) {
                    boolean allowed = false;
                    for (int i = 0; !allowed && i < targets.length; ++i) {
                        allowed = Text.isDescendantOrEqual((String)targets[i], (String)targetPath);
                    }
                    if (!allowed) {
                        log.debug("LiveCopy {} not contained in target filter {}", (Object)targetPath, (Object)targets);
                        continue;
                    }
                }
                if (relations.containsKey(targetPath) || (lr = this.buildRelationship(source.getResourceResolver(), lc, relPath, advancedStatus)) == null) continue;
                if (trigger != null && !lr.isTrigger(trigger)) {
                    log.debug("liveCopy {} ignored by trigger filter {}", (Object)lc.getPath(), (Object)trigger);
                    continue;
                }
                log.debug("adding relation {}", (Object)lr);
                relations.put(targetPath, lr);
            }
        }
        catch (RepositoryException e) {
            throw new WCMException((Throwable)e);
        }
        return relations.values();
    }

    public static void markRelationship(Node node, boolean forceContent) throws RepositoryException {
        LiveRelationshipManagerImpl.markRelationship(node, forceContent, true);
    }

    private LiveRelationship buildRelationship(ResourceResolver resolver, LiveCopy liveCopy, String relPath, boolean advancedStatus) throws WCMException {
        try {
            LiveRelationshipImpl relation = new LiveRelationshipImpl(liveCopy, relPath);
            String dstPath = relation.getTargetPath();
            Node target = Utils.getNode(resolver, dstPath);
            boolean isTargetFromDifferentTree = false;
            if (target != null && !target.isNew()) {
                LiveCopy targetLiveCopy = this.getLiveCopy(resolver.getResource(target.getPath()));
                if (!(targetLiveCopy == null || liveCopy.getBlueprintPath().equals(targetLiveCopy.getBlueprintPath()) && liveCopy.getPath().equals(targetLiveCopy.getPath()))) {
                    String syncPath = dstPath.substring(targetLiveCopy.getPath().length());
                    relation = new LiveRelationshipImpl(targetLiveCopy, syncPath);
                    isTargetFromDifferentTree = true;
                }
            } else if (target == null) {
                String parentDst;
                LiveCopy targetLiveCopy;
                int level = 1;
                if (dstPath.endsWith("/jcr:content")) {
                    level = 2;
                }
                if (!((targetLiveCopy = this.getLiveCopy(resolver.getResource(parentDst = Text.getRelativeParent((String)dstPath, (int)level)))) == null || liveCopy.getBlueprintPath().equals(targetLiveCopy.getBlueprintPath()) && liveCopy.getPath().equals(targetLiveCopy.getPath()))) {
                    String syncPath = dstPath.substring(targetLiveCopy.getPath().length());
                    relation = new LiveRelationshipImpl(targetLiveCopy, syncPath);
                    isTargetFromDifferentTree = true;
                }
            }
            LiveStatusImpl status = StatusUtil.createLiveStatus(resolver, relation.getSourcePath(), relation.getTargetPath(), relation.getLiveCopy().getPath(), advancedStatus);
            if (advancedStatus) {
                status.setAdvancedStatus("msm:isTargetFromDifferentTree", isTargetFromDifferentTree);
            }
            relation.setStatus(status);
            relation.setRolloutConfigs(this.computeRolloutConfigs(relation, resolver));
            relation.setComputationTime(-1);
            return relation;
        }
        catch (RepositoryException e) {
            throw new WCMException((Throwable)e);
        }
    }

    public static void removeMarker(Node targetNode) throws RepositoryException {
        if (targetNode.isNodeType("cq:LiveSyncCancelled")) {
            targetNode.removeMixin("cq:LiveSyncCancelled");
        }
        if (targetNode.hasProperty("cq:isCancelledForChildren")) {
            targetNode.getProperty("cq:isCancelledForChildren").remove();
        }
        if (targetNode.isNodeType("cq:PropertyLiveSyncCancelled")) {
            targetNode.removeMixin("cq:PropertyLiveSyncCancelled");
            if (targetNode.hasProperty("cq:propertyInheritanceCancelled")) {
                targetNode.getProperty("cq:propertyInheritanceCancelled").remove();
            }
        }
    }

    private List<RolloutConfig> computeRolloutConfigs(LiveRelationship relation, ResourceResolver resolver) throws WCMException, RepositoryException {
        String targetPath = Utils.getPagePath(relation.getTargetPath());
        LiveCopy lc = relation.getLiveCopy();
        if (lc.getPath().equals(targetPath) && !lc.getRolloutConfigs().isEmpty()) {
            return lc.getRolloutConfigs();
        }
        String sourcePath = Utils.getPagePath(relation.getSourcePath());
        Blueprint bp = this.blueprintManagerFactory.getBlueprintManager(resolver).getContainingBlueprint(sourcePath);
        List configs = this.inheritRolloutConfig(targetPath, sourcePath, lc, bp);
        while (configs == null && !lc.isRoot() && !targetPath.equals("/")) {
            targetPath = Text.getRelativeParent((String)targetPath, (int)1);
            sourcePath = Text.getRelativeParent((String)sourcePath, (int)1);
            lc = this.getContainingLiveCopy((Resource)new NonExistingResource(resolver, targetPath), resolver);
            configs = this.inheritRolloutConfig(targetPath, sourcePath, lc, bp);
        }
        if (configs == null) {
            RolloutConfig defaultConfig = this.liveCopyService.getRolloutConfig(this.defaultRolloutConfigPath, resolver);
            configs = defaultConfig == null ? Collections.emptyList() : Collections.singletonList(defaultConfig);
        }
        return configs;
    }

    private List<RolloutConfig> inheritRolloutConfig(String targetPath, String sourcePath, LiveCopy lc, Blueprint bp) throws WCMException {
        List rcs = null;
        boolean exhausted = lc.getPath().equals(targetPath);
        if (bp != null && Text.isDescendantOrEqual((String)bp.getSitePath(), (String)sourcePath)) {
            String srcPath;
            String string = srcPath = bp.getSitePath().equals(sourcePath) ? null : sourcePath.substring(bp.getSitePath().length() + 1);
            while (((rcs = bp.getBlueprintRolloutConfig(srcPath, true)) == null || exhausted) && srcPath != null) {
                srcPath = srcPath.lastIndexOf("/") > -1 ? srcPath.substring(0, srcPath.lastIndexOf("/")) : null;
                targetPath = Text.getRelativeParent((String)targetPath, (int)1);
                exhausted = !Text.isDescendantOrEqual((String)lc.getPath(), (String)targetPath);
                if (!exhausted) continue;
            }
        }
        if (!exhausted && rcs != null || lc.getRolloutConfigs().isEmpty()) {
            return rcs;
        }
        return lc.getRolloutConfigs();
    }

    private LiveCopyManagerImpl.LiveCopyImpl getContainingLiveCopy(Resource resource, ResourceResolver resolver) throws RepositoryException, WCMException {
        assert (resource != null);
        if (ResourceUtil.isStarResource((Resource)resource)) {
            String parentPath = resource.getPath();
            if ((resource = resource.getParent()) == null) {
                log.warn("StarResource given at {}: no parent: no LiveCopy", (Object)parentPath);
                return null;
            }
        }
        return this.liveCopyService.createLiveCopyManager(resolver).getContainingLiveCopy(resource.getPath());
    }

    private boolean isManuallyCreated(Node target) throws RepositoryException {
        return target == null || !target.isNodeType("cq:LiveRelationship");
    }

    /*
     * Enabled force condition propagation
     * Lifted jumps to return sites
     */
    private static void markRelationship(Node node, boolean forceContent, boolean deep) throws RepositoryException {
        Node workingNode;
        try {
            workingNode = Utils.getWorkingNode(node);
        }
        catch (ItemNotFoundException e) {
            if (forceContent) {
                workingNode = node.addNode("jcr:content", "nt:unstructured");
            }
            log.debug("No jcr:content on HierarchyItem: skip addition of liveRelation on {}", (Object)node.getPath());
            return;
        }
        if (!workingNode.isNodeType("cq:LiveSyncConfig") && !workingNode.isNodeType("cq:LiveRelationship")) {
            if (workingNode.canAddMixin("cq:LiveRelationship")) {
                workingNode.addMixin("cq:LiveRelationship");
                log.debug("Marked Node {} as LiveRelationship", (Object)workingNode.getPath());
            } else {
                log.debug("Not able to mark {} as {}", (Object)workingNode.getPath(), (Object)"cq:LiveRelationship");
            }
        }
        if (deep) {
            NodeIterator itr = node.getNodes();
            while (itr.hasNext()) {
                LiveRelationshipManagerImpl.markRelationship(itr.nextNode(), forceContent, true);
            }
            return;
        } else {
            if (workingNode.getPath().equals(node.getPath())) return;
            NodeIterator itr = workingNode.getNodes();
            while (itr.hasNext()) {
                LiveRelationshipManagerImpl.markRelationship(itr.nextNode(), forceContent, true);
            }
        }
    }

    private void checkCircularRelationship(String source, String target, boolean deep) throws RepositoryException, WCMException {
        ResourceResolver adminResolver = null;
        try {
            adminResolver = this.resolverFactory.getAdministrativeResourceResolver(null);
            if (this.liveCopyService.createLiveCopyManager(adminResolver).dependsOn(source, target, deep)) {
                throw new IllegalStateException(String.format("Can not establish Relation from %s -> %s: would be circular", source, target));
            }
        }
        catch (LoginException e) {
            throw new WCMException("Failed to access Repository", (Throwable)e);
        }
        finally {
            if (adminResolver != null) {
                adminResolver.close();
            }
        }
    }

    private static Iterator<Resource> pageToResourceIterator(Resource resource) {
        return resource.adaptTo(Page.class) == null ? resource.listChildren() : IteratorUtils.transformedIterator((Iterator)((Page)resource.adaptTo(Page.class)).listChildren(), (Transformer)new Transformer(){

            public Object transform(Object input) {
                return ((Page)input).adaptTo(Resource.class);
            }
        });
    }

    protected void bindBlueprintManagerFactory(BlueprintManagerFactory blueprintManagerFactory) {
        this.blueprintManagerFactory = blueprintManagerFactory;
    }

    protected void unbindBlueprintManagerFactory(BlueprintManagerFactory blueprintManagerFactory) {
        if (this.blueprintManagerFactory == blueprintManagerFactory) {
            this.blueprintManagerFactory = null;
        }
    }

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

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

    protected void bindLiveCopyService(LiveCopyServiceImpl liveCopyServiceImpl) {
        this.liveCopyService = liveCopyServiceImpl;
    }

    protected void unbindLiveCopyService(LiveCopyServiceImpl liveCopyServiceImpl) {
        if (this.liveCopyService == liveCopyServiceImpl) {
            this.liveCopyService = null;
        }
    }

    private class LiveRelationshipIterator
    implements RangeIterator {
        private final String sourcePath;
        private Iterator<LiveCopyManagerImpl.LiveCopyImpl> allLiveCopies;
        private final ResourceResolver resourceResolver;
        private final String targetFilter;
        private final RolloutManager.Trigger triggerFilter;
        private final LiveCopyManagerImpl lcm;
        private LiveRelationship next;
        private long pos;
        private int size;
        private HashSet<String> served;

        private LiveRelationshipIterator(Resource source, LiveCopyServiceImpl liveCopyService, String targetFilter, RolloutManager.Trigger triggerFilter) throws WCMException, RepositoryException {
            this.pos = -1;
            this.size = -1;
            this.served = new HashSet();
            this.targetFilter = targetFilter;
            this.triggerFilter = triggerFilter;
            this.sourcePath = source.getPath();
            this.resourceResolver = source.getResourceResolver();
            this.lcm = liveCopyService.createLiveCopyManager(this.resourceResolver);
            this.allLiveCopies = this.lcm.getDependentLiveCopies(this.sourcePath);
            this.seek();
        }

        private void seek() throws WCMException {
            while (this.next == null && this.allLiveCopies.hasNext()) {
                LiveCopyManagerImpl.LiveCopyImpl cand = this.allLiveCopies.next();
                if (this.targetFilter != null) {
                    String targetPath = cand.createCopyPath(this.sourcePath);
                    if (targetPath == null || !Text.isDescendantOrEqual((String)this.targetFilter, (String)targetPath) || this.served.contains(targetPath)) continue;
                    if (Text.isDescendantOrEqual((String)cand.getPath(), (String)this.targetFilter)) {
                        this.allLiveCopies = IteratorUtils.emptyIterator();
                    }
                }
                LiveRelationship rel = LiveRelationshipManagerImpl.this.buildRelationship(this.resourceResolver, cand, this.sourcePath.substring(cand.getBlueprintPath().length()), true);
                if (this.triggerFilter != null && !rel.isTrigger(this.triggerFilter)) continue;
                if (this.targetFilter != null) {
                    this.served.add(rel.getTargetPath());
                }
                this.next = rel;
                ++this.pos;
            }
        }

        public void skip(long skipNum) {
            for (long i = 0; i < skipNum; ++i) {
                this.next();
            }
        }

        public long getSize() {
            if (this.targetFilter == null && this.size == -1) {
                try {
                    this.size = IteratorUtils.toList(this.lcm.getDependentLiveCopies(this.sourcePath)).size();
                }
                catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            return this.size;
        }

        public long getPosition() {
            return this.pos;
        }

        public boolean hasNext() {
            return this.next != null;
        }

        public Object next() {
            if (this.next == null) {
                throw new NoSuchElementException("Call hasNext first");
            }
            LiveRelationship ret = this.next;
            this.next = null;
            try {
                this.seek();
            }
            catch (WCMException e) {
                throw new RuntimeException((Throwable)e);
            }
            return ret;
        }

        public void remove() {
            throw new UnsupportedOperationException("Result can not be modified");
        }
    }

}