OffloadingDefaultTransporter.java 32.4 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.replication.Agent
 *  com.day.cq.replication.AgentFilter
 *  com.day.cq.replication.ReplicationAction
 *  com.day.cq.replication.ReplicationActionType
 *  com.day.cq.replication.ReplicationException
 *  com.day.cq.replication.ReplicationListener
 *  com.day.cq.replication.ReplicationLog
 *  com.day.cq.replication.ReplicationLog$Level
 *  com.day.cq.replication.ReplicationOptions
 *  com.day.cq.replication.ReplicationResult
 *  com.day.cq.replication.Replicator
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.apache.commons.lang.ArrayUtils
 *  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.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.vault.fs.api.ProgressTrackerListener
 *  org.apache.jackrabbit.vault.fs.io.AccessControlHandling
 *  org.apache.jackrabbit.vault.fs.io.ImportOptions
 *  org.apache.jackrabbit.vault.packaging.JcrPackage
 *  org.apache.jackrabbit.vault.packaging.JcrPackageManager
 *  org.apache.jackrabbit.vault.packaging.PackageException
 *  org.apache.jackrabbit.vault.packaging.Packaging
 *  org.apache.sling.api.resource.LoginException
 *  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.ValueMap
 *  org.apache.sling.api.wrappers.ValueMapDecorator
 *  org.apache.sling.discovery.TopologyEvent
 *  org.apache.sling.discovery.TopologyEventListener
 *  org.osgi.service.event.Event
 *  org.osgi.service.event.EventHandler
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.granite.offloading.impl.transporter;

import com.adobe.granite.offloading.api.OffloadingException;
import com.adobe.granite.offloading.api.OffloadingJobProperties;
import com.adobe.granite.offloading.impl.OffloadingConfigurator;
import com.adobe.granite.offloading.impl.OffloadingEventProcessor;
import com.adobe.granite.offloading.impl.OffloadingLocations;
import com.adobe.granite.offloading.impl.OffloadingProcessor;
import com.adobe.granite.offloading.impl.OffloadingTransporter;
import com.adobe.granite.offloading.impl.transporter.OffloadingAgentFilter;
import com.adobe.granite.offloading.impl.util.OffloadingUtil;
import com.day.cq.replication.Agent;
import com.day.cq.replication.AgentFilter;
import com.day.cq.replication.ReplicationAction;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.ReplicationListener;
import com.day.cq.replication.ReplicationLog;
import com.day.cq.replication.ReplicationOptions;
import com.day.cq.replication.ReplicationResult;
import com.day.cq.replication.Replicator;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.commons.lang.ArrayUtils;
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.Properties;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.vault.fs.api.ProgressTrackerListener;
import org.apache.jackrabbit.vault.fs.io.AccessControlHandling;
import org.apache.jackrabbit.vault.fs.io.ImportOptions;
import org.apache.jackrabbit.vault.packaging.JcrPackage;
import org.apache.jackrabbit.vault.packaging.JcrPackageManager;
import org.apache.jackrabbit.vault.packaging.PackageException;
import org.apache.jackrabbit.vault.packaging.Packaging;
import org.apache.sling.api.resource.LoginException;
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.ValueMap;
import org.apache.sling.api.wrappers.ValueMapDecorator;
import org.apache.sling.discovery.TopologyEvent;
import org.apache.sling.discovery.TopologyEventListener;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1)
@Service
@Properties(value={@org.apache.felix.scr.annotations.Property(name="offloading.transporter.name", propertyPrivate=1, value={"offloading.transporter.default"}), @org.apache.felix.scr.annotations.Property(name="event.topics", propertyPrivate=1, value={"org/apache/sling/api/resource/Resource/ADDED", "org/apache/sling/api/resource/Resource/REMOVED"}), @org.apache.felix.scr.annotations.Property(name="event.filter", propertyPrivate=1, value={"(!(event.application=*))"})})
public class OffloadingDefaultTransporter
implements OffloadingTransporter,
EventHandler,
OffloadingEventProcessor,
TopologyEventListener {
    public static final String SERVICE_NAME = "offloading.transporter.default";
    private static final String AGENT_TO_WORKER_PREFIX_DEFAULT = "offloading";
    private static final String SUB_SERVICE_NAME = "offloading";
    @org.apache.felix.scr.annotations.Property(value={"offloading"})
    private static final String AGENT_TO_WORKER_PREFIX = "default.transport.agent-to-worker.prefix";
    private static final String AGENT_TO_MASTER_PREFIX_DEFAULT = "offloading_outbox";
    @org.apache.felix.scr.annotations.Property(value={"offloading_outbox"})
    private static final String AGENT_TO_MASTER_PREFIX = "default.transport.agent-to-master.prefix";
    private static final String INPUT_PACKAGE_NAME_DEFAULT = "offloadingInput.zip";
    @org.apache.felix.scr.annotations.Property(value={"offloadingInput.zip"})
    private static final String INPUT_PACKAGE_NAME = "default.transport.input.package";
    private static final String OUTPUT_PACKAGE_NAME_DEFAULT = "offloadingOutput.zip";
    @org.apache.felix.scr.annotations.Property(value={"offloadingOutput.zip"})
    private static final String OUTPUT_PACKAGE_NAME = "default.transport.output.package";
    private static final boolean REPLICATE_SYNCHRONOUS_DEFAULT = true;
    @org.apache.felix.scr.annotations.Property(boolValue={1})
    private static final String REPLICATE_SYNCHRONOUS = "default.transport.replication.synchronous";
    private static final boolean USE_CONTENT_PACKAGE_DEFAULT = true;
    @org.apache.felix.scr.annotations.Property(boolValue={1})
    private static final String USE_CONTENT_PACKAGE = "default.transport.contentpackage";
    private static final boolean TRANSPORT_ENABLED_DEFAULT = false;
    @org.apache.felix.scr.annotations.Property(label="Transport Enabled", description="Allows to enable/disable offloading transport in general.", boolValue={0})
    private static final String TRANSPORT_ENABLED = "offloading.transporter.default.enabled";
    @Reference
    private Replicator replicator;
    @Reference
    private Packaging packaging;
    @Reference
    private ResourceResolverFactory resolverFactory;
    @Reference
    private OffloadingConfigurator configurator;
    private final Logger log;
    private String agentToWorkerPrefix;
    private String agentToMasterPrefix;
    private String inputPackageName;
    private String outputPackageName;
    private boolean replicateSynchronous;
    private boolean useContentPackage;
    private boolean transportEnabled;
    private Map<String, String> transportErrorMap;
    private OffloadingProcessor offloadingProcessor;

    public OffloadingDefaultTransporter() {
        this.log = LoggerFactory.getLogger(this.getClass());
        this.agentToWorkerPrefix = "offloading";
        this.agentToMasterPrefix = "offloading_outbox";
        this.inputPackageName = "offloadingInput.zip";
        this.outputPackageName = "offloadingOutput.zip";
        this.replicateSynchronous = true;
        this.useContentPackage = true;
        this.transportEnabled = false;
        this.transportErrorMap = new ConcurrentHashMap<String, String>();
    }

    @Activate
    protected void activate(Map<String, Object> props) {
        this.offloadingProcessor = new OffloadingProcessor(this, this.configurator, true, "Adobe Granite Offloading: Default Transporter");
        this.modified(props);
    }

    @Modified
    protected void modified(Map<String, Object> props) {
        ValueMapDecorator properties = new ValueMapDecorator(props);
        this.agentToWorkerPrefix = (String)properties.get("default.transport.agent-to-worker.prefix", (Object)"offloading");
        this.agentToMasterPrefix = (String)properties.get("default.transport.agent-to-master.prefix", (Object)"offloading_outbox");
        this.inputPackageName = (String)properties.get("default.transport.input.package", (Object)"offloadingInput.zip");
        this.outputPackageName = (String)properties.get("default.transport.output.package", (Object)"offloadingOutput.zip");
        this.replicateSynchronous = (Boolean)properties.get("default.transport.replication.synchronous", (Object)true);
        this.useContentPackage = (Boolean)properties.get("default.transport.contentpackage", (Object)true);
        this.transportEnabled = (Boolean)properties.get("offloading.transporter.default.enabled", (Object)false);
        if (this.transportEnabled) {
            this.offloadingProcessor.start();
        } else {
            this.offloadingProcessor.stop();
        }
    }

    @Deactivate
    protected void deactivate() {
        this.offloadingProcessor.stop();
        this.offloadingProcessor = null;
    }

    public void handleEvent(Event event) {
        if (this.transportEnabled) {
            this.offloadingProcessor.handleEvent(event);
        }
    }

    public void handleTopologyEvent(TopologyEvent event) {
        if (this.transportEnabled) {
            this.offloadingProcessor.handleTopologyEvent(event);
        }
    }

    private boolean isJobDeleteEvent(Event event) {
        String topic = event.getTopic();
        String path = (String)event.getProperty("path");
        return "org/apache/sling/api/resource/Resource/REMOVED".equals(topic) && path != null && path.startsWith(this.configurator.getSlingJobPath());
    }

    @Override
    public void transportToWorker(Resource offloadingJob) {
        this.log.debug("transport job {} to worker", (Object)offloadingJob.getPath());
        try {
            ValueMap jobProperties = ResourceUtil.getValueMap((Resource)offloadingJob);
            String targetInstance = this.getWorkerInstanceId(jobProperties);
            if (targetInstance != null) {
                this.log.debug("transport job {} to worker {}", (Object)offloadingJob.getPath(), (Object)targetInstance);
                Session replicationSession = (Session)offloadingJob.getResourceResolver().adaptTo(Session.class);
                if (replicationSession == null) {
                    throw new OffloadingException("replication session is null, cannot transport");
                }
                if (this.useContentPackage) {
                    JcrPackage pack = this.createInputPackage(replicationSession, offloadingJob);
                    this.activateToWorker(replicationSession, pack.getNode().getPath(), targetInstance);
                    Resource packageResource = offloadingJob.getResourceResolver().getResource(pack.getNode().getPath());
                    if (packageResource != null) {
                        this.cleanupPackage(packageResource);
                    }
                } else {
                    this.activateJobInput(replicationSession, jobProperties, targetInstance);
                    this.activateToWorker(replicationSession, offloadingJob.getPath(), targetInstance);
                }
            }
        }
        catch (Exception e) {
            throw new OffloadingException(e);
        }
    }

    @Override
    public void transportToMaster(Resource offloadingJob) {
        this.log.debug("transport job {} to master", (Object)offloadingJob.getPath());
        try {
            Session replicationSession = (Session)offloadingJob.getResourceResolver().adaptTo(Session.class);
            if (replicationSession == null) {
                throw new OffloadingException("session is null, cannot transport");
            }
            ValueMap jobProperties = offloadingJob.getValueMap();
            String masterInstance = this.getMasterInstanceId(jobProperties);
            if (this.useContentPackage) {
                JcrPackage pack = this.createOutputPackage(replicationSession, offloadingJob);
                this.activateJobToMaster(replicationSession, pack.getNode().getPath(), masterInstance);
                Resource packageResource = offloadingJob.getResourceResolver().getResource(pack.getNode().getPath());
                if (packageResource != null) {
                    this.cleanupPackage(packageResource);
                }
            } else {
                this.activateJobOutput(replicationSession, jobProperties, masterInstance);
                this.activateJobToMaster(replicationSession, offloadingJob.getPath(), masterInstance);
            }
        }
        catch (Exception e) {
            throw new OffloadingException(e);
        }
    }

    private String getMasterInstanceId(ValueMap offloadingJobProperties) {
        if ("offloading_outbox".equals(this.agentToMasterPrefix)) {
            return null;
        }
        String masterInstance = (String)offloadingJobProperties.get("slingevent:application", String.class);
        if (StringUtils.isBlank((String)masterInstance)) {
            throw new OffloadingException("Master instance ID is blank. Not able to activate to master.");
        }
        return masterInstance;
    }

    private String getWorkerInstanceId(ValueMap offloadingJobProperties) {
        String targetInstance = (String)offloadingJobProperties.get("event.job.application", String.class);
        if (StringUtils.isBlank((String)targetInstance)) {
            throw new OffloadingException("Target instance ID is blank. Not able to activate to worker.");
        }
        return targetInstance;
    }

    private void processJobInput(Resource offloadingJob) throws RepositoryException, PackageException, IOException {
        Resource inputPackage;
        this.log.debug("process input of job {} ", (Object)offloadingJob.getPath());
        Session packageSession = (Session)offloadingJob.getResourceResolver().adaptTo(Session.class);
        if (packageSession == null) {
            throw new OffloadingException("session is null, cannot process input");
        }
        if (this.useContentPackage && (inputPackage = offloadingJob.getChild(this.inputPackageName)) != null) {
            this.installPackage(packageSession, inputPackage);
            this.cleanupPackageManagerSnapshot(packageSession, inputPackage);
            this.cleanupPackage(inputPackage);
        }
    }

    private void processJobOutput(Resource offloadingJob) throws RepositoryException, PackageException, IOException {
        Resource outputPackage;
        this.log.debug("process output of job {} ", (Object)offloadingJob.getPath());
        Session packageSession = (Session)offloadingJob.getResourceResolver().adaptTo(Session.class);
        if (packageSession == null) {
            throw new OffloadingException("session is null, cannot process input");
        }
        if (this.useContentPackage && (outputPackage = offloadingJob.getChild(this.outputPackageName)) != null) {
            this.installPackage(packageSession, outputPackage);
            this.cleanupPackageManagerSnapshot(packageSession, outputPackage);
            this.cleanupPackage(outputPackage);
        }
    }

    private void cleanupPackage(Resource packageResource) throws PersistenceException {
        this.log.debug("cleanup package resource {}", (Object)packageResource.getPath());
        ResourceResolver resolver = packageResource.getResourceResolver();
        if (packageResource != null) {
            Resource packageResourceParent = packageResource.getParent();
            resolver.delete(packageResource);
            if (!packageResourceParent.getChildren().iterator().hasNext()) {
                resolver.delete(packageResourceParent);
            }
        }
    }

    private void cleanupPackageManagerSnapshot(Session packageSession, Resource packageResource) throws RepositoryException, PersistenceException {
        JcrPackageManager packageManager = this.packaging.getPackageManager(packageSession);
        String snapShotPath = packageResource.getParent().getPath();
        snapShotPath = snapShotPath + "/.snapshot";
        snapShotPath = packageManager.getPackageRoot().getPath() + snapShotPath;
        this.log.debug("cleanup package manager snapshot {}", (Object)snapShotPath);
        ResourceResolver resolver = packageResource.getResourceResolver();
        Resource snapshotResource = resolver.getResource(snapShotPath);
        if (snapshotResource != null) {
            Resource snapShotParent = snapshotResource.getParent();
            resolver.delete(snapShotParent);
        }
    }

    private void handleReassignEvent(ResourceResolver resourceResolver, Event event) throws PersistenceException {
        String path = (String)event.getProperty("path");
        String topic = event.getTopic();
        this.log.debug("handle reassign event for topic {} on path {}", (Object)topic, (Object)path);
        String offloadingJobPath = OffloadingUtil.convertSlingJobPathToOffloadingJobPath(this.configurator.getSlingJobPath(), this.configurator.getOffloadingJobPath(), path);
        String inputPackagePath = this.configurator.getPackagePath() + offloadingJobPath + "/" + this.inputPackageName;
        Resource packageResource = resourceResolver.getResource(inputPackagePath);
        if (packageResource != null) {
            this.log.debug("delete package of reassigned job at path {}", (Object)inputPackagePath);
            Resource parent = packageResource.getParent();
            resourceResolver.delete(packageResource);
            if (!parent.getChildren().iterator().hasNext()) {
                resourceResolver.delete(parent);
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Override
    public void processEvent(Event event) {
        this.log.debug("process resource event {}", (Object)event.getTopic());
        ResourceResolver resolver = null;
        try {
            resolver = this.getServiceResolver();
            if (this.isJobPackage(event)) {
                Resource packageResource = this.getPackageResource(resolver, event);
                if (packageResource != null && this.processInputPackage(packageResource)) {
                    Resource jobResource = packageResource.getParent();
                    this.processJobInput(jobResource);
                } else if (packageResource != null && this.processOutputPackage(packageResource)) {
                    Resource jobResource = packageResource.getParent();
                    this.processJobOutput(jobResource);
                } else if (packageResource != null && this.isInvalidOutputPackage(packageResource)) {
                    this.deleteInvalidOutputPackage(resolver, packageResource);
                }
            } else if (this.isJobDeleteEvent(event) && this.offloadingProcessor.isReassignEvent(event)) {
                this.handleReassignEvent(resolver, event);
            }
            if (resolver.hasChanges()) {
                resolver.commit();
            }
        }
        catch (Exception e) {
            this.log.error(e.getMessage(), (Throwable)e);
        }
        finally {
            if (resolver != null) {
                resolver.close();
            }
        }
    }

    @Override
    public boolean doHandleEvent(Event event) {
        return this.isJobPackage(event) || this.isJobDeleteEvent(event);
    }

    private void deleteInvalidOutputPackage(ResourceResolver resolver, Resource packageResource) throws PersistenceException {
        this.log.debug("deleting invalid output package {}", (Object)packageResource.getPath());
        Resource parent = packageResource.getParent();
        resolver.delete(packageResource);
        if (!parent.getChildren().iterator().hasNext()) {
            resolver.delete(parent);
        }
    }

    private boolean processInputPackage(Resource packageResource) {
        String offloadingJobPath;
        boolean processInput = false;
        String packageName = packageResource.getName();
        if (packageName.equals(this.inputPackageName) && (offloadingJobPath = packageResource.getParent().getPath()).startsWith(this.configurator.getPackagePath())) {
            offloadingJobPath = offloadingJobPath.replace(this.configurator.getPackagePath(), "");
            Resource offloadingJob = packageResource.getResourceResolver().getResource(offloadingJobPath);
            String location = "";
            if (offloadingJob != null) {
                ValueMap jobProps = ResourceUtil.getValueMap((Resource)offloadingJob);
                location = (String)jobProps.get(OffloadingJobProperties.LOCATION.propertyName(), (Object)"");
            }
            processInput = StringUtils.isBlank((String)location);
        }
        return processInput;
    }

    private boolean processOutputPackage(Resource packageResource) {
        boolean processOutput = false;
        if (this.isOutPutPackage(packageResource)) {
            Resource offloadingJob = this.getOffloadingJobFromPackage(packageResource);
            String location = "";
            if (offloadingJob != null) {
                ValueMap jobProps = ResourceUtil.getValueMap((Resource)offloadingJob);
                location = (String)jobProps.get(OffloadingJobProperties.LOCATION.propertyName(), (Object)"");
            }
            processOutput = StringUtils.isNotBlank((String)location) && location.endsWith(OffloadingLocations.WORKER.getPropertyValue());
        }
        return processOutput;
    }

    private boolean isInvalidOutputPackage(Resource packageResource) {
        return this.isOutPutPackage(packageResource) && this.getOffloadingJobFromPackage(packageResource) == null;
    }

    private boolean isOutPutPackage(Resource packageResource) {
        boolean isOutPutPackage = false;
        String packageName = packageResource.getName();
        if (this.outputPackageName.equals(packageName)) {
            isOutPutPackage = packageResource.getPath().startsWith(this.configurator.getPackagePath());
        }
        return isOutPutPackage;
    }

    private Resource getOffloadingJobFromPackage(Resource packageResource) {
        Resource offloadingJob = null;
        String offloadingJobPath = packageResource.getParent().getPath();
        if (offloadingJobPath.startsWith(this.configurator.getPackagePath())) {
            offloadingJobPath = offloadingJobPath.replace(this.configurator.getPackagePath(), "");
            offloadingJob = packageResource.getResourceResolver().getResource(offloadingJobPath);
        }
        return offloadingJob;
    }

    private Resource getPackageResource(ResourceResolver resolver, Event event) {
        String path = (String)event.getProperty("path");
        if (StringUtils.isNotBlank((String)path)) {
            return resolver.getResource(path);
        }
        return null;
    }

    private boolean isJobPackage(Event event) {
        boolean isJobPackage = false;
        String path = (String)event.getProperty("path");
        String resourceType = (String)event.getProperty("resourceType");
        Object[] propertyAdded = (String[])event.getProperty("resourceAddedAttributes");
        if (propertyAdded != null && StringUtils.isNotBlank((String)path) && StringUtils.isNotBlank((String)resourceType)) {
            isJobPackage = path.startsWith(this.configurator.getPackagePath()) && !path.contains(".snapshot") && (path.endsWith(this.inputPackageName) || path.endsWith(this.outputPackageName)) && "nt:file".equals(resourceType) && ArrayUtils.contains((Object[])propertyAdded, (Object)"jcr:data");
        }
        return isJobPackage;
    }

    private JcrPackage createInputPackage(Session replicationSession, Resource offloadingJob) throws RepositoryException, PackageException, IOException {
        ValueMap jobProperties = ResourceUtil.getValueMap((Resource)offloadingJob);
        String[] inputPaths = OffloadingUtil.getInputPayloadPaths(jobProperties);
        return this.createTransportPackage(replicationSession, offloadingJob, inputPaths, this.inputPackageName);
    }

    private JcrPackage createOutputPackage(Session replicationSession, Resource offloadingJob) throws RepositoryException, PackageException, IOException {
        ValueMap jobProperties = ResourceUtil.getValueMap((Resource)offloadingJob);
        String[] outputPaths = OffloadingUtil.getOutputPayloadPaths(jobProperties);
        return this.createTransportPackage(replicationSession, offloadingJob, outputPaths, this.outputPackageName);
    }

    private JcrPackage createTransportPackage(Session packageSession, Resource offloadingJob, String[] paths, String packageName) throws RepositoryException, IOException, PackageException {
        JcrPackage pack = null;
        Resource packageResourceBase = this.createPackageResource(offloadingJob);
        Node packageBaseNode = (Node)packageResourceBase.adaptTo(Node.class);
        if (packageBaseNode != null) {
            JcrPackageManager packageManager = this.packaging.getPackageManager(packageSession);
            pack = packageManager.create(packageBaseNode, packageName);
            Node definitionNode = pack.getDefNode();
            Node filterRoot = definitionNode.addNode("filter");
            for (int i = 0; i < paths.length; ++i) {
                String path = paths[i];
                Node filter = filterRoot.addNode("f" + i);
                filter.setProperty("mode", "replace");
                filter.setProperty("root", path);
            }
            Node filter = filterRoot.addNode("f" + paths.length);
            filter.setProperty("mode", "replace");
            filter.setProperty("root", offloadingJob.getPath());
            definitionNode.getSession().save();
            packageManager.assemble(pack, null);
        }
        return pack;
    }

    private Resource createPackageResource(Resource offloadingJob) throws PersistenceException {
        String packagePath = this.configurator.getPackagePath() + offloadingJob.getPath();
        return ResourceUtil.getOrCreateResource((ResourceResolver)offloadingJob.getResourceResolver(), (String)packagePath, (String)"sling:Folder", (String)"sling:Folder", (boolean)true);
    }

    private void installPackage(Session packageSession, Resource packageResource) throws RepositoryException, PackageException, IOException {
        if (packageResource != null) {
            this.log.debug("install package {}", (Object)packageResource.getPath());
            Node packageNode = (Node)packageResource.adaptTo(Node.class);
            JcrPackageManager packageManager = this.packaging.getPackageManager(packageSession);
            JcrPackage pack = packageManager.open(packageNode);
            if (pack != null) {
                ImportOptions opts = new ImportOptions();
                opts.setAutoSaveThreshold(1024);
                opts.setAccessControlHandling(AccessControlHandling.MERGE_PRESERVE);
                pack.install(opts);
            }
        }
    }

    private void activateJobInput(Session replicationSession, ValueMap jobProperties, String targetInstanceId) throws ReplicationException {
        String[] inputPaths;
        for (String path : inputPaths = OffloadingUtil.getInputPayloadPaths(jobProperties)) {
            this.activateToWorker(replicationSession, path, targetInstanceId);
        }
    }

    private void activateToWorker(Session replicationSession, String jobPath, String targetInstanceId) throws ReplicationException {
        this.replicate(replicationSession, jobPath, this.agentToWorkerPrefix, targetInstanceId, ReplicationActionType.ACTIVATE);
    }

    private void activateJobOutput(Session replicationSession, ValueMap jobProperties, String masterInstanceId) throws ReplicationException {
        String[] outputPaths;
        for (String path : outputPaths = OffloadingUtil.getOutputPayloadPaths(jobProperties)) {
            this.replicate(replicationSession, path, this.agentToMasterPrefix, masterInstanceId, ReplicationActionType.ACTIVATE);
        }
    }

    private void activateJobToMaster(Session replicationSession, String jobPath, String masterInstanceId) throws ReplicationException {
        this.replicate(replicationSession, jobPath, this.agentToMasterPrefix, masterInstanceId, ReplicationActionType.ACTIVATE);
    }

    private void transportFailed(String job, String message) {
        this.transportErrorMap.put(job, message);
    }

    private void replicate(Session replicationSession, final String path, String agentPrefix, String instanceId, ReplicationActionType replicationType) throws ReplicationException {
        ReplicationActionType type = ReplicationActionType.ACTIVATE;
        if (type != ReplicationActionType.DELETE) {
            this.replicator.checkPermission(replicationSession, type, path);
        }
        ReplicationOptions options = new ReplicationOptions();
        options.setListener(new ReplicationListener(){

            public void onStart(Agent agent, ReplicationAction replicationAction) {
            }

            public void onMessage(ReplicationLog.Level level, String s) {
            }

            public void onEnd(Agent agent, ReplicationAction replicationAction, ReplicationResult replicationResult) {
                if (replicationResult.isSuccess()) {
                    OffloadingDefaultTransporter.this.log.debug("Transport using replication was successful");
                } else {
                    OffloadingDefaultTransporter.this.transportFailed(path, "Transport failed: " + replicationResult.getCode() + "/" + replicationResult.getMessage());
                }
            }

            public void onError(Agent agent, ReplicationAction replicationAction, Exception e) {
                OffloadingDefaultTransporter.this.transportFailed(path, "Transport error: " + e.getMessage());
            }
        });
        options.setFilter((AgentFilter)new OffloadingAgentFilter(agentPrefix, instanceId));
        options.setSynchronous(this.replicateSynchronous);
        this.replicator.replicate(replicationSession, replicationType, path, options);
        String message = this.transportErrorMap.remove(path);
        if (StringUtils.isNotBlank((String)message)) {
            throw new OffloadingException("Transport error: " + message);
        }
    }

    private ResourceResolver getServiceResolver() throws LoginException {
        HashMap<String, String> authenticationInfo = new HashMap<String, String>();
        authenticationInfo.put("sling.service.subservice", "offloading");
        return this.resolverFactory.getServiceResourceResolver(authenticationInfo);
    }

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

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

    protected void bindPackaging(Packaging packaging) {
        this.packaging = packaging;
    }

    protected void unbindPackaging(Packaging packaging) {
        if (this.packaging == packaging) {
            this.packaging = null;
        }
    }

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

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

    protected void bindConfigurator(OffloadingConfigurator offloadingConfigurator) {
        this.configurator = offloadingConfigurator;
    }

    protected void unbindConfigurator(OffloadingConfigurator offloadingConfigurator) {
        if (this.configurator == offloadingConfigurator) {
            this.configurator = null;
        }
    }

}