Highlighted

Copy Assets from crx to Physical server location

Avatar

Avatar

santhosha583576

Avatar

santhosha583576

santhosha583576

27-11-2018

I am trying to Copy the asstes from crx to physical server location based on their Metadata (ex release date). So based on the Metadata a listener has to create a scheduler and deploy it to the physical server.

package sampleforms.core.listener;

import java.io.Serializable;

import java.util.Calendar;

import java.util.Date;

import java.util.HashMap;

import java.util.Map;

import javax.jcr.Node;

import javax.jcr.Property;

import javax.jcr.RepositoryException;

import javax.jcr.Session;

import javax.jcr.observation.Event;

import javax.jcr.observation.EventIterator;

import javax.jcr.observation.EventListener;

import javax.jcr.observation.ObservationManager;

import org.apache.jackrabbit.api.observation.JackrabbitEventFilter;

import org.apache.jackrabbit.api.observation.JackrabbitObservationManager;

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.commons.scheduler.Scheduler;

import org.apache.sling.jcr.api.SlingRepository;

import org.osgi.service.component.ComponentContext;

import org.osgi.service.component.annotations.Component;

import org.osgi.service.component.annotations.Reference;

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 com.day.cq.dam.api.Asset;

import com.day.cq.dam.api.Rendition;

@Component(immediate = true, service = EventListener.class)

public class DeployAssetsHandler implements EventListener {

private final Logger logger = LoggerFactory.getLogger(getClass());

// Inject a Sling ResourceResolverFactory

@Reference

private ResourceResolverFactory resolverFactory;

private Session observationSession = null;

private JackrabbitObservationManager observationManager;

@Reference

private SlingRepository repository;

@Reference

private Scheduler scheduler;

    public static final String DEPLOY_DATE_PROPERTY = "deploy_date";

private String damPathImages;

private String serverPathImages;

private final String[] nodeTypes = new String[] { "nt:unstructured" };

// Place app logic here to define the AEM Custom Event Handler

protected void activate() {

damPathImages = "/content/dam/images";

serverPathImages = "Physical server location";

logger.debug("activate: DAM PATH='{}''", damPathImages);

try {

// Invoke the adaptTo method to create a Session

// ResourceResolver resourceResolver =

// resolverFactory.getAdministrativeResourceResolver(null);

observationSession = repository.loginAdministrative(null);

// Setup the event handler to respond to a new claim under

// content/claim....

observationManager = (JackrabbitObservationManager) observationSession.getWorkspace()

.getObservationManager();

JackrabbitEventFilter eventFilter = new JackrabbitEventFilter()

             .setAbsPath(damPathImages)

             .setEventTypes(Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED)

             .setIsDeep(true)

             .setNodeTypes(nodeTypes)

             .setNoLocal(false)

             .setNoExternal(false);

observationManager.addEventListener(this,eventFilter);

logger.info("Observing property changes to {} ", damPathImages);

} catch (Exception e) {

logger.error("Exception {} ", e);

}

}

protected void deactivate(ComponentContext componentContext)

throws RepositoryException {

try {

if (observationManager != null) {

observationManager.removeEventListener(this);

}

} catch (Exception e) {

logger.error("Exception {} ", e);

}

if (observationSession != null) {

observationSession.logout();

observationSession = null;

}

}

// when the event occurred.

public void onEvent(EventIterator it) {

while (it.hasNext()) {

Event event = it.nextEvent();

try {

logger.info("{} property event: ------->>>>> {}",DEPLOY_DATE_PROPERTY, event.getPath());

Property changedProperty = observationSession.getProperty(event

.getPath());

if (changedProperty.getName().equalsIgnoreCase(DEPLOY_DATE_PROPERTY)) {

Date date = changedProperty.getValue().getDate().getTime();

Date currentDate = new Date();

if (date.getTime() >= currentDate.getTime()) {

Calendar deplotDate = (Calendar) changedProperty

.getValue().getDate();

String cronExpression = deplotDate.get(Calendar.SECOND)

+ " " + deplotDate.get(Calendar.MINUTE) + " "

+ deplotDate.get(Calendar.HOUR_OF_DAY) + " "

+ deplotDate.get(Calendar.DAY_OF_MONTH) + " "

+ (deplotDate.get(Calendar.MONTH)+1) + " ? "

+ deplotDate.get(Calendar.YEAR);

logger.info("cron: {}", cronExpression);

String assetPath = event.getPath().split("/jcr:content")[0];

Node damResorce = observationSession.getNode(assetPath);

String jobName = damResorce.getName();

scheduleWork(assetPath, serverPathImages, cronExpression,jobName);

}

}

} catch (Exception e) {

logger.error(e.getMessage(), e);

}

}

}

@SuppressWarnings("deprecation")

private void scheduleWork(String assetPath,String saveLocation,String cronExpression,String jobName) {

        try {

            logger.info("In ReRegister" + jobName + " " + assetPath + " " + cronExpression);

            Map<String, Serializable> serviceProps = new HashMap<String, Serializable>();

            serviceProps.put("assetPath", assetPath);

            serviceProps.put("jobName", jobName);

            serviceProps.put("saveLocation", saveLocation);

            Runnable job = new DeployAssetsScheduler(serviceProps);

            scheduler.addJob(jobName, job, serviceProps, cronExpression, false);

            logger.info("#### Successfully re registered ####" + jobName);

        } catch (Exception e) {

            logger.error("Could not schedule work.", e);

        }

    }

public class DeployAssetsScheduler implements Runnable {

    private Map<String, Serializable> jobProperties;

public DeployAssetsScheduler(Map<String, Serializable> jobProperties) {

        logger.info("#####In my DeployAssetsScheduler constructor with property " + jobProperties.get("jobName"));

        this.jobProperties = jobProperties;

    }

    @Override

    public void run() {

        // TODO Auto-generated method stub

        logger.debug("In Job Run Method");

        String assetPath = (String) this.jobProperties.get("assetPath");

        String saveLocation = (String) this.jobProperties.get("saveLocation");

        deployAsset(assetPath, saveLocation);

    }

@SuppressWarnings("deprecation")

private void deployAsset(String assetPath,

String saveLocation) {

ResourceResolver resourceResolver = null;

try {

logger.info("entered deployAsset {}",resolverFactory);

resourceResolver = resolverFactory

.getAdministrativeResourceResolver(null);

Resource r = resourceResolver.getResource(assetPath);

Asset asset = r.adaptTo(Asset.class);

Rendition original = asset.getOriginal();

if (original != null) {

String name = asset.getName();

String newFile = saveLocation +"/"+ name;

logger.info("Asset path {}",newFile);

// Use AssetManager to place the file into the AEM DAM

com.day.cq.dam.api.AssetManager assetMgr = resourceResolver

.adaptTo(com.day.cq.dam.api.AssetManager.class);

Asset deployedAsset = assetMgr.createAsset(newFile, original.getStream(),

asset.getMimeType(), true);

logger.info("End of Deploy Asset {}",deployedAsset.getPath());

}

} catch (Exception e) {

logger.error("Exception {}", e);

} finally {

resourceResolver.close();

}

}

}

}

Can we use this Code

Replies

Highlighted

Avatar

Avatar

Veena_Vikram

MVP

Avatar

Veena_Vikram

MVP

Veena_Vikram
MVP

15-12-2018

Santhosh,

  I couldn't test the entire code yet, I will try to test it if I get some time. But a quick observation, Please don't use repository.loginAdministrative(null);

Thanks

Veena