ExpiryNotificationJobImpl.java 34.8 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.security.user.UserProperties
 *  com.adobe.granite.security.user.UserPropertiesManager
 *  com.adobe.granite.security.user.UserPropertiesService
 *  com.adobe.granite.taskmanagement.Task
 *  com.adobe.granite.taskmanagement.TaskAction
 *  com.adobe.granite.taskmanagement.TaskManager
 *  com.adobe.granite.taskmanagement.TaskManagerException
 *  com.adobe.granite.taskmanagement.TaskManagerFactory
 *  com.day.cq.commons.Externalizer
 *  com.day.cq.dam.api.Asset
 *  com.day.cq.dam.commons.util.DamUtil
 *  com.day.cq.mailer.MailService
 *  com.day.cq.mailer.MailingException
 *  com.day.cq.replication.AccessDeniedException
 *  com.day.cq.replication.PathNotFoundException
 *  com.day.cq.replication.ReplicationActionType
 *  com.day.cq.replication.Replicator
 *  com.day.cq.search.PredicateGroup
 *  com.day.cq.search.Query
 *  com.day.cq.search.QueryBuilder
 *  com.day.cq.search.result.Hit
 *  com.day.cq.search.result.SearchResult
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.apache.commons.mail.EmailException
 *  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.jackrabbit.api.JackrabbitSession
 *  org.apache.jackrabbit.api.security.user.Authorizable
 *  org.apache.jackrabbit.api.security.user.UserManager
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.commons.scheduler.Job
 *  org.apache.sling.commons.scheduler.JobContext
 *  org.apache.sling.commons.scheduler.Scheduler
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.dam.core.impl;

import com.adobe.granite.security.user.UserProperties;
import com.adobe.granite.security.user.UserPropertiesManager;
import com.adobe.granite.security.user.UserPropertiesService;
import com.adobe.granite.taskmanagement.Task;
import com.adobe.granite.taskmanagement.TaskAction;
import com.adobe.granite.taskmanagement.TaskManager;
import com.adobe.granite.taskmanagement.TaskManagerException;
import com.adobe.granite.taskmanagement.TaskManagerFactory;
import com.day.cq.commons.Externalizer;
import com.day.cq.dam.api.Asset;
import com.day.cq.dam.commons.util.DamUtil;
import com.day.cq.dam.core.impl.MailHelper;
import com.day.cq.mailer.MailService;
import com.day.cq.mailer.MailingException;
import com.day.cq.replication.AccessDeniedException;
import com.day.cq.replication.PathNotFoundException;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.Replicator;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.Hit;
import com.day.cq.search.result.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
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.List;
import java.util.Map;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.commons.mail.EmailException;
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.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.sling.api.resource.LoginException;
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.ValueMap;
import org.apache.sling.commons.scheduler.Job;
import org.apache.sling.commons.scheduler.JobContext;
import org.apache.sling.commons.scheduler.Scheduler;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1, label="Adobe CQ DAM Expiry Notification", description="Adobe CQ DAM Expiry Notification")
public class ExpiryNotificationJobImpl
implements Job {
    private static final Logger log = LoggerFactory.getLogger(ExpiryNotificationJobImpl.class);
    @Reference
    private Scheduler scheduler;
    @Reference
    private ResourceResolverFactory resolverFactory;
    @Reference
    private QueryBuilder queryBuilder;
    @Reference(cardinality=ReferenceCardinality.OPTIONAL_UNARY, policy=ReferencePolicy.DYNAMIC)
    private MailService mailer;
    @Reference
    Externalizer externalizerService = null;
    @Reference
    UserPropertiesService userPropertiesService;
    @Reference
    private Replicator replicator;
    @org.apache.felix.scr.annotations.Property(boolValue={1}, label="Time based Scheduler", description="Whether to schedule a time based schedular")
    public static final String SCHEDULE_TIME_BASED = "cq.dam.expiry.notification.scheduler.istimebased";
    @org.apache.felix.scr.annotations.Property(value={"0 0 0 * * ?"}, label="Time Based Scheduler Rule", description="Regular expression for time based Scheduler. Eg: '0 0 0 * * ?'. The example expression triggers the Job @ 00 hrs. This expression get picked if Time Based Scheduler is true")
    public static final String SCHEDULER_TIMEBASED_RULE = "cq.dam.expiry.notification.scheduler.timebased.rule";
    @org.apache.felix.scr.annotations.Property(longValue={10}, label="Preiodic Scheduler", description="Time in seconds for periodic scheduler. This expression get picked if Time Based Scheduler is set false")
    public static final String SCHEDULER_PERIOD = "cq.dam.expiry.notification.scheduler.period.rule";
    @org.apache.felix.scr.annotations.Property(boolValue={0}, name="send_email", label="send email", description="Send emails on asset expiry")
    public static final String CONFIG_SEND_EMAIL = "send_email";
    @org.apache.felix.scr.annotations.Property(longValue={86400}, name="prior_notification_seconds", label="Prior notification in seconds", description="Number of seconds before which a notification should be sent before an asset expires")
    public static final String PRIOR_NOTIFICATION_SECONDS = "prior_notification_seconds";
    @org.apache.felix.scr.annotations.Property(value={"http"}, label="Protocol", description="Protocol")
    public static final String PROTOCOL = "cq.dam.expiry.notification.url.protocol";
    public static final String TASK_TYPE = "Notification";
    private static final String EXPIRY_MONITORING_SERVICE = "expirymonitoringhelper";
    private static final String NOTIFICATION_SERVICE = "notificationhelper";
    private static final String ASSET_REPLICATION_SERVICE = "assetreplicationhelper";
    private boolean sendEmail;
    private String protocol;
    private static Calendar LAST_RUN;
    private static Calendar THIS_RUN;
    private long priorNotificationInSeconds;

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public void execute(JobContext arg0) {
        ResourceResolver assetResolver = null;
        ResourceResolver notificationResolver = null;
        ResourceResolver replicationResolver = null;
        THIS_RUN = Calendar.getInstance();
        try {
            assetResolver = this.resolverFactory.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "expirymonitoringhelper"));
            Collection<Hit> expiredAssets = this.getExpiredAssetHits(assetResolver);
            Collection<Hit> toExpireAssets = this.getToexpireAssetHits(assetResolver);
            Collection<Asset> expireRefererAssets = this.propagateExpiry(assetResolver, expiredAssets);
            this.dePropagateExpiry(assetResolver);
            notificationResolver = this.resolverFactory.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "notificationhelper"));
            Notification notification = new Notification(assetResolver, notificationResolver, expiredAssets, toExpireAssets, expireRefererAssets);
            notification.sendPriorInboxNotification();
            notification.sendExpiryInBoxNotification();
            notification.sendRefExpiryInBoxNotification();
            if (this.sendEmail) {
                notification.sendPriorEmailNotification();
                notification.sendExpiryEmailNotification();
                notification.sendRefExpiryEmailNotification();
            }
            assetResolver.close();
            notificationResolver.close();
            assetResolver = null;
            notificationResolver = null;
            replicationResolver = this.resolverFactory.getServiceResourceResolver(Collections.singletonMap("sling.service.subservice", "assetreplicationhelper"));
            PublishOrUnPublishAssets publishOrUnPublishAssets = new PublishOrUnPublishAssets(replicationResolver, "Deactivate");
            ArrayList<String> assetPaths = new ArrayList<String>();
            for (Hit hit : expiredAssets) {
                assetPaths.add(hit.getPath());
            }
            for (Asset each : expireRefererAssets) {
                assetPaths.add(each.getPath());
            }
            publishOrUnPublishAssets.action(assetPaths);
            replicationResolver.close();
            replicationResolver = null;
        }
        catch (Exception e) {
            log.error("Error in execute.", (Throwable)e);
        }
        finally {
            if (null != assetResolver) {
                assetResolver.close();
            }
            if (null != notificationResolver) {
                notificationResolver.close();
            }
            if (null != replicationResolver) {
                replicationResolver.close();
            }
        }
        LAST_RUN = THIS_RUN;
    }

    private Collection<Asset> propagateExpiry(ResourceResolver resolver, Collection<Hit> hits) throws RepositoryException {
        Session session = (Session)resolver.adaptTo(Session.class);
        Collection<Asset> expiredSinceLastRun = this.getExpiredAssets(resolver, hits);
        ArrayList<Asset> expireRefererAssets = new ArrayList<Asset>();
        for (Asset each : expiredSinceLastRun) {
            Asset asset;
            String path = each.getPath();
            Collection refererAssets = DamUtil.getRefererAssets((ResourceResolver)resolver, (String)each.getPath());
            Resource res = resolver.getResource(path);
            if (DamUtil.isSubAsset((Resource)res) && null != (asset = DamUtil.getParentAsset((Resource)res))) {
                refererAssets.add(asset);
            }
            expireRefererAssets.addAll(refererAssets);
            for (Asset refAsset : refererAssets) {
                Node refNode = (Node)resolver.getResource(refAsset.getPath()).adaptTo(Node.class);
                refNode.getNode("jcr:content/metadata").setProperty("refExpired", true);
            }
        }
        session.save();
        return expireRefererAssets;
    }

    private Collection<Asset> getExpiredAssets(ResourceResolver resolver, Collection<Hit> hits) throws RepositoryException {
        ArrayList<Asset> expiredSinceLastRun = new ArrayList<Asset>();
        if (hits.size() > 0) {
            for (Hit hit : hits) {
                Resource res = resolver.getResource(hit.getPath());
                Asset asset = null;
                if (null == res || null == (asset = (Asset)res.adaptTo(Asset.class))) continue;
                expiredSinceLastRun.add(asset);
            }
        }
        return expiredSinceLastRun;
    }

    private void dePropagateExpiry(ResourceResolver resolver) throws RepositoryException {
        Calendar now = Calendar.getInstance();
        Collection<Asset> expiredRefAssets = this.getExpiredRefAssets(resolver);
        for (Asset each : expiredRefAssets) {
            List subAssets = DamUtil.getReferencedSubAssets((Resource)resolver.getResource(each.getPath()));
            subAssets.addAll(DamUtil.getSubAssets((Resource)resolver.getResource(each.getPath())));
            boolean toChangeStatus = true;
            for (Asset each1 : subAssets) {
                Calendar expiryTime;
                Node node = (Node)resolver.getResource(each1.getPath()).adaptTo(Node.class);
                if (!node.hasProperty("jcr:content/metadata/prism:expirationDate") || !(expiryTime = node.getProperty("jcr:content/metadata/prism:expirationDate").getDate()).before(now)) continue;
                toChangeStatus = false;
                break;
            }
            if (!toChangeStatus) continue;
            Node eachNode = (Node)resolver.getResource(each.getPath()).adaptTo(Node.class);
            eachNode.getNode("jcr:content/metadata").setProperty("refExpired", false);
        }
        ((Session)resolver.adaptTo(Session.class)).save();
    }

    private Collection<Asset> getExpiredRefAssets(ResourceResolver resolver) throws RepositoryException {
        Collection<Hit> hits = this.getExpiredRefAssetHits(resolver);
        ArrayList<Asset> expiredRefAssets = new ArrayList<Asset>();
        if (hits.size() > 0) {
            for (Hit hit : hits) {
                Resource res = resolver.getResource(hit.getPath());
                Asset asset = null;
                if (null == res || null == (asset = (Asset)res.adaptTo(Asset.class))) continue;
                expiredRefAssets.add(asset);
            }
        }
        return expiredRefAssets;
    }

    private Collection<Hit> getExpiredAssetHits(ResourceResolver resolver) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("path", "/content/dam");
        map.put("type", "dam:Asset");
        map.put("1_daterange.property", "jcr:content/metadata/prism:expirationDate");
        map.put("1_daterange.lowerBound", "" + LAST_RUN.getTimeInMillis());
        map.put("1_daterange.upperBound", "" + THIS_RUN.getTimeInMillis());
        Query query = this.queryBuilder.createQuery(PredicateGroup.create(map), (Session)resolver.adaptTo(Session.class));
        SearchResult results = query.getResult();
        return results.getHits();
    }

    private Collection<Hit> getToexpireAssetHits(ResourceResolver resolver) {
        long priorNotificationInMillis = this.priorNotificationInSeconds * 1000;
        long thisRunTime = THIS_RUN.getTimeInMillis();
        long lastRunTime = LAST_RUN.getTimeInMillis();
        long startTime = thisRunTime;
        long endTime = thisRunTime + priorNotificationInMillis;
        if (priorNotificationInMillis > thisRunTime - lastRunTime) {
            startTime = priorNotificationInMillis + lastRunTime;
        }
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("path", "/content/dam");
        map.put("type", "dam:Asset");
        map.put("1_daterange.property", "jcr:content/metadata/prism:expirationDate");
        map.put("1_daterange.lowerBound", "" + startTime);
        map.put("1_daterange.upperBound", "" + endTime);
        Query query = this.queryBuilder.createQuery(PredicateGroup.create(map), (Session)resolver.adaptTo(Session.class));
        SearchResult results = query.getResult();
        return results.getHits();
    }

    private Collection<Hit> getExpiredRefAssetHits(ResourceResolver resolver) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("path", "/content/dam");
        map.put("type", "dam:Asset");
        map.put("1_property", "jcr:content/metadata/refExpired");
        map.put("1_property.value", "true");
        Query query = this.queryBuilder.createQuery(PredicateGroup.create(map), (Session)resolver.adaptTo(Session.class));
        SearchResult results = query.getResult();
        return results.getHits();
    }

    protected void activate(ComponentContext componentContext) throws Exception {
        try {
            LAST_RUN = Calendar.getInstance();
            LAST_RUN.set(11, 0);
            LAST_RUN.set(12, 0);
            LAST_RUN.set(13, 0);
            LAST_RUN.set(14, 0);
            boolean isTimeBased = (Boolean)componentContext.getProperties().get("cq.dam.expiry.notification.scheduler.istimebased");
            if (isTimeBased) {
                String expression = (String)componentContext.getProperties().get("cq.dam.expiry.notification.scheduler.timebased.rule");
                this.scheduler.addJob(ExpiryNotificationJobImpl.class.getName(), (Object)this, null, expression, false);
            } else {
                long periodinsecs = (Long)componentContext.getProperties().get("cq.dam.expiry.notification.scheduler.period.rule");
                this.scheduler.addPeriodicJob(ExpiryNotificationJobImpl.class.getName(), (Object)this, null, periodinsecs, false);
            }
            this.sendEmail = (Boolean)componentContext.getProperties().get("send_email");
            this.priorNotificationInSeconds = (Long)componentContext.getProperties().get("prior_notification_seconds");
            this.protocol = (String)componentContext.getProperties().get("cq.dam.expiry.notification.url.protocol");
        }
        catch (Exception e) {
            log.error("Error in activate.", (Throwable)e);
            throw e;
        }
    }

    protected void deactivate(ComponentContext componentContext) {
        log.debug("Deactivating the expiry notification scheduler");
        this.scheduler.removeJob(ExpiryNotificationJobImpl.class.getName());
    }

    protected void bindScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    protected void unbindScheduler(Scheduler scheduler) {
        if (this.scheduler == scheduler) {
            this.scheduler = null;
        }
    }

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

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

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

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

    protected void bindMailer(MailService mailService) {
        this.mailer = mailService;
    }

    protected void unbindMailer(MailService mailService) {
        if (this.mailer == mailService) {
            this.mailer = null;
        }
    }

    protected void bindExternalizerService(Externalizer externalizer) {
        this.externalizerService = externalizer;
    }

    protected void unbindExternalizerService(Externalizer externalizer) {
        if (this.externalizerService == externalizer) {
            this.externalizerService = null;
        }
    }

    protected void bindUserPropertiesService(UserPropertiesService userPropertiesService) {
        this.userPropertiesService = userPropertiesService;
    }

    protected void unbindUserPropertiesService(UserPropertiesService userPropertiesService) {
        if (this.userPropertiesService == userPropertiesService) {
            this.userPropertiesService = null;
        }
    }

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

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

    private class Notification {
        ResourceResolver assetResolver;
        ResourceResolver notificationResolver;
        Map<String, Set<String>> expiredAssetsWithUser;
        Map<String, Set<String>> toExpireAssetsWithUser;
        Map<String, Set<String>> expiredRefAssetsWithUser;
        UserPropertiesManager upm;

        public Notification(ResourceResolver assetResolver, ResourceResolver notificationResolver, Collection<Hit> expiredAssets, Collection<Hit> toExpireAssets, Collection<Asset> expiredRefAssets) throws RepositoryException {
            HashSet<String> set;
            Resource res;
            String createdBy;
            Asset asset;
            this.assetResolver = assetResolver;
            this.notificationResolver = notificationResolver;
            this.upm = ExpiryNotificationJobImpl.this.userPropertiesService.createUserPropertiesManager((Session)notificationResolver.adaptTo(Session.class), notificationResolver);
            this.expiredAssetsWithUser = new HashMap<String, Set<String>>();
            this.expiredRefAssetsWithUser = new HashMap<String, Set<String>>();
            this.toExpireAssetsWithUser = new HashMap<String, Set<String>>();
            for (Hit each22 : expiredAssets) {
                res = assetResolver.getResource(each22.getPath());
                asset = null;
                if (null == res || null == (asset = (Asset)res.adaptTo(Asset.class))) continue;
                createdBy = (String)((ValueMap)res.adaptTo(ValueMap.class)).get("jcr:createdBy", String.class);
                if (this.expiredAssetsWithUser.containsKey(createdBy)) {
                    this.expiredAssetsWithUser.get(createdBy).add(each22.getPath());
                    continue;
                }
                set = new HashSet<String>();
                set.add(each22.getPath());
                this.expiredAssetsWithUser.put(createdBy, set);
            }
            for (Hit each : toExpireAssets) {
                res = assetResolver.getResource(each.getPath());
                asset = null;
                if (null == res || null == (asset = (Asset)res.adaptTo(Asset.class))) continue;
                createdBy = (String)((ValueMap)res.adaptTo(ValueMap.class)).get("jcr:createdBy", String.class);
                if (this.toExpireAssetsWithUser.containsKey(createdBy)) {
                    this.toExpireAssetsWithUser.get(createdBy).add(each.getPath());
                    continue;
                }
                set = new HashSet();
                set.add(each.getPath());
                this.toExpireAssetsWithUser.put(createdBy, set);
            }
            for (Asset each2 : expiredRefAssets) {
                res = assetResolver.getResource(each2.getPath());
                asset = null;
                if (null == res || null == (asset = (Asset)res.adaptTo(Asset.class))) continue;
                createdBy = (String)((ValueMap)res.adaptTo(ValueMap.class)).get("jcr:createdBy", String.class);
                if (this.expiredRefAssetsWithUser.containsKey(createdBy)) {
                    this.expiredRefAssetsWithUser.get(createdBy).add(each2.getPath());
                    continue;
                }
                set = new HashSet();
                set.add(each2.getPath());
                this.expiredRefAssetsWithUser.put(createdBy, set);
            }
        }

        public void sendPriorInboxNotification() throws TaskManagerException {
            if (null == this.toExpireAssetsWithUser || this.toExpireAssetsWithUser.isEmpty()) {
                return;
            }
            Iterator<Map.Entry<String, Set<String>>> entries = this.toExpireAssetsWithUser.entrySet().iterator();
            TaskManager tm = (TaskManager)this.notificationResolver.adaptTo(TaskManager.class);
            TaskManagerFactory tmf = tm.getTaskManagerFactory();
            StringBuffer description = new StringBuffer("Following Assets are about to expired:\n");
            while (entries.hasNext()) {
                Map.Entry<String, Set<String>> entry = entries.next();
                Set<String> asstePaths = entry.getValue();
                for (String each : asstePaths) {
                    description.append("\n" + each);
                }
                Task newTask = tmf.newTask("Notification");
                newTask.setName("ASSETS ABOUT TO EXPIRE");
                TaskAction newTaskAction = tmf.newTaskAction("Remove");
                newTask.setActions(Collections.singletonList(newTaskAction));
                newTask.setContentPath("/content/dam");
                newTask.setCurrentAssignee(entry.getKey());
                newTask.setDescription(description.toString());
                tm.createTask(newTask);
            }
        }

        public void sendPriorEmailNotification() throws RepositoryException, MailingException, IOException, LoginException, EmailException {
            if (null == this.toExpireAssetsWithUser || this.toExpireAssetsWithUser.isEmpty()) {
                return;
            }
            Iterator<Map.Entry<String, Set<String>>> entries = this.toExpireAssetsWithUser.entrySet().iterator();
            while (entries.hasNext()) {
                String email;
                HashMap<String, String> parameters = new HashMap<String, String>();
                Map.Entry<String, Set<String>> entry = entries.next();
                Set<String> asstePaths = entry.getValue();
                parameters.put("templateRootPath", "/etc/notification/email/default/com.adobe.cq.dam.asset.expiry.prior/en.txt");
                StringBuffer allAssetPaths = new StringBuffer("");
                for (String each : asstePaths) {
                    allAssetPaths.append("\n" + each);
                }
                parameters.put("assetpaths", allAssetPaths.toString());
                parameters.put("hostUserFullName", "AEM TEAM");
                String assetsLink = ExpiryNotificationJobImpl.this.externalizerService.externalLink(this.assetResolver, "author", ExpiryNotificationJobImpl.this.protocol, "/assets.html/content/dam");
                parameters.put("assetlink", assetsLink);
                UserManager um = ((JackrabbitSession)this.notificationResolver.adaptTo(Session.class)).getUserManager();
                Authorizable user = um.getAuthorizable(entry.getKey());
                UserProperties up = this.upm.getUserProperties(user, "profile");
                String string = email = up == null ? "" : up.getProperty("email");
                if (!ExpiryNotificationJobImpl.this.sendEmail || email == null || email.equals("")) continue;
                MailHelper.sendMail((Session)this.notificationResolver.adaptTo(Session.class), ExpiryNotificationJobImpl.this.mailer, Collections.singletonMap(up.getDisplayName(), email), parameters);
            }
        }

        public void sendExpiryInBoxNotification() throws TaskManagerException {
            if (null == this.expiredAssetsWithUser || this.expiredAssetsWithUser.isEmpty()) {
                return;
            }
            Iterator<Map.Entry<String, Set<String>>> entries = this.expiredAssetsWithUser.entrySet().iterator();
            TaskManager tm = (TaskManager)this.notificationResolver.adaptTo(TaskManager.class);
            TaskManagerFactory tmf = tm.getTaskManagerFactory();
            StringBuffer description = new StringBuffer("Following Assets are expired:\n");
            while (entries.hasNext()) {
                Map.Entry<String, Set<String>> entry = entries.next();
                Set<String> asstePaths = entry.getValue();
                for (String each : asstePaths) {
                    description.append("\n" + each);
                }
                Task newTask = tmf.newTask("Notification");
                newTask.setName("ASSETS EXPIRED");
                TaskAction newTaskAction = tmf.newTaskAction("Remove");
                newTask.setActions(Collections.singletonList(newTaskAction));
                newTask.setContentPath("/content/dam");
                newTask.setCurrentAssignee(entry.getKey());
                newTask.setDescription(description.toString());
                tm.createTask(newTask);
            }
        }

        public void sendRefExpiryInBoxNotification() throws TaskManagerException {
            if (null == this.expiredRefAssetsWithUser || this.expiredRefAssetsWithUser.isEmpty()) {
                return;
            }
            Iterator<Map.Entry<String, Set<String>>> entries = this.expiredRefAssetsWithUser.entrySet().iterator();
            TaskManager tm = (TaskManager)this.notificationResolver.adaptTo(TaskManager.class);
            TaskManagerFactory tmf = tm.getTaskManagerFactory();
            StringBuffer description = new StringBuffer("Following Assets have expired subassets:\n");
            while (entries.hasNext()) {
                Map.Entry<String, Set<String>> entry = entries.next();
                Set<String> asstePaths = entry.getValue();
                for (String each : asstePaths) {
                    description.append("\n" + each);
                }
                Task newTask = tmf.newTask("Notification");
                newTask.setName("SUBASSETS EXPIRED");
                TaskAction newTaskAction = tmf.newTaskAction("Remove");
                newTask.setActions(Collections.singletonList(newTaskAction));
                newTask.setContentPath("/content/dam");
                newTask.setCurrentAssignee(entry.getKey());
                newTask.setDescription(description.toString());
                tm.createTask(newTask);
            }
        }

        public void sendExpiryEmailNotification() throws RepositoryException, MailingException, IOException, LoginException, EmailException {
            if (null == this.expiredAssetsWithUser || this.expiredAssetsWithUser.isEmpty()) {
                return;
            }
            Iterator<Map.Entry<String, Set<String>>> entries = this.expiredAssetsWithUser.entrySet().iterator();
            while (entries.hasNext()) {
                String email;
                HashMap<String, String> parameters = new HashMap<String, String>();
                Map.Entry<String, Set<String>> entry = entries.next();
                Set<String> asstePaths = entry.getValue();
                parameters.put("templateRootPath", "/etc/notification/email/default/com.adobe.cq.dam.asset.expiry/en.txt");
                StringBuffer allAssetPaths = new StringBuffer("");
                for (String each : asstePaths) {
                    allAssetPaths.append("\n" + each);
                }
                parameters.put("assetpaths", allAssetPaths.toString());
                parameters.put("hostUserFullName", "AEM TEAM");
                String assetsLink = ExpiryNotificationJobImpl.this.externalizerService.externalLink(this.assetResolver, "author", ExpiryNotificationJobImpl.this.protocol, "/assets.html/content/dam");
                parameters.put("assetlink", assetsLink);
                UserManager um = ((JackrabbitSession)this.notificationResolver.adaptTo(Session.class)).getUserManager();
                Authorizable user = um.getAuthorizable(entry.getKey());
                UserProperties up = this.upm.getUserProperties(user, "profile");
                String string = email = up == null ? "" : up.getProperty("email");
                if (!ExpiryNotificationJobImpl.this.sendEmail || email == null || email.equals("")) continue;
                MailHelper.sendMail((Session)this.notificationResolver.adaptTo(Session.class), ExpiryNotificationJobImpl.this.mailer, Collections.singletonMap(up.getDisplayName(), email), parameters);
            }
        }

        public void sendRefExpiryEmailNotification() throws RepositoryException, MailingException, IOException, LoginException, EmailException {
            if (null == this.expiredRefAssetsWithUser || this.expiredRefAssetsWithUser.isEmpty()) {
                return;
            }
            Iterator<Map.Entry<String, Set<String>>> entries = this.expiredRefAssetsWithUser.entrySet().iterator();
            while (entries.hasNext()) {
                String email;
                HashMap<String, String> parameters = new HashMap<String, String>();
                Map.Entry<String, Set<String>> entry = entries.next();
                Set<String> asstePaths = entry.getValue();
                parameters.put("templateRootPath", "/etc/notification/email/default/com.adobe.cq.dam.asset.refexpiry/en.txt");
                StringBuffer allAssetPaths = new StringBuffer("");
                for (String each : asstePaths) {
                    allAssetPaths.append("\n" + each);
                }
                parameters.put("assetpaths", allAssetPaths.toString());
                parameters.put("hostUserFullName", "AEM TEAM");
                String assetsLink = ExpiryNotificationJobImpl.this.externalizerService.externalLink(this.assetResolver, "author", ExpiryNotificationJobImpl.this.protocol, "/assets.html/content/dam");
                parameters.put("assetlink", assetsLink);
                UserManager um = ((JackrabbitSession)this.notificationResolver.adaptTo(Session.class)).getUserManager();
                Authorizable user = um.getAuthorizable(entry.getKey());
                UserProperties up = this.upm.getUserProperties(user, "profile");
                String string = email = up == null ? "" : up.getProperty("email");
                if (!ExpiryNotificationJobImpl.this.sendEmail || email == null || email.equals("")) continue;
                MailHelper.sendMail((Session)this.notificationResolver.adaptTo(Session.class), ExpiryNotificationJobImpl.this.mailer, Collections.singletonMap(up.getDisplayName(), email), parameters);
            }
        }
    }

    private class PublishOrUnPublishAssets {
        ResourceResolver resolver;
        ReplicationActionType action;

        public PublishOrUnPublishAssets(ResourceResolver resolver, String action) {
            this.resolver = resolver;
            this.action = ReplicationActionType.fromName((String)action);
            if (null == this.resolver || null == this.action) {
                throw new RuntimeException("Cannot read the action type or resource resolver");
            }
        }

        public void action(Collection<String> assets) {
            Session session = (Session)this.resolver.adaptTo(Session.class);
            if (null == ExpiryNotificationJobImpl.this.replicator) {
                log.error("Replicator service is not available");
                return;
            }
            if (null == assets || assets.size() < 1) {
                log.info("No assets passed to deactivate.");
                return;
            }
            for (String eachPath : assets) {
                try {
                    ExpiryNotificationJobImpl.this.replicator.replicate(session, this.action, eachPath);
                }
                catch (PathNotFoundException pnfe) {
                    log.error("Path not found for replication: " + eachPath);
                }
                catch (AccessDeniedException ade) {
                    log.debug(this.resolver.getUserID() + " is not allowed to replicate " + "this resource " + eachPath + ". Issuing request for 'replication");
                }
                catch (Throwable e) {
                    log.error("Error during replication: " + e.getMessage(), e);
                }
            }
        }
    }

}