Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
5.6 kB
2
Indexable
Never
package org.aarp.stayingsharp.core.schedulers;

import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.Replicator;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.SearchResult;
import com.day.cq.wcm.api.Page;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.scheduler.ScheduleOptions;
import org.apache.sling.commons.scheduler.Scheduler;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.service.component.annotations.*;
import org.osgi.service.metatype.annotations.AttributeDefinition;
import org.osgi.service.metatype.annotations.Designate;
import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.Session;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.aarp.foundation.api.ServiceUserConstants;

@Component(service = Runnable.class, immediate = true, configurationPolicy = ConfigurationPolicy.REQUIRE, property = {})
@Designate(ocd = AssetMonitorScheduler.Configuration.class)
public class AssetMonitorScheduler implements Runnable {

    private Logger log = LoggerFactory.getLogger(AssetMonitorScheduler.class);

    public static final String DAM_PATH ="/content/dam/specialized-membership/staying-sharp/articles";

    public static final String DEFAULT_CRON_EXPRESSION = "0 0 0 ? * *";

    @Reference
    private Scheduler scheduler;
    @Reference
    private Replicator replicator;


    /** The sling settings service. */
    @Reference
    private SlingSettingsService slingSettingsService;
    @Reference
    private ResourceResolverFactory resolverFactory;

    @Override
    public void run() {
        log.debug("run method");

        if (slingSettingsService.getRunModes().contains("author")) {
            try (ResourceResolver aarpResolver = resolverFactory.getServiceResourceResolver(Collections.singletonMap(
                    ResourceResolverFactory.SUBSERVICE, ServiceUserConstants.ADMINISTRATIVE_SERVICE_USER))) {
                log.debug("author");
                Session jcrSession = aarpResolver.adaptTo(Session.class);
                QueryBuilder builder = aarpResolver.adaptTo(QueryBuilder.class);
                Map<String, String> map = new HashMap<String, String>();
                map.put("path", DAM_PATH);
                map.put("property", "jcr:primaryType");
                map.put("property.value","dam:Asset");
                map.put("p.limit", "-1");
                log.debug("query done");
                com.day.cq.search.Query query = builder.createQuery(PredicateGroup.create(map), jcrSession);
                SearchResult result = query.getResult();
                log.debug("query results {}", result.toString());
                Iterator<Page> pageList = null;
                if (result != null) {
                    log.debug("result{}", result.getNodes().toString());
                    while (null != pageList && pageList.hasNext()) {
                        log.debug("pageList {}", pageList.toString());
                        Page page = pageList.next();
                        boolean isReplicated = replicator.getReplicationStatus(jcrSession, page.getPath()).isActivated();
                        if(!isReplicated){
                            log.debug("page path {}", page.getPath());
                            replicator.replicate(aarpResolver.adaptTo(Session.class), ReplicationActionType.ACTIVATE, page.getPath());
                        }
                    }

                }
            } catch (ReplicationException | LoginException e) {
                log.error("Error in SiteMapJob {}", e.getMessage());
            }
        }
    }
    @Activate
    protected void activate(final AssetMonitorScheduler.Configuration config) {
        log.debug("Inside Activate Method::");

    }

    /*
     * Method called to add scheduler for cron expression.
     */
    private void addScheduler(AssetMonitorScheduler.Configuration config) {
        log.debug("Inside add scheduler::");
        ScheduleOptions sOpts = scheduler.EXPR(config.monitorExpresssion());
        sOpts.name("damAsset");
        sOpts.canRunConcurrently(false);
        scheduler.schedule(this, sOpts);
        log.debug("Scheduler added successfully");

    }

    /*
     * Method called when service is modified.
     */
    @Modified
    protected void modified(final AssetMonitorScheduler.Configuration config) {
        log.debug("Inside Modified Method::");
        removeScheduler();
    }

    /*
     * Method called when service is deactivated.
     */
    @Deactivate
    protected void deactivate() {
        log.debug(" service is deactivated.");
        removeScheduler();
    }

    /*
     * Method called to remove existing scheduler.
     */
    private void removeScheduler() {
        log.debug("Removing scheduler");
        scheduler.unschedule("damAsset");
    }


    @ObjectClassDefinition(name = "Asset Monitor Scheduler", description = "Asset Monitor Scheduler to monitor dam assets")
    public static @interface Configuration {

        @AttributeDefinition(name ="expression")
        String monitorExpresssion() default DEFAULT_CRON_EXPRESSION;

        @AttributeDefinition(name = "DamAsset Folder Path")
        String damPath() default  DAM_PATH;

    }
}