ReplicatorImpl.java 28.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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.Credentials
 *  javax.jcr.Item
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.SimpleCredentials
 *  javax.jcr.Value
 *  javax.jcr.security.AccessControlManager
 *  javax.jcr.security.Privilege
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferenceCardinality
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.felix.scr.annotations.References
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.util.Text
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.apache.sling.jcr.resource.JcrPropertyMap
 *  org.osgi.framework.ServiceReference
 *  org.osgi.service.component.ComponentContext
 *  org.osgi.service.event.Event
 *  org.osgi.service.event.EventAdmin
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.replication.impl;

import com.day.cq.replication.AccessDeniedException;
import com.day.cq.replication.Agent;
import com.day.cq.replication.AgentConfig;
import com.day.cq.replication.AgentFilter;
import com.day.cq.replication.AgentManager;
import com.day.cq.replication.AgentNotFoundException;
import com.day.cq.replication.AggregateHandler;
import com.day.cq.replication.DefaultAggregateHandler;
import com.day.cq.replication.Preprocessor;
import com.day.cq.replication.ReplicationAction;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationContent;
import com.day.cq.replication.ReplicationContentFacade;
import com.day.cq.replication.ReplicationContentFilter;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.ReplicationLog;
import com.day.cq.replication.ReplicationOptions;
import com.day.cq.replication.ReplicationPathTransformer;
import com.day.cq.replication.ReplicationStatus;
import com.day.cq.replication.Replicator;
import com.day.cq.replication.impl.AgentManagerImpl;
import com.day.cq.replication.impl.AliasesPreprocessor;
import com.day.cq.replication.impl.ReplicationPathTransformerProvider;
import com.day.cq.replication.impl.ReplicationStatusImpl;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.jcr.Credentials;
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.SimpleCredentials;
import javax.jcr.Value;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.References;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.jcr.resource.JcrPropertyMap;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1)
@Service(value={Replicator.class})
@References(value={@Reference(name="preprocessor", referenceInterface=Preprocessor.class, policy=ReferencePolicy.DYNAMIC, cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE)})
public class ReplicatorImpl
implements Replicator {
    public static final String REPLICATION_SERVICE_USER = "replicationService";
    private final Logger logger;
    @Reference
    private EventAdmin eventAdmin;
    @Reference
    private SlingRepository repository;
    @Reference
    private AgentManager agentMgr;
    @org.apache.felix.scr.annotations.Property(boolValue={0})
    static final String DISTRIBUTE_EVENTS = "distribute_events";
    @Reference
    private ReplicationPathTransformerProvider transformerProvider;
    private boolean distributeEvents;
    private final Map<String, Preprocessor> preprocessors;
    private final Map<String, ServiceReference> unhandledPreprocessors;
    private ComponentContext context;
    private final Lock lock;

    public ReplicatorImpl() {
        this.logger = LoggerFactory.getLogger(this.getClass());
        this.eventAdmin = null;
        this.repository = null;
        this.agentMgr = null;
        this.transformerProvider = null;
        this.preprocessors = new HashMap<String, Preprocessor>();
        this.unhandledPreprocessors = new HashMap<String, ServiceReference>();
        this.lock = new ReentrantLock();
    }

    public ReplicatorImpl(AgentManager agentMgr, SlingRepository repository, EventAdmin eventAdmin, ReplicationPathTransformerProvider transformerProvider) {
        this.logger = LoggerFactory.getLogger(this.getClass());
        this.eventAdmin = null;
        this.repository = null;
        this.agentMgr = null;
        this.transformerProvider = null;
        this.preprocessors = new HashMap<String, Preprocessor>();
        this.unhandledPreprocessors = new HashMap<String, ServiceReference>();
        this.lock = new ReentrantLock();
        this.agentMgr = agentMgr;
        this.repository = repository;
        this.eventAdmin = eventAdmin;
        this.transformerProvider = transformerProvider;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void activate(ComponentContext context) {
        this.lock.lock();
        try {
            this.distributeEvents = (Boolean)context.getProperties().get("distribute_events");
            this.context = context;
            for (ServiceReference ref : this.unhandledPreprocessors.values()) {
                this.registerPreprocessor(ref);
            }
            this.preprocessors.put(AliasesPreprocessor.class.getName(), new AliasesPreprocessor(this.repository, this));
            this.unhandledPreprocessors.clear();
        }
        finally {
            this.lock.unlock();
        }
    }

    protected void deactivate(ComponentContext context) {
        this.lock.lock();
        try {
            this.context = null;
            this.preprocessors.remove(AliasesPreprocessor.class.getName());
        }
        finally {
            this.lock.unlock();
        }
    }

    protected void bindPreprocessor(ServiceReference ref) {
        block4 : {
            this.lock.lock();
            try {
                if (this.context == null) {
                    this.unhandledPreprocessors.put((String)ref.getProperty("service.pid"), ref);
                    break block4;
                }
                this.registerPreprocessor(ref);
            }
            finally {
                this.lock.unlock();
            }
        }
    }

    protected void unbindPreprocessor(ServiceReference ref) {
        this.lock.lock();
        try {
            this.unregisterPreprocessor(ref);
            this.unhandledPreprocessors.remove(ref.getProperty("service.pid"));
        }
        finally {
            this.lock.unlock();
        }
    }

    private void registerPreprocessor(ServiceReference ref) {
        String key = (String)ref.getProperty("service.pid");
        Object service = this.context.locateService("preprocessor", ref);
        if (service != null) {
            this.preprocessors.put(key, (Preprocessor)service);
            this.logger.debug("Registering service {} : {}", (Object)key, service);
        }
    }

    private void unregisterPreprocessor(ServiceReference ref) {
        String key = (String)ref.getProperty("service.pid");
        this.preprocessors.remove(key);
        this.logger.debug("Unregistering service {}.", (Object)key);
    }

    private Preprocessor[] getPreprocessors() {
        this.lock.lock();
        try {
            Collection<Preprocessor> values = this.preprocessors.values();
            Preprocessor[] arrpreprocessor = values.toArray(new Preprocessor[values.size()]);
            return arrpreprocessor;
        }
        finally {
            this.lock.unlock();
        }
    }

    @Override
    public ReplicationStatus getReplicationStatus(Session session, String path) {
        ReplicationStatusImpl status = null;
        try {
            if (session.nodeExists(path)) {
                Node node = session.getNode(path);
                if (node.hasNode("{http://www.jcp.org/jcr/1.0}content")) {
                    node = node.getNode("{http://www.jcp.org/jcr/1.0}content");
                }
                status = new ReplicationStatusImpl(this.agentMgr, path, (ValueMap)new JcrPropertyMap(node));
            }
        }
        catch (RepositoryException e) {
            this.logger.warn("Unable to create replication status: {}", (Object)e.toString());
        }
        return status;
    }

    @Override
    public List<ReplicationContentFilter> createContentFilterChain(ReplicationAction action) {
        return Collections.unmodifiableList(((AgentManagerImpl)this.agentMgr).createContentFilterChain(action));
    }

    @Override
    public void replicate(Session session, ReplicationActionType type, String path) throws ReplicationException {
        this.replicate(session, type, path, null);
    }

    @Override
    public void replicate(Session session, ReplicationActionType type, String path, ReplicationOptions options) throws ReplicationException {
        AggregateHandler aggregateHandler;
        long start = System.currentTimeMillis();
        if (options == null) {
            options = new ReplicationOptions();
        }
        LinkedList<Agent> agents = new LinkedList<Agent>();
        AgentFilter filter = options.getFilter();
        if (filter == null) {
            filter = AgentFilter.DEFAULT;
        }
        boolean noStatusUpdate = true;
        boolean noVersions = true;
        boolean isPureCacheInvalidation = true;
        boolean replicateAlias = false;
        for (Agent agent : this.agentMgr.getAgents().values()) {
            if (!agent.isValid() || !filter.isIncluded(agent) || !agent.isEnabled() && type != ReplicationActionType.TEST) continue;
            agents.add(agent);
            noStatusUpdate &= agent.getConfiguration().noStatusUpdate();
            noVersions &= agent.getConfiguration().noVersions();
            isPureCacheInvalidation &= agent.isCacheInvalidator();
            if (replicateAlias) {
                replicateAlias &= agent.getConfiguration().aliasUpdate();
                continue;
            }
            replicateAlias = agent.getConfiguration().aliasUpdate();
        }
        if (agents.size() == 0) {
            if (filter != AgentFilter.DEFAULT) {
                throw new AgentNotFoundException("Replication triggered, but no agent found!");
            }
            this.logger.info("Replication triggered, but no agent found or selected.");
            return;
        }
        if (noStatusUpdate || isPureCacheInvalidation || type == ReplicationActionType.TEST) {
            options.setSuppressStatusUpdate(true);
        }
        if (noVersions || type == ReplicationActionType.TEST) {
            options.setSuppressVersions(true);
        }
        if (replicateAlias) {
            options.setUpdateAlias(true);
        }
        if ((aggregateHandler = options.getAggregateHandler()) == null) {
            aggregateHandler = new DefaultAggregateHandler();
        }
        this.logger.info("Setting up replication with options: {}", (Object)options);
        Session systemSession = null;
        try {
            long setup = System.currentTimeMillis();
            systemSession = this.repository.loginService("replicationService", null);
            List<String> aggregatePaths = aggregateHandler.prepareForReplication(systemSession, type, path);
            if (aggregatePaths.isEmpty()) {
                aggregatePaths = new LinkedList<String>();
                aggregatePaths.add(path);
            }
            String privPath = path;
            while (!systemSession.nodeExists(privPath)) {
                if ((privPath = Text.getRelativeParent((String)privPath, (int)1)).length() != 0) continue;
                privPath = "/";
            }
            if (path.equals(privPath)) {
                for (String testPath : aggregatePaths) {
                    this.checkPermission(session, type, testPath);
                }
            } else {
                this.checkReplicationPermission(session, type, privPath);
            }
            long permissionChecked = System.currentTimeMillis();
            String rev = options.getRevision();
            ReplicationAction action = new ReplicationAction(type, aggregatePaths.toArray(new String[aggregatePaths.size()]), 0, session.getUserID(), rev);
            for (Preprocessor p : this.getPreprocessors()) {
                p.preprocess(action, options);
            }
            long preprocessed = System.currentTimeMillis();
            aggregateHandler.processForReplication(session, action);
            session.save();
            Map<String, ReplicationContent> contents = this.buildContents(systemSession, action, agents);
            long built = System.currentTimeMillis();
            int numSuccess = 0;
            for (Agent agent2 : agents) {
                ReplicationLog log = agent2.getLog();
                ReplicationContent content = contents.get(agent2.getId());
                try {
                    if (content == null) continue;
                    ReplicationAction transformedAction = this.getTransformedAction(session, type, systemSession, rev, action, agent2);
                    agent2.replicate(transformedAction, content, options);
                    ++numSuccess;
                }
                catch (Exception e) {
                    log.error("Error during replication %s", e.toString());
                    this.logger.error("Error during replication.", (Throwable)e);
                    if (content == null) continue;
                    content.release(agent2.getId());
                }
            }
            long queued = System.currentTimeMillis();
            if (numSuccess > 0) {
                if (!options.isSuppressStatusUpdate()) {
                    this.updateStatus(systemSession, action);
                }
                if (this.eventAdmin != null) {
                    this.eventAdmin.postEvent(action.toEvent(this.distributeEvents));
                }
            }
            long end = System.currentTimeMillis();
            this.logger.info("Processed replication: setup {}ms, checked {}ms, pre {}ms, build {}ms, queued {}ms, status {}ms, total {}ms", new Object[]{setup - start, permissionChecked - setup, preprocessed - permissionChecked, built - preprocessed, queued - built, end - queued, end - start});
        }
        catch (RepositoryException e) {
            this.logger.error("Repository error while replicating.", (Throwable)e);
            throw new ReplicationException((Exception)e);
        }
        finally {
            if (systemSession != null) {
                systemSession.logout();
            }
        }
    }

    private ReplicationAction getTransformedAction(Session session, ReplicationActionType type, Session systemSession, String rev, ReplicationAction action, Agent agent) {
        ReplicationAction overridingAction = null;
        ReplicationPathTransformer transformer = null;
        if (this.transformerProvider != null) {
            transformer = this.transformerProvider.getTransformer(systemSession, action, agent);
        }
        if (transformer != null) {
            boolean isActionOverridden = false;
            String[] actionPaths = action.getPaths();
            for (int i = 0; i < actionPaths.length; ++i) {
                String actionPath = actionPaths[i];
                String transformedActionPath = this.getTransformedPath(transformer, systemSession, actionPath, agent, action);
                if (actionPath.equals(transformedActionPath)) continue;
                isActionOverridden = true;
                actionPaths[i] = transformedActionPath;
            }
            if (isActionOverridden) {
                overridingAction = new ReplicationAction(type, actionPaths, 0, session.getUserID(), rev);
                overridingAction.setConfig(action.getConfig());
                overridingAction.setLog(action.getLog());
                return overridingAction;
            }
        }
        return action;
    }

    @Override
    public void checkPermission(Session session, ReplicationActionType type, String path) throws ReplicationException {
        this.checkDeletePermission(session, type, path);
        this.checkReplicationPermission(session, type, path);
    }

    private void checkReplicationPermission(Session session, ReplicationActionType type, String path) throws AccessDeniedException {
        try {
            AccessControlManager acMgr = session.getAccessControlManager();
            if (type != ReplicationActionType.TEST && !acMgr.hasPrivileges(path, new Privilege[]{acMgr.privilegeFromName("{http://www.day.com/crx/1.0}replicate")})) {
                this.logger.warn("User {} has not enough privileges to replicate {}", (Object)session.getUserID(), (Object)path);
                throw new AccessDeniedException(path);
            }
        }
        catch (RepositoryException e) {
            this.logger.error("Error while evaluating user privileges.", (Throwable)e);
            throw new AccessDeniedException(path);
        }
    }

    private void checkDeletePermission(Session session, ReplicationActionType type, String path) throws AccessDeniedException {
        try {
            AccessControlManager acMgr = session.getAccessControlManager();
            if (type == ReplicationActionType.DELETE && session.nodeExists(path) && !acMgr.hasPrivileges(path, new Privilege[]{acMgr.privilegeFromName("{http://www.jcp.org/jcr/1.0}removeNode")})) {
                this.logger.warn("User {} has not enough privileges to delete {}", (Object)session.getUserID(), (Object)path);
                throw new AccessDeniedException(path);
            }
        }
        catch (RepositoryException e) {
            this.logger.error("Error while evaluating user privileges.", (Throwable)e);
            throw new AccessDeniedException(path);
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private Map<String, ReplicationContent> buildContents(Session systemSession, ReplicationAction action, List<Agent> agents) throws ReplicationException {
        HashMap<ContentKey, ReplicationContent> contents = new HashMap<ContentKey, ReplicationContent>();
        HashMap<String, ReplicationContent> ret = new HashMap<String, ReplicationContent>();
        for (Agent agent : agents) {
            ReplicationContent content;
            block20 : {
                String userId = agent.getConfiguration().getAgentUserId();
                ContentKey key = new ContentKey(userId, agent.getConfiguration().getSerializationType());
                content = null;
                ReplicationLog log = agent.getLog();
                ReplicationPathTransformer transformer = null;
                boolean skipCache = false;
                Session agentSession = systemSession;
                if (userId != null) {
                    try {
                        agentSession = this.repository.impersonateFromService("replicationService", (Credentials)new SimpleCredentials(userId, new char[0]), null);
                        log.info("Using user %s for building content.", userId);
                    }
                    catch (RepositoryException e) {
                        log.error("Unable to build content for agent '%s'.  Invalid userId:'%s'", agent.getId(), userId);
                        if (agents.size() != 1 && !ReplicationActionType.TEST.equals((Object)action.getType())) continue;
                        throw new ReplicationException("Replicaiton Agent [" + agent.getId() + "] has invalid agent userId [" + userId + "]", (Exception)e);
                    }
                }
                if (this.transformerProvider != null && (transformer = this.transformerProvider.getTransformer(agentSession, action, agent)) != null) {
                    skipCache = true;
                }
                if (!skipCache) {
                    content = (ReplicationContent)contents.get(key);
                }
                if (content == null) {
                    try {
                        if (systemSession.itemExists(action.getPath()) && !agentSession.itemExists(action.getPath())) {
                            log.error("Unable to build content for agent '%s'.Agent User '%s' does not sufficient permission on '%s'. ", agent.getId(), userId, action.getPath());
                            if (agents.size() != 1 && !ReplicationActionType.TEST.equals((Object)action.getType())) continue;
                            throw new AccessDeniedException("Replicaiton Agent [" + agent.getId() + "]- Agent user [" + userId + "] doesn't have sufficient permission on [" + action.getPath() + "]");
                        }
                        if (transformer != null) {
                            HashMap<String, Object> paramaters = new HashMap<String, Object>();
                            paramaters.put("replicationStartPath", this.getTransformedPath(transformer, agentSession, action.getPath(), agent, action));
                            content = agent.buildContent(agentSession, action, paramaters);
                        } else {
                            content = agent.buildContent(agentSession, action);
                        }
                        if (!skipCache) {
                            contents.put(key, content);
                        }
                        break block20;
                    }
                    catch (AccessDeniedException e) {
                        log.error("Error while building replication content %s", e.toString());
                        this.logger.error("Error while building replication content.", (Throwable)e);
                        throw e;
                    }
                    catch (Exception e) {
                        log.error("Error while building replication content %s", e.toString());
                        this.logger.error("Error while building replication content.", (Throwable)e);
                    }
                    finally {
                        if (agentSession == systemSession) continue;
                        agentSession.logout();
                        continue;
                    }
                }
                try {
                    content = agent.getContent(content.getFacade());
                }
                catch (Exception e) {
                    log.error("Error while retrieving existing replication content %s", e.toString());
                    this.logger.error("Error while retrieving existing content.", (Throwable)e);
                }
            }
            if (content == null) continue;
            ret.put(agent.getId(), content);
        }
        return ret;
    }

    private void updateStatus(Session session, ReplicationAction action) {
        if (action.getType() == ReplicationActionType.ACTIVATE || action.getType() == ReplicationActionType.DEACTIVATE || action.getType() == ReplicationActionType.DELETE) {
            try {
                Calendar c = Calendar.getInstance();
                c.setTimeInMillis(action.getTime());
                int retries = 10;
                while (retries-- > 0) {
                    try {
                        this.update(session, action.getPath(), action.getType(), action.getUserId(), c);
                        break;
                    }
                    catch (RepositoryException e) {
                        try {
                            session.refresh(false);
                        }
                        catch (RepositoryException var6_7) {
                            // empty catch block
                        }
                        if (retries != 0) continue;
                        throw e;
                    }
                }
                if ((action.getType() == ReplicationActionType.DEACTIVATE || action.getType() == ReplicationActionType.DELETE) && session.nodeExists(action.getPath())) {
                    this.deactivateChildNodes(session, session.getNode(action.getPath()), action.getType(), action.getUserId(), c);
                }
            }
            catch (RepositoryException e) {
                this.logger.warn("Unable to update replication status: {}", (Object)e.toString());
            }
        }
    }

    private String getTransformedPath(ReplicationPathTransformer transformer, Session session, String replicationPath, Agent agent, ReplicationAction action) {
        return transformer.transform(session, replicationPath, action, agent);
    }

    private void deactivateChildNodes(Session session, Node node, ReplicationActionType type, String userId, Calendar date) throws RepositoryException {
        NodeIterator ni = node.getNodes();
        while (ni.hasNext()) {
            Node current = ni.nextNode();
            if (!current.isNodeType("{http://www.jcp.org/jcr/nt/1.0}hierarchyNode")) continue;
            this.update(session, current.getPath(), type, userId, date);
            this.deactivateChildNodes(session, current, type, userId, date);
        }
    }

    private void update(Session session, String path, ReplicationActionType type, String userId, Calendar date) throws RepositoryException {
        if (session.itemExists(path)) {
            Node node = (Node)session.getItem(path);
            if (node.hasNode("{http://www.jcp.org/jcr/1.0}content")) {
                node = node.getNode("{http://www.jcp.org/jcr/1.0}content");
            }
            if (!node.isNodeType("cq:ReplicationStatus") && node.canAddMixin("cq:ReplicationStatus")) {
                node.addMixin("cq:ReplicationStatus");
            }
            node.setProperty("cq:lastReplicationAction", type.getName());
            node.setProperty("cq:lastReplicatedBy", userId);
            node.setProperty("cq:lastReplicated", date);
            node.setProperty("cq:lastPublishedBy", (Value)null);
            node.setProperty("cq:lastPublished", (Value)null);
            node.save();
        }
    }

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

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

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

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

    protected void bindAgentMgr(AgentManager agentManager) {
        this.agentMgr = agentManager;
    }

    protected void unbindAgentMgr(AgentManager agentManager) {
        if (this.agentMgr == agentManager) {
            this.agentMgr = null;
        }
    }

    protected void bindTransformerProvider(ReplicationPathTransformerProvider replicationPathTransformerProvider) {
        this.transformerProvider = replicationPathTransformerProvider;
    }

    protected void unbindTransformerProvider(ReplicationPathTransformerProvider replicationPathTransformerProvider) {
        if (this.transformerProvider == replicationPathTransformerProvider) {
            this.transformerProvider = null;
        }
    }

    private static final class ContentKey {
        private final String userId;
        private final String serType;

        private ContentKey(String userId, String serType) {
            this.userId = userId == null ? "" : userId;
            this.serType = serType;
        }

        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || this.getClass() != o.getClass()) {
                return false;
            }
            ContentKey that = (ContentKey)o;
            if (!this.serType.equals(that.serType)) {
                return false;
            }
            if (!this.userId.equals(that.userId)) {
                return false;
            }
            return true;
        }

        public int hashCode() {
            int result = this.userId.hashCode();
            result = 31 * result + this.serType.hashCode();
            return result;
        }
    }

}