
com.adobe.aem.formsndocuments.util.FMUtils Maven / Gradle / Ivy
/*************************************************************************
*
* ADOBE CONFIDENTIAL
* __________________
*
* Copyright 2014 Adobe Systems Incorporated
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Adobe Systems Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Adobe Systems Incorporated and its
* suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Adobe Systems Incorporated.
**************************************************************************/
package com.adobe.aem.formsndocuments.util;
import com.adobe.aem.formsndocuments.transferobjects.AssetInfo;
import com.adobe.aem.formsndocuments.util.FMConstants.CoreAssetType;
import com.adobe.aemforms.fm.exception.FormsMgrException;
import com.adobe.forms.foundation.service.FormsAssetType;
import com.adobe.granite.asset.api.Asset;
import com.adobe.granite.asset.api.AssetManager;
import com.adobe.granite.asset.api.Rendition;
import com.adobe.granite.ui.clientlibs.ClientLibrary;
import com.adobe.granite.ui.clientlibs.HtmlLibraryManager;
import com.day.cq.commons.jcr.JcrConstants;
import com.day.cq.commons.jcr.JcrUtil;
import com.day.cq.replication.ReplicationStatus;
import com.day.cq.replication.Replicator;
import com.day.cq.wcm.api.Template;
import com.day.cq.wcm.api.policies.ContentPolicy;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.User;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.request.RequestParameterMap;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.ModifiableValueMap;
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.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.event.jobs.JobManager;
import org.apache.sling.event.jobs.ScheduledJobInfo;
import org.apache.sling.jcr.api.SlingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ValueFormatException;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.security.AccessControlManager;
import javax.jcr.security.Privilege;
import javax.jcr.version.VersionException;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
public class FMUtils {
/** Default log. */
private static final Logger log = LoggerFactory.getLogger(FMUtils.class);
public static Node getMetadataNode(Node formNode, boolean create) throws FormsMgrException {
try {
Node metadataNode = null;
Node contentNode = getContentNode(formNode, create);
if (contentNode != null) {
if (!contentNode.hasNode(FMConstants.METADATA_NODE_NAME)) {
if (create) {
metadataNode = contentNode.addNode(FMConstants.METADATA_NODE_NAME, NodeType.NT_UNSTRUCTURED);
}
} else {
metadataNode = contentNode.getNode(FMConstants.METADATA_NODE_NAME);
}
}
return metadataNode;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static Node getMetadataNode(Session session, String formPath, boolean create) throws FormsMgrException {
try {
Node metadataNode = null;
if(session != null) {
Node formNode = session.getNode(FMUtils.getAssetPathFromPage(formPath));
metadataNode = getMetadataNode(formNode, create);
}
return metadataNode;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static Node getAnalyticsDataNode(Node formNode, boolean create) throws FormsMgrException {
try {
Node analyticsDataNode = null;
Node contentNode = getContentNode(formNode, create);
if (contentNode != null) {
if (!contentNode.hasNode(FMConstants.ANALYTICS_DATA_NODE_NAME)) {
if (create) {
analyticsDataNode = contentNode.addNode(FMConstants.ANALYTICS_DATA_NODE_NAME, NodeType.NT_UNSTRUCTURED);
}
} else {
analyticsDataNode = contentNode.getNode(FMConstants.ANALYTICS_DATA_NODE_NAME);
}
}
return analyticsDataNode;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static Node getContentNode(Node formNode, boolean create) throws FormsMgrException {
try {
Node contentNode = null;
if (!formNode.hasNode(FMConstants.JCR_CONTENT_NODE_NAME)) {
if (create) {
contentNode = formNode.addNode(FMConstants.JCR_CONTENT_NODE_NAME, FMConstants.DAM_ASSET_CONTENT_NODETYPE);
}
} else {
contentNode = formNode.getNode(FMConstants.JCR_CONTENT_NODE_NAME);
}
return contentNode;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static boolean isFolder(Session session, String path) throws FormsMgrException {
boolean isFolderNode = false;
if (session != null) {
try {
Node folderNode = null;
folderNode = session.getNode(path);
if(folderNode.isNodeType(FMConstants.SLING_FOLDER_NODETYPE)){
if (folderNode.hasProperty(FMConstants.LC_FOLDER)) {
Property prop = folderNode
.getProperty(FMConstants.LC_FOLDER);
if (prop.getLong() == FMConstants.FOLDER_STATE.VALID
.ordinal()) {
isFolderNode = true;
}
}
}
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
return isFolderNode;
}
public static boolean isApplication(Session session, String path) throws FormsMgrException {
boolean isApplicationNode = false;
if (session != null) {
try {
Node applicationNode = null;
applicationNode = session.getNode(path);
if (applicationNode.hasProperty(FMConstants.LC_APPLICATION)) {
Property prop = applicationNode
.getProperty(FMConstants.LC_APPLICATION);
if (prop.getLong() == FMConstants.APPLICATION_STATE.VALID
.ordinal()) {
isApplicationNode = true;
}
}
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
return isApplicationNode;
}
public static boolean isXDPForm(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, Collections.singletonList(FMConstants.LC_XDP_FORM), FMConstants.FORM_STATE.VALID.ordinal());
}
public static boolean isResource(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, Collections.singletonList(FMConstants.LC_RESOURCE), FMConstants.FORM_STATE.VALID.ordinal());
}
public static boolean isGuide(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, Collections.singletonList(FMConstants.GUIDE), FMConstants.FORM_STATE.VALID.ordinal());
}
public static boolean isPDFForm(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, Collections.singletonList(FMConstants.LC_PDF_FORM), FMConstants.FORM_STATE.VALID.ordinal());
}
public static boolean isPrintForm(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, Collections.singletonList(FMConstants.LC_PRINT_FORM), FMConstants.FORM_STATE.VALID.ordinal());
}
public static boolean isFormset(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, Collections.singletonList(FMConstants.FORMSET), FMConstants.FORM_STATE.VALID.ordinal());
}
public static boolean isAFFragment(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, Collections.singletonList(FMConstants.AFFRAGMENT), FMConstants.FORM_STATE.VALID.ordinal());
}
public static boolean isAdaptiveDocument(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, Collections.singletonList(FMConstants.ADAPTIVE_DOCUMENT), FMConstants.FORM_STATE.VALID.ordinal());
}
public static boolean isTheme(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, Collections.singletonList(FMConstants.THEME), FMConstants.FORM_STATE.VALID.ordinal());
}
/**
* @param assetNode a non null node
* @return true if the given node is of type FMConstants.CQ_CLIENTLIBRARY_FOLDER
* and FMConstants.GUIDE_COMPONENT_TYPE property's value is
* FMConstants.THEME_GUIDE_COMPONENT_TYPE_VALUE. false otherwise
* @throws FormsMgrException
*/
public static boolean isThemeClientLib(Node assetNode) throws FormsMgrException {
try {
return assetNode.isNodeType(FMConstants.CQ_CLIENTLIBRARY_FOLDER)
&& assetNode.hasProperty(FMConstants.GUIDE_COMPONENT_TYPE) && FMConstants.THEME_GUIDE_COMPONENT_TYPE_VALUE
.equals(assetNode.getProperty(FMConstants.GUIDE_COMPONENT_TYPE).getString());
} catch (Exception e) {
throw FMUtils.getFormsMgrException(e);
}
}
public static boolean isFDM(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, FMConstants.TYPE_PROPERTY, FMConstants.FORM_DATA_MODEL);
}
public static boolean isMultichannelDocument(Session session, String path) throws FormsMgrException {
return isValidAssetType(session, path, FMConstants.TYPE_PROPERTY, FMConstants.MULTICHANNEL_DOCUMENT);
}
/**
* Returns whether a cq:Page is a Document channel or not
* @param resourceResolver
* @param path Path to the Channel cq:Page
* @return
*/
public static boolean isDocumentChannel(@Nonnull ResourceResolver resourceResolver, String path) {
Resource channelResource = resourceResolver.getResource(path);
if (channelResource != null) {
Resource contentResource = channelResource.getChild(FMConstants.JCR_CONTENT_NODE_NAME);
if (contentResource != null && contentResource.getValueMap().containsKey(FMConstants.DOCUMENT_CHANNEL_TYPE)) {
return true;
}
}
return false;
}
/**
* Returns the Document page path
* @param channelPath Path to the Channel cq:Page
* @return
*/
public static String getDocumentPagePath (String channelPath) {
String documentPath = "";
if (StringUtils.isNotEmpty(channelPath)) {
documentPath = Text.getRelativeParent(channelPath, 2);
}
return documentPath;
}
/*
* Checks whether the asset is of a given type.
*/
private static boolean isValidAssetType(Session session, String path, String propertyName, String value) throws FormsMgrException {
boolean isValid = false;
if (session != null) {
try {
Node assetNode = null;
assetNode = session.getNode(path);
if (assetNode != null) {
String primaryType = assetNode.getPrimaryNodeType().getName();
if (primaryType.equals(FMConstants.DAM_ASSET_NODETYPE)) {
Node contentNode = getContentNode(assetNode, false);
if (contentNode != null) {
if (contentNode.hasProperty(propertyName)) {
Property prop = contentNode.getProperty(propertyName);
if (prop.getString().equals(value)) {
isValid = true;
}
}
}
}
}
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
return isValid;
}
/*
* Checks whether the asset is of a given type (XDPForm, Resource etc.).
*/
private static boolean isValidAssetType(Session session, String path, List assetTypes, long validValue) throws FormsMgrException {
if (session != null) {
try {
Node assetNode = null;
assetNode = session.getNode(path);
if (assetNode == null) {
return false;
}
String primaryType = assetNode.getPrimaryNodeType().getName();
if (primaryType.equals(FMConstants.DAM_ASSET_NODETYPE)) {
Node contentNode = getContentNode(assetNode, false);
if (contentNode == null) {
return false;
}
for (String assetType : assetTypes) {
if (contentNode.hasProperty(assetType)) {
Property prop = contentNode.getProperty(assetType);
if (prop.getLong() == validValue) {
return true;
}
}
}
}
} catch (Exception e) {
throw FMUtils.getFormsMgrException(e);
}
}
return false;
}
public static boolean isXFABasedForm(Session session, String path) throws FormsMgrException {
try {
if (session.nodeExists(path) && (isGuide(session, path) || isAFFragment(session, path))){
Node formNode = session.getNode(path);
Node metadataNode = getMetadataNode(formNode, false);
if (metadataNode != null)
return (metadataNode.hasProperty(FMConstants.PROPERTYNAME_FORMMODEL) && metadataNode.getProperty(FMConstants.PROPERTYNAME_FORMMODEL)
.getString().equals(FMConstants.PROPERTYVAL_FORMMODEL_XFA));
}
return false;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static boolean hasDORTemplate(Session session, String path) throws FormsMgrException {
try {
if (session.nodeExists(path) && (isGuide(session, path) || isAFFragment(session, path))){
Node formNode = session.getNode(path);
Node metadataNode = getMetadataNode(formNode, false);
if (metadataNode != null)
if(metadataNode.hasProperty(FMConstants.PROPERTYNAME_DOR_TYPE)) {
return (FMConstants.PROPERTYVAL_DORTYPE_SELECT.equals(metadataNode.getProperty(FMConstants.PROPERTYNAME_DOR_TYPE).getString())
&& metadataNode.hasProperty(FMConstants.PROPERTYNAME_DOR_REFERENCE));
}
}
return false;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static boolean hasMetaTemplate(Session session, String path) throws FormsMgrException{
try {
if(session.nodeExists(path) && isGuide(session, path)){
Node formNode = session.getNode(path);
Node metadataNode = getMetadataNode(formNode, false);
if(metadataNode != null)
return (metadataNode.hasProperty(FMConstants.PROPERTYNAME_METATEMPLATE_REFERENCE));
}
return false;
} catch (Exception e){
throw new FormsMgrException(e);
}
}
public static boolean hasXSDRef(Session session, String path) throws FormsMgrException {
try {
if (session.nodeExists(path) && (isGuide(session, path) || isAFFragment(session, path))){
Node formNode = session.getNode(path);
Node metadataNode = getMetadataNode(formNode, false);
if (metadataNode != null)
return (metadataNode.hasProperty(FMConstants.PROPERTYNAME_XSD_REFERENCE));
}
return false;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static boolean hasSchemaRef(Session session, String path) throws FormsMgrException {
try {
if (session.nodeExists(path) && (isGuide(session, path) || isAFFragment(session, path))){
Node formNode = session.getNode(path);
Node metadataNode = getMetadataNode(formNode, false);
if (metadataNode != null) {
return (metadataNode.hasProperty(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE));
}
}
return false;
} catch (Exception e) {
throw getFormsMgrException(e);
}
}
public static boolean hasProperty(Session session, String path, String propertyName) throws FormsMgrException {
try {
//doing away with rigorous asset type checks to avoid similar work for different types
if (session.nodeExists(path)){
Node node = session.getNode(path);
return node != null && (node.hasProperty(propertyName));
}
return false;
} catch (Exception e) {
throw getFormsMgrException(e);
}
}
public static Property getNodeProperty(String propertyName, Node node) throws FormsMgrException {
try {
if (node.hasProperty(propertyName)) {
Property property = node.getProperty(propertyName);
if (property != null) {
return property;
}
}
return null;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static String getXDPRefPath(Session session, String guidePath) throws FormsMgrException {
try {
String guideContainerNodePath = guidePath + "/"+ FMConstants.GUIDE_CONTAINER_PATH;
if (!session.itemExists(guideContainerNodePath)) // This should never happen
throw new FormsMgrException(ExceptionCodes.XFA_GUIDE_NO_CONTAINER, new String[] {guidePath});
Node guideContainerNode = session.getNode(guideContainerNodePath);
if (guideContainerNode.hasProperty(FMConstants.PROPERTYNAME_XDP_REFERENCE)) {
return guideContainerNode.getProperty(FMConstants.PROPERTYNAME_XDP_REFERENCE).getString();
}
else {
throw new FormsMgrException(ExceptionCodes.XFA_GUIDE_NO_XDPREF, new String[] {guidePath});
}
} catch (FormsMgrException e) {
throw e;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static String getDORRefPath(Session session, String guidePath) throws FormsMgrException {
try {
String guideContainerNodePath = guidePath + "/"+ FMConstants.GUIDE_CONTAINER_PATH;
if (!session.itemExists(guideContainerNodePath)) // This should never happen
throw new FormsMgrException(ExceptionCodes.XFA_GUIDE_NO_CONTAINER, new String[] {guidePath});
Node guideContainerNode = session.getNode(guideContainerNodePath);
if (guideContainerNode.hasProperty(FMConstants.PROPERTYNAME_DOR_REFERENCE)) {
return guideContainerNode.getProperty(FMConstants.PROPERTYNAME_DOR_REFERENCE).getString();
}
else {
throw new FormsMgrException(ExceptionCodes.XFA_GUIDE_NO_XDPREF, new String[] {guidePath});
}
} catch (FormsMgrException e) {
throw e;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static String getMetaTemplateRefPath(Session session, String guidePath) throws FormsMgrException {
try {
String guideContainerNodePath = guidePath + "/"+ FMConstants.GUIDE_CONTAINER_PATH;
if (!session.nodeExists(guideContainerNodePath))
throw new FormsMgrException(ExceptionCodes.XFA_GUIDE_NO_CONTAINER, new String[] {guidePath});
Node guideContainerNode = session.getNode(guideContainerNodePath);
if (guideContainerNode.hasProperty(FMConstants.PROPERTYNAME_METATEMPLATE_REFERENCE)) {
return guideContainerNode.getProperty(FMConstants.PROPERTYNAME_METATEMPLATE_REFERENCE).getString();
}
else {
throw new FormsMgrException(ExceptionCodes.XFA_GUIDE_NO_XDPREF, new String[] {guidePath});
}
} catch (FormsMgrException e) {
throw e;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static String getXSDRefPath(Session session, String guidePath) throws FormsMgrException {
try {
String guideContainerNodePath = guidePath + "/"+ FMConstants.GUIDE_CONTAINER_PATH;
if (!session.itemExists(guideContainerNodePath)) // This should never happen
throw new FormsMgrException(ExceptionCodes.XFA_GUIDE_NO_CONTAINER, new String[] {guidePath});
Node guideContainerNode = session.getNode(guideContainerNodePath);
if (guideContainerNode.hasProperty(FMConstants.PROPERTYNAME_XSD_REFERENCE)) {
return guideContainerNode.getProperty(FMConstants.PROPERTYNAME_XSD_REFERENCE).getString();
}
else {
throw new FormsMgrException(ExceptionCodes.XFA_GUIDE_NO_XDPREF, new String[] {guidePath});
}
} catch (FormsMgrException e) {
throw e;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static String getSchemaRefPath(Session session, String guidePath) throws FormsMgrException {
try {
String guideContainerNodePath = guidePath + "/"+ FMConstants.GUIDE_CONTAINER_PATH;
if (!session.itemExists(guideContainerNodePath)) // This should never happen
throw new FormsMgrException(ExceptionCodes.SCHEMA_GUIDE_NO_CONTAINER, new String[] {guidePath});
Node guideContainerNode = session.getNode(guideContainerNodePath);
if (guideContainerNode.hasProperty(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE)) {
return guideContainerNode.getProperty(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE).getString();
}
else {
throw new FormsMgrException(ExceptionCodes.SCHEMA_GUIDE_NO_SCHEMAREF, new String[] {guidePath});
}
} catch (Exception e) {
throw getFormsMgrException(e);
}
}
public static Map createGuideRenderURL(Node guideNode, String sampleDataId,Session session)
throws FormsMgrException {
try {
Map renderUrlMap = new HashMap();
String cqPagePath = FMUtils.getPagePathFromAsset(guideNode.getPath());
if (!session.nodeExists(cqPagePath)) {
throw new FormsMgrException("CQ Page corresponding to Guide Node does not exists");
}
renderUrlMap.put("formUrl",cqPagePath + ".html");
String completeDataUrl = createDataUrl(sampleDataId,session);
renderUrlMap.put("dataRef",completeDataUrl);
return renderUrlMap;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static Map createMulichannelDocumentRenderURL(Node assetNode, String sampleDataId,Session session, String channelType)
throws FormsMgrException {
try {
Map renderUrlMap = new HashMap();
String cqPagePath = FMUtils.getPagePathFromAsset(assetNode.getPath());
if (!session.nodeExists(cqPagePath)) {
throw new FormsMgrException("CQ Page corresponding to Guide Node does not exists");
}
StringBuilder formUrl = new StringBuilder(cqPagePath);
formUrl.append(FMConstants.DELIMITER_SLASH).append(FMConstants.DOCUMENT_CHANNELS_NODENAME).append(FMConstants.DELIMITER_SLASH).append(channelType);
if (FMConstants.CHANNEL_TYPE_PRINT.equals(channelType)){
formUrl.append(".pdf");
} else if (FMConstants.CHANNEL_TYPE_WEB.equals(channelType)){
formUrl.append(".html");
} else {
throw new FormsMgrException(new IllegalArgumentException("Unsupported channel type=" + channelType));
}
renderUrlMap.put("formUrl", formUrl.toString());
String completeDataUrl = createDataUrl(sampleDataId,session);
renderUrlMap.put("dataRef",completeDataUrl);
return renderUrlMap;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
/*
* Prepare URL to generate formset rendition.
*/
public static Map createFormsetRenderURLParams(Node formNode, String type, String submitUrl, String profile, String sampleDataId,Session session)
throws FormsMgrException {
try {
String formUrl;
Map renderUrlMap = new HashMap();
//try to get profile and submitUrl from metadata node
Node metadataNode = getMetadataNode(formNode, false);
if(profile == null || profile.trim().equals("")){
if(metadataNode != null && metadataNode.hasProperty(FMConstants.PROFILE_PROPERTY)){
profile = metadataNode.getProperty(FMConstants.PROFILE_PROPERTY).getString();
} else {
profile = FMConstants.DEFAULT_FORMSET_RENDER_PROFILE;
}
}
if (submitUrl == null) {
submitUrl= (metadataNode != null && metadataNode.hasProperty(FMConstants.SUBMIT_URL_PROPERTY)) ? metadataNode.getProperty(FMConstants.SUBMIT_URL_PROPERTY).getString() : null;
}
String templateName = null;
String contentRoot = null;
String formsetPath = null;
String contentUri = formNode.getPath();
if(contentUri != null) {
int index = contentUri.lastIndexOf("/");
templateName = contentUri.substring(index + 1);
contentRoot = contentUri.substring(0, index);
formsetPath = contentRoot + "/" + templateName;
}
else {
throw new FormsMgrException("Failed to render form. Null ContentRootURI.");
}
String completeDataUrl = createDataUrl(sampleDataId,session);
formUrl = profile + "."+type;
renderUrlMap.put(FMConstants.FORM_URL_PROPERTY,formUrl);
renderUrlMap.put(FMConstants.FORM_SET_PATH_PROPERTY, formsetPath);
renderUrlMap.put(FMConstants.DATA_REF_PROPERTY, completeDataUrl);
renderUrlMap.put(FMConstants.SUBMIT_URL_PROPERTY, submitUrl);
return renderUrlMap;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
private static String createDataUrl(String dataId,Session session)
throws FormsMgrException {
String dataUrl = null, urlPrefix = FMConstants.CRX_REPOSITORY_ACCESS_PREFIX;
if(dataId != null && dataId.trim().length() > 0) {
if(!dataId.contains("://") && !dataId.trim().equals("None")) {
dataUrl = getSampleDataPath(dataId,session);
}
}
String completeDataUrl = null;
if(dataUrl != null && !dataUrl.trim().equals("")) {
completeDataUrl = urlPrefix + dataUrl;
}else if(dataId != null && !dataId.trim().equals("") && dataId.contains("://")){
completeDataUrl = dataId;
}else {
completeDataUrl = "";
}
return completeDataUrl;
}
private static String getSampleDataPath(String fileId,Session session) throws FormsMgrException {
try {
String fileName = FMConstants.TEMP_ARCHIVE + "_" + fileId;
String tempArchiveLocation = FMConstants.TEMP_ARCHIVE_STORAGE_PATH + "/" + fileName;
Node tempNode = null;
if (!session.nodeExists(tempArchiveLocation)) {
log.error("temp node doesn't exist " + tempArchiveLocation);
return null;
} else {
tempNode = session.getNode(tempArchiveLocation);
}
return tempNode.getPath();
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static boolean isForm(CoreAssetType assetType) {
return (assetType == CoreAssetType.FORM || assetType == CoreAssetType.PDFFORM || assetType == CoreAssetType.PRINTFORM);
}
public static String getFormType(CoreAssetType assetType) {
if (CoreAssetType.FORM == assetType)
return FMConstants.LC_XDP_FORM;
else if (CoreAssetType.PDFFORM == assetType)
return FMConstants.LC_PDF_FORM;
else if (CoreAssetType.PRINTFORM == assetType)
return FMConstants.LC_PRINT_FORM;
else
throw new RuntimeException("Invalid form type");
}
/**
* Deletes temp archives created in CRX during uploadForm. If a temp archive remains in the repository
* for more than a certain duration, the DeleteTempArchiveScheduler will call this function and delete it.
* @param session - Session session
* @throws FormsMgrException
*/
public static void deleteTempArchives(Session session) throws FormsMgrException{
/*
* Location where temp archives are stored in the repository.
*/
String tempStoragePath = FMConstants.TEMP_STORAGE_ROOT_PATH;
try {
if(session.nodeExists(tempStoragePath)){
Node tempStorageNode = session.getNode(tempStoragePath);
List folderList= new ArrayList();
NodeIterator iterator = tempStorageNode.getNodes();
while(iterator.hasNext()){
Node node = iterator.nextNode();
if(node.isNodeType(FMConstants.SLING_FOLDER_NODETYPE)) {
folderList.add(node);
} else {
log.info("Temp file found at unexpected location: "+node.getPath()+". This file will not be cleaned as it is not present in a folder.");
}
}
for(Node tempStorageFolder : folderList){
NodeIterator iter = tempStorageFolder.getNodes();
if (iter != null) {
for (int i = 0; i < iter.getSize(); i++) {
Node node = iter.nextNode();
/*
* If the node has jcr:created.
*/
if(node.hasProperty("jcr:created")){
Calendar cal = Calendar.getInstance();
long currentTime = cal.getTime().getTime();
long creationTime = node.getProperty("jcr:created").getDate().getTime().getTime();
/*
* If the temp archive was created more than 30 minutes ago, it is not useful anymore.
* We are going to delete it using the Delete Temp Archive Scheduler.
*/
if((currentTime - creationTime) > (FMConstants.TEMP_ARCHIVE_EXPIRE_TIME_MINUTES*60*1000)){
log.info("Deleting temp archive : "+node.getPath());
//log.info("Current time : "+currentTime+" , creation time : "+creationTime);
node.remove();
session.save();
}
}
/*
* Else the node's name string has the system.nanotime when it was created.
*/
else{
long currentTime = System.nanoTime();
String name = node.getName();
if(name.startsWith(FMConstants.TEMP_ARCHIVE + "_")){
String creationTimeString = name.substring(FMConstants.TEMP_ARCHIVE.length()+1);
try{
Long creationTime = Long.parseLong(creationTimeString);
//log.info(" For without mixin - Current time : "+currentTime+" , creation time : "+creationTime);
/*
* If the temp archive was created more than 30 minutes ago, it is not useful anymore.
* We are going to delete it using the Delete Temp Archive Scheduler.
*/
if((currentTime - creationTime) > (FMConstants.TEMP_ARCHIVE_EXPIRE_TIME_MINUTES*60*1000000000)){
log.info("Deleting temp archive without mixin : "+node.getPath());
node.remove();
session.save();
}
}
catch(NumberFormatException e){
log.warn(node.getName() + " does not have a valid system time name. Failed to delete" , e);
}
}
}
}
} else {
log.info("No Temp Archive files.");
}
}
}
}
catch(Exception e){
throw new FormsMgrException(e);
}
}
public static ResourceResolver getResourceResolver(ResourceResolverFactory resourceResolverFactory, Session session) throws FormsMgrException {
try {
Map authInfo = new HashMap();
authInfo.put(FMConstants.AUTHENTICATION_INFO_SESSION, session);
return resourceResolverFactory.getResourceResolver(authInfo);
} catch (LoginException e) {
throw new FormsMgrException(e);
}
}
public static void writeRequestStatusSuccess(SlingHttpServletResponse resp, boolean isIE) throws IOException, JSONException {
PrintWriter writer = null;
try {
writer = resp.getWriter();
JSONObject successJson = new JSONObject();
successJson.put("requestStatus", "success");
/* The following check is to handle the case when servlet URL is passed as a form action on client-side and is hit on form submission.
In that case an html tag needs to be added in the response when working on IE because the Accept type in req is text/html
and so returning a json object downloads a file with name baseManage.json/manage.json */
if (isIE) {
resp.setContentType("text/html;charset=utf-8");
writer.write("");
}
}
finally {
if (writer != null)
writer.close();
}
}
public static Node getFolderNode(Session session, String rootNodePath, boolean create, String folderType) throws FormsMgrException {
try {
Node workingNode = null;
if (session.nodeExists(rootNodePath)) {
return session.getNode(rootNodePath);
}
else if (!create) {
throw new FormsMgrException("Node "+rootNodePath+" does not exist. Please check logs for more detail.");
}
String[] pathElems = rootNodePath.split("/");
Node workspaceRootNode = session.getRootNode();
Node parentNode = workspaceRootNode;
String rootPath = rootNodePath;
if (rootPath.endsWith("/")) {
rootPath = rootPath.substring(0, rootPath.length() - 1);
}
for (String path : pathElems) {
if (!path.equals("")) {
if (!parentNode.hasNode(path)) {
workingNode = parentNode.addNode(path, folderType);
} else {
workingNode = parentNode.getNode(path);
}
parentNode = workingNode;
}
}
return workingNode;
} catch (FormsMgrException e) {
throw e;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
/**
* This function returns Page path from Asset path for Adaptive Assets
* ie : Guide, AF Fragment, Adaptive Document, Multichannel Document
* @param assetPath path of the asset
*/
public static String getPagePathFromAsset(String assetPath) {
return assetPath.replace(FMConstants.SHADOW_NODES_ROOT, FMConstants.AF_ROOT);
}
/**
* This function returns Asset path from Page path for Adaptive Pages
* ie : Guide, AF Fragment, Adaptive Document
* @param pagePath path of the asset
*/
public static String getAssetPathFromPage(String pagePath) {
return pagePath.replace(FMConstants.AF_ROOT, FMConstants.SHADOW_NODES_ROOT);
}
/**
* This function returns first node resource encountered up in the hierarchy that has given property value of the given property name.
* @param resolver
* @param path
* @param inputPropertyName
* @param inputPropertyValue
* @param includeCurrentNode
*/
public static Resource getClosestNodeUpInHierarchy(ResourceResolver resolver, String path, String inputPropertyName, String inputPropertyValue, boolean includeCurrentNode) throws FormsMgrException {
try {
if(resolver == null || path == null || path.isEmpty() ||
inputPropertyName == null || inputPropertyName.isEmpty() ||
inputPropertyValue == null || inputPropertyValue.isEmpty() ) {
throw new FormsMgrException(ExceptionCodes.INVALID_PARAMETER);
}
Resource res = resolver.getResource(path);
String propeVal = null;
ValueMap map = null;
if(res != null && !includeCurrentNode) {
res = res.getParent();
}
while(res != null) {
map = res.getValueMap();
propeVal = (String) map.get(inputPropertyName);
if(inputPropertyValue.equals(propeVal)) {
break;
}
res = res.getParent();
}
return res;
} catch (FormsMgrException e) {
log.error("exception while finding node in getClosestNodeUpInHierarchy() : " + e);
throw e;
} catch (Exception e) {
log.error("exception while finding node in getClosestNodeUpInHierarchy() : " + e);
throw new FormsMgrException(e);
}
}
/**
*
* @param session
* @param assetPath
* @return lastmodified time or created time or -1 if cant read property, but node exists
* @throws FormsMgrException if cant get node
*/
public static long getLastModifiedOrCreated(Session session, String assetPath) throws FormsMgrException {
try {
String originalPath = assetPath;
if(originalPath.startsWith(FMConstants.AF_ROOT)) {
assetPath = FMUtils.getAssetPathFromPage(originalPath);// we read LMT for AF_ROOT paths from SHADOW_NODES_ROOT path
if (!session.nodeExists(assetPath)){
assetPath = originalPath;
log.debug(assetPath + "does not exist");
}
}
Property lastUpdateProperty = null;
Node assetNode = session.getNode(assetPath);
Node contentNode = FMUtils.getContentNode(assetNode, false);
if (assetNode.isNodeType(FMConstants.CQ_TEMPLATE_NODETYPE)) {
// return -1 in case of AF templates since its LMT does not update on changing it.. To be fixed in CQ-76288
return -1L;
} else if (assetNode.isNodeType(FMConstants.CQ_CLIENTLIBRARY_FOLDER)) {
// return -1 in case of theme clientlib since it does not have lastModified property.
return -1L;
} else if (assetNode.hasProperty(FMConstants.SLING_RES_TYPE) &&
FMConstants.CONTENT_POLICY_RESOURCE_TYPE.equals(assetNode.getProperty(FMConstants.SLING_RES_TYPE).getString())) {
// return -1 in case of content policies since they do not have lastModified property.
return -1L;
} else if (contentNode != null && contentNode.hasProperty(JcrConstants.JCR_LASTMODIFIED)) {
lastUpdateProperty = contentNode.getProperty(JcrConstants.JCR_LASTMODIFIED);
} else if (contentNode != null && contentNode.hasProperty(JcrConstants.JCR_CREATED)) {
lastUpdateProperty = contentNode.getProperty(JcrConstants.JCR_CREATED);
} else if(assetNode.hasProperty(JcrConstants.JCR_LASTMODIFIED)){
lastUpdateProperty = assetNode.getProperty(JcrConstants.JCR_LASTMODIFIED);
}
if (lastUpdateProperty == null) {
return -1L;
} else {
return lastUpdateProperty.getDate().getTimeInMillis();
}
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
public static String getNameFromPath(String path)
throws FormsMgrException {
String name = null;
int nameStartIndex = path.lastIndexOf("/");
if (nameStartIndex >= 0 && nameStartIndex < path.length() - 1) {
name = path.substring(nameStartIndex + 1);
} else {
throw new FormsMgrException(
"Invalid asset path: "+path);
}
return name;
}
/*
* This method returns null if nodePath does not correspond to to a FM Asset.
*/
public static CoreAssetType getAssetType(Session session, String nodePath) throws FormsMgrException {
if (session != null) {
try {
if (!session.nodeExists(nodePath)) {
Object[] args = {nodePath};
throw new FormsMgrException(ExceptionCodes.NODE_DOES_NOT_EXIST, args);
}
if (isXDPForm(session, nodePath)) {
return CoreAssetType.FORM;
} else if (isPDFForm(session, nodePath)) {
return CoreAssetType.PDFFORM;
} else if (isPrintForm(session, nodePath)) {
return CoreAssetType.PRINTFORM;
} else if(isFolder(session, nodePath) || isApplication(session, nodePath)) {
return CoreAssetType.FOLDER;
} else if (isResource(session, nodePath)) {
return CoreAssetType.RESOURCE;
} else if (isGuide(session, nodePath)) {
return CoreAssetType.GUIDE;
} else if (isFormset(session, nodePath)) {
return CoreAssetType.FORMSET;
} else if (isAFFragment(session, nodePath)) {
return CoreAssetType.AFFRAGMENT;
} else if (isAdaptiveDocument(session, nodePath)) {
return CoreAssetType.ADAPTIVEDOCUMENT;
} else if (isTheme(session, nodePath)) {
return CoreAssetType.THEME;
} else if (isFDM(session, nodePath)) {
return CoreAssetType.FORMDATAMODEL;
} else if (isMultichannelDocument(session, nodePath)) {
return CoreAssetType.DOCUMENT_TEMPLATE;
} else {
return CoreAssetType.NONFMASSET;
}
} catch (Exception e) {
throw new FormsMgrException(e);
}
} else {
log.error("Unable to get a JCR session");
throw new FormsMgrException("Invalid session object.");
}
}
public static FormsMgrException getFormsMgrException(Exception e)
{
if (e instanceof FormsMgrException) {
return (FormsMgrException) e;
}
return new FormsMgrException(e);
}
public static void unscheduleJob(JobManager jobManager, String formPath, String replicationAtribute) {
/*TODO Replace with an API that would allow searching among scheduled jobs.
Logged https://issues.apache.org/jira/browse/SLING-3701 for the same.
*/
Collection scheduledJobs = jobManager.getScheduledJobs();
for (ScheduledJobInfo eachJob : scheduledJobs) {
Map eachJobProps = eachJob.getJobProperties();
if (eachJob.getJobTopic().equals(FMConstants.REPLICATION_EVENT_TOPIC) &&
eachJobProps.get(FMConstants.PROPERTY_REPLICATION_FORM_PATH).equals(formPath) &&
eachJobProps.get(FMConstants.PROPERTY_REPLICATION_ATTRIBUTE).equals(replicationAtribute)) {
eachJob.unschedule();
break;
}
}
}
/** This method is used to deduce the type of the root level folder in which the asset with the specified asset path lies.
* It will return 'lcApplication' if asset lies inside an LC Application, 'lcFolder' if inside a general folder,
* its asset type if the asset lies in the shadow root node
* and null if the asset does not exist or if the path is of the shadow root node itself.
* @param session CRX session to be used
* @param assetPath Path of the asset for which to deduce which type of root folder it belongs to.
* @throws javax.jcr.RepositoryException
*/
public static String getRootLevelAssetType(Session session, String assetPath) throws RepositoryException {
if (assetPath != null && assetPath.startsWith(FMConstants.SHADOW_NODES_ROOT)) {
int endIndex = assetPath.indexOf("/", FMConstants.SHADOW_NODES_ROOT.length() + 1);
if (endIndex > 0) {
assetPath = assetPath.substring(0, endIndex);
}
if (session.nodeExists(assetPath)) {
Node rootFolderNode = session.getNode(assetPath);
if (rootFolderNode.hasProperty(FMConstants.LC_APPLICATION))
return FMConstants.LC_APPLICATION;
else if (rootFolderNode.hasProperty(FMConstants.LC_FOLDER))
return FMConstants.LC_FOLDER;
else if (rootFolderNode.hasProperty(FMConstants.LC_XDP_FORM))
return FMConstants.LC_XDP_FORM;
else if (rootFolderNode.hasProperty(FMConstants.LC_PDF_FORM))
return FMConstants.LC_PDF_FORM;
else if (rootFolderNode.hasProperty(FMConstants.LC_PRINT_FORM))
return FMConstants.LC_PRINT_FORM;
else if (rootFolderNode.hasProperty(FMConstants.LC_RESOURCE))
return FMConstants.LC_RESOURCE;
}
}
return null;
}
public static byte[] getBytesFromInputStream (InputStream oInpStream) throws IOException
{
byte[] result = new byte[0];
if (oInpStream == null)
return result;
BufferedInputStream oStream = new BufferedInputStream (oInpStream);
ByteArrayOutputStream oBAOS = new ByteArrayOutputStream();
int nRead = 0;
int nBlkSize = 1024 * 32;
byte[] buffer = new byte[nBlkSize];
try
{
while ((nRead = oStream.read(buffer, 0, nBlkSize)) != -1)
{
oBAOS.write(buffer, 0, nRead);
}
result = oBAOS.toByteArray();
}
catch(IOException e)
{
log.debug("Error while generating a byte array from input stream.", e);
}
finally
{
try
{
if (oStream != null)
oStream.close();
if (oBAOS != null)
oBAOS.close();
if(oInpStream != null)
oInpStream.close();
}
catch (IOException e)
{
log.debug("Error while attempting to close input/output stream.", e);
}
}
return result;
}
/**
* This function returns the session for fd-service system user.
*
* @param repository
* @return fnd-service system user session
* @throws RepositoryException
*/
public static Session getFnDServiceUserSession(SlingRepository repository)
throws RepositoryException {
Session session = repository.loginService(null, null);
return session;
}
/**
* This function returns the resource resolver for fd-service system user.
*
* @param resourceResolverFactory
* @return fnd-service system user resource resolver
* @throws RepositoryException
*/
public static ResourceResolver getFnDServiceUserResourceResolver(ResourceResolverFactory resourceResolverFactory)
throws LoginException {
ResourceResolver resourceResolver = resourceResolverFactory.getServiceResourceResolver(null);
return resourceResolver;
}
public static JSONObject convertSetOfFormInfoToJSONObject(Set formInfoList) throws FormsMgrException{
try{
JSONObject rootJson = new JSONObject();
JSONArray jsonArray = new JSONArray();
for (AssetInfo formInfo : formInfoList) {
JSONObject formInfoJSON = new JSONObject();
Resource resource = formInfo.getResource();
if(resource!=null){
Session session = resource.getResourceResolver().adaptTo(Session.class);
String title = getResourceTitle(resource);
if(title !=null && !title.isEmpty()){
formInfoJSON.put("name", title);
}
else{
formInfoJSON.put("name", resource.getName());
}
formInfoJSON.put("type", formInfo.getPublishAssetType());
formInfoJSON.put("path", resource.getPath());
ReplicationStatus replStatus = resource.adaptTo(ReplicationStatus.class);
long lastModified = FMUtils.getLastModifiedOrCreated(session, resource.getPath());
formInfoJSON.put("lastModified", lastModified);
if (replStatus != null) {
boolean published = replStatus.isDelivered() || replStatus.isActivated();
formInfoJSON.put("published", published);
if (published) {
long lastPublished = replStatus.getLastPublished().getTimeInMillis();
formInfoJSON.put("lastPublished", lastPublished);
boolean outdated = lastModified < 0 || (lastPublished < lastModified);
formInfoJSON.put("outdated", outdated);
formInfoJSON.put("status", outdated ? "outdated" : "not available");
}
}
formInfoJSON.put("disabled", ! canReplicate(resource.getPath(), session));
}
jsonArray.put(formInfoJSON);
}
rootJson.put("assets", jsonArray);
return rootJson;
} catch(Exception e){
throw new FormsMgrException(e);
}
}
public static boolean canReplicate(String path, Session session) throws RepositoryException {
AccessControlManager acMgr = session.getAccessControlManager();
return acMgr.hasPrivileges(path, new Privilege[] {acMgr.privilegeFromName(Replicator.REPLICATE_PRIVILEGE)});
}
/**
* Method to return DAM Asset json structure. This Json can be used with createAsset() API of FMCRUDService to create Asset.
* Session is not saved by this method.
* @param resourceResolver
* @param inOutAssetJSON
* @param assetType
* @param formPath
* @param formName
* @return
* @throws FormsMgrException
*/
public static void prepareJsonToCreateDAMAsset(ResourceResolver resourceResolver, JSONObject inOutAssetJSON, CoreAssetType assetType,
String formPath, String formName) throws FormsMgrException {
if(resourceResolver == null || inOutAssetJSON == null || formPath == null || formName == null) {
log.error("invalid input parametrs in prepareJsonToCreateDAMAsset()");
throw new FormsMgrException(ExceptionCodes.INVALID_PARAMETER);
}
try {
formName = formName.replaceAll("[^a-zA-Z0-9_-]", "-");
Session session = resourceResolver.adaptTo(Session.class);
if(!session.nodeExists(formPath)) {
log.error("DAM Asset to be created at non existant path : " + formPath);
Object args[] = { formPath };
throw new FormsMgrException(ExceptionCodes.NODE_DOES_NOT_EXIST, args);
}
String assetPath = ResourceUtil.normalize(formPath + "/" + formName);
inOutAssetJSON.put(FMConstants.ASSET_PATH_JSONPROPERTY, assetPath);
JSONObject assetJcrProperties = new JSONObject();
switch (assetType) {
case GUIDE:
inOutAssetJSON.put(FMConstants.ASSET_TYPE_JSONPROPERTY, FMConstants.GUIDE);
assetJcrProperties.put(FMConstants.SLING_RES_TYPE, FMConstants.AF_RESOURCE_TYPE);
break;
case AFFRAGMENT:
inOutAssetJSON.put(FMConstants.ASSET_TYPE_JSONPROPERTY, FMConstants.AFFRAGMENT);
assetJcrProperties.put(FMConstants.SLING_RES_TYPE, FMConstants.AF_RESOURCE_TYPE);
break;
case FORMSET:
inOutAssetJSON.put(FMConstants.ASSET_TYPE_JSONPROPERTY, FMConstants.FORMSET);
assetJcrProperties.put(FMConstants.SLING_RES_TYPE, FMConstants.FORMSET_SLING_RESOURCE_TYPE_VALUE);
break;
case DOCUMENT_TEMPLATE:
inOutAssetJSON.put(FMConstants.ASSET_TYPE_JSONPROPERTY, FMConstants.MULTICHANNEL_DOCUMENT);
assetJcrProperties.put(FMConstants.SLING_RES_TYPE, FMConstants.MCDOCUMENT_RESOURCE_TYPE);
}
inOutAssetJSON.put(FMConstants.ASSET_JCR_PROPERTIES_JSONPROPERTY, assetJcrProperties);
JSONObject metaDataProperties = inOutAssetJSON.getJSONObject(FMConstants.METADATA_PROPERTIES_JSONPROPERTY);
metaDataProperties.put(FMConstants.PROPERTYNAME_ALLOWED_RENDER_FORMAT, FMConstants.PROPERTYVAL_HTML);
metaDataProperties.put(FMConstants.PROPERTYNAME_AUTHOR, resourceResolver.getUserID());
metaDataProperties.put(FMConstants.JCR_PRIMARY_TYPE, FMConstants.NT_UNSTRUCTURED_NODETYPE);
if(!metaDataProperties.has(FMConstants.PROPERTYNAME_TITLE) || metaDataProperties.getString(FMConstants.PROPERTYNAME_TITLE).isEmpty()) {
metaDataProperties.put(FMConstants.PROPERTYNAME_TITLE, formName);
}
if(metaDataProperties.has(FMConstants.PROPERTYNAME_XDP_REFERENCE) && metaDataProperties.getString(FMConstants.PROPERTYNAME_XDP_REFERENCE).isEmpty()) {
metaDataProperties.remove(FMConstants.PROPERTYNAME_XDP_REFERENCE);
}
if(metaDataProperties.has(FMConstants.PROPERTYNAME_XSD_REFERENCE) && metaDataProperties.getString(FMConstants.PROPERTYNAME_XSD_REFERENCE).isEmpty()) {
metaDataProperties.remove(FMConstants.PROPERTYNAME_XSD_REFERENCE);
}
if(metaDataProperties.has(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE) && metaDataProperties.getString(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE).isEmpty()) {
metaDataProperties.remove(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE);
}
if(metaDataProperties.has(FMConstants.PROPERTYNAME_DESCRIPTION) && metaDataProperties.getString(FMConstants.PROPERTYNAME_DESCRIPTION).isEmpty()) {
metaDataProperties.remove(FMConstants.PROPERTYNAME_DESCRIPTION);
}
if(metaDataProperties.has(FMConstants.CQ_TAGS_PROPERTY)) {
String[] tags = (String[]) metaDataProperties.get(FMConstants.CQ_TAGS_PROPERTY);
if(tags != null && tags.length > 0) {
metaDataProperties.put(FMConstants.CQ_TAGS_PROPERTY, new JSONArray(Arrays.asList(tags)));
}
}
} catch (FormsMgrException fmException) {
throw fmException;
} catch (Exception e) {
log.error("error while creating json to create DAM Asset", e);
throw new FormsMgrException(ExceptionCodes.IMPROPER_ASSET_JSON);
}
}
public static Resource createCQPageResource(ResourceResolver resourceResolver, String cqPagePath , JSONObject metadataProperties, FMConstants.CoreAssetType assetType, FMConstants.FORM_MODEL form_model, String templatePath) throws FormsMgrException, RepositoryException, PersistenceException, JSONException {
JcrUtils.getOrCreateByPath(cqPagePath, FMConstants.SLING_FOLDER_NODETYPE,
FMConstants.SLING_FOLDER_NODETYPE, resourceResolver.adaptTo(Session.class), false);
AssetManager assetManager = resourceResolver.adaptTo(AssetManager.class);
if(assetType == FMConstants.CoreAssetType.GUIDE || assetType == CoreAssetType.DOCUMENT_TEMPLATE) {
String folderPath = assetType == CoreAssetType.DOCUMENT_TEMPLATE ? FMUtils.getAssetPathFromPage(Text.getRelativeParent(cqPagePath,3)) : FMUtils.getAssetPathFromPage(Text.getRelativeParent(cqPagePath,1));
Template afTemplate = getValidAFTemplate(resourceResolver, templatePath, folderPath);
if (afTemplate == null) {
throw new FormsMgrException(ExceptionCodes.INVALID_AD_TEMPLATE_PATH, new String[]{templatePath});
}
/* The following condition is to handle new authored templates that are stored in /conf and have a different structure */
if (afTemplate.hasStructureSupport()) {
assetManager.copyAsset(templatePath + "/initial", cqPagePath);
} else {
assetManager.copyAsset(templatePath, cqPagePath);
}
} else if(assetType == FMConstants.CoreAssetType.AFFRAGMENT) {
assetManager.copyAsset(FMConstants.DEFAULT_FRAGMENT_TEMPLATE_PATH, cqPagePath);
}
Resource cqPageResource = resourceResolver.getResource(cqPagePath);
Resource thumbnailResource = resourceResolver.getResource(cqPageResource, "thumbnail.png");
if (thumbnailResource != null) {
resourceResolver.delete(thumbnailResource);
}
addMetaDataToCQPage(cqPageResource, resourceResolver, cqPagePath, metadataProperties, assetType, templatePath);
Resource guideContainerResource = resourceResolver.getResource(cqPageResource, FMConstants.GUIDE_CONTAINER_PATH);
if(assetType != CoreAssetType.DOCUMENT_TEMPLATE) {
//Remove existing rootPanel items
Resource guideRootPanelItemResource = resourceResolver.getResource(guideContainerResource,
FMConstants.ROOTPANEL_NODENAME + "/" + FMConstants.ITEMS_NODENAME);
if (guideContainerResource != null) {
Node itemNode = guideRootPanelItemResource.adaptTo(Node.class);
NodeIterator Iter = itemNode.getNodes();
while (Iter.hasNext()) {
Iter.nextNode().remove();
}
}
}
return cqPageResource;
}
public static void addMetaDataToCQPage(Resource cqPageResource, ResourceResolver resourceResolver, String cqPagePath, JSONObject metadataProperties, CoreAssetType assetType, String templatePath) throws JSONException {
if (cqPageResource != null) {
ModifiableValueMap mvm = cqPageResource.adaptTo(ModifiableValueMap.class);
mvm.remove(FMConstants.JCR_TITLE);
mvm.remove(FMConstants.JCR_DESCRIPTION);
mvm.remove(FMConstants.PROPERTYNAME_ALLOWED_PATHS);
mvm.put(FMConstants.JCR_PRIMARY_TYPE, FMConstants.CQ_PAGE_NODETYPE);
Resource jcrContentResource = resourceResolver.getResource(cqPageResource, FMConstants.JCR_CONTENT_NODE_NAME);
mvm = jcrContentResource.adaptTo(ModifiableValueMap.class);
if (assetType == FMConstants.CoreAssetType.GUIDE) {
mvm.put(FMConstants.PROPERTYNAME_CQ_TEMPLATE, templatePath);
} else if (assetType == FMConstants.CoreAssetType.AFFRAGMENT) {
mvm.put(FMConstants.PROPERTYNAME_CQ_TEMPLATE, FMConstants.DEFAULT_FRAGMENT_TEMPLATE_PATH);
}
mvm.put(FMConstants.JCR_LANGUAGE_PROPERTY, FMConstants.JCR_LANGUAGE_EN);
mvm.put(FMConstants.CQ_LAST_MODIFIED_BY, resourceResolver.getUserID());
mvm.put(FMConstants.CQ_LAST_MODIFIED, Calendar.getInstance());
mvm.remove(FMConstants.GUIDE_COMPONENT_TYPE);
if (assetType != CoreAssetType.DOCUMENT_TEMPLATE) {
mvm.put(FMConstants.JCR_TITLE, metadataProperties.getString(FMConstants.PROPERTYNAME_TITLE));
}
} else {
log.error("Error. Unable to add metadata to CQ Page while form generation as CQ Page resource should not be null. Path: " + cqPagePath);
}
}
public static void handleViewPrintNodeForDOR(String dorType, Resource guideContainerResource) {
if(FMConstants.PROPERTYVAL_DORTYPE_GENERATE.equals(dorType)) {
Node guideContainerNode = guideContainerResource.adaptTo(Node.class);
try {
Node viewNode = guideContainerNode.addNode("view", FMConstants.NT_UNSTRUCTURED_NODETYPE);
Node printNode = viewNode.addNode("print", FMConstants.NT_UNSTRUCTURED_NODETYPE);
Calendar cal = Calendar.getInstance();
printNode.setProperty(FMConstants.PROPERTYNAME_METATEMPLATE_REFERENCE, "/libs/fd/af/dor/templates/defaultTemplate.xdp");
printNode.setProperty(FMConstants.SLING_RES_TYPE, "fd/af/authoring/components/dor/dorProperties");
printNode.setProperty(JcrConstants.JCR_CREATED, cal);
printNode.setProperty(JcrConstants.JCR_LASTMODIFIED, cal);
} catch (RepositoryException e) {
log.error("Unable to create view/print node for DOR Type generate", e);
}
}
}
public static void addMetaDataToGuideContainer(ResourceResolver resourceResolver, String cqPagePath , JSONObject metadataProperties, CoreAssetType assetType, FMConstants.FORM_MODEL form_model) throws JSONException {
Resource guideContainerResource = resourceResolver.getResource(cqPagePath + "/" + FMConstants.GUIDE_CONTAINER_PATH);
if (guideContainerResource != null) {
ModifiableValueMap mvm = guideContainerResource.adaptTo(ModifiableValueMap.class);
// add fd:version in guideContainer node
if (assetType != CoreAssetType.DOCUMENT_TEMPLATE) {
mvm.put(FMConstants.STR_FD_VERSION_NAME, metadataProperties.getString(FMConstants.STR_FD_VERSION_NAME));
} else {
mvm.put(FMConstants.STR_FD_VERSION_NAME, FMConstants.CURRENT_AFF_SPEC_VERSION);
}
// set the themeRef, DoR Template Ref and DoR type property
if (assetType == CoreAssetType.DOCUMENT_TEMPLATE || assetType == FMConstants.CoreAssetType.GUIDE) {
if (metadataProperties != null) {
if (metadataProperties.has(FMConstants.PROPERTYNAME_THEME_REFERENCE)) {
mvm.put(FMConstants.PROPERTYNAME_THEME_REFERENCE, metadataProperties.getString(FMConstants.PROPERTYNAME_THEME_REFERENCE));
}
if (metadataProperties.has(FMConstants.PROPERTYNAME_DOR_REFERENCE)) {
mvm.put(FMConstants.PROPERTYNAME_DOR_REFERENCE, metadataProperties.getString(FMConstants.PROPERTYNAME_DOR_REFERENCE));
}
if (metadataProperties.has(FMConstants.PROPERTYNAME_DOR_TYPE)) {
String dorType = metadataProperties.getString(FMConstants.PROPERTYNAME_DOR_TYPE);
mvm.put(FMConstants.PROPERTYNAME_DOR_TYPE, dorType);
handleViewPrintNodeForDOR(dorType, guideContainerResource);
}
}
}
if (assetType == FMConstants.CoreAssetType.GUIDE) {
switch (form_model) {
case FORM_TEMPLATE:
mvm.put(FMConstants.PROPERTYNAME_XDP_REFERENCE, metadataProperties.getString(FMConstants.PROPERTYNAME_XDP_REFERENCE));
break;
case XML_SCHEMA:
mvm.put(FMConstants.PROPERTYNAME_XSD_REFERENCE, metadataProperties.getString(FMConstants.PROPERTYNAME_XSD_REFERENCE));
mvm.put(FMConstants.PROPERTYNAME_XSD_ROOT_ELEMENT, metadataProperties.getString(FMConstants.PROPERTYNAME_XSD_ROOT_ELEMENT));
mvm.put(FMConstants.PROPERTYNAME_SCHEMA_TYPE, FMConstants.PROPERTYVAL_FORMMODEL_XMLSCHEMA);
break;
case JSON_SCHEMA:
mvm.put(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE, metadataProperties.getString(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE));
mvm.put(FMConstants.PROPERTYNAME_SCHEMA_TYPE, FMConstants.PROPERTYVAL_FORMMODEL_JSONSCHEMA);
break;
case FORM_DATA_MODEL:
mvm.put(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE, metadataProperties.getString(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE));
mvm.put(FMConstants.PROPERTYNAME_SCHEMA_TYPE, FMConstants.PROPERTYVAL_FORMMODEL_FORMDATAMODEL);
break;
}
//Adding adobe sign related configuration
mvm.put(FMConstants.USE_SIGNED_PDF, metadataProperties.optBoolean(FMConstants.USE_SIGNED_PDF));
if (StringUtils.isNotBlank(metadataProperties.optString(FMConstants.ADOBE_SIGN_CONFIG_PATH))) {
Resource signerInfoResource = resourceResolver.getResource(guideContainerResource, FMConstants.SIGNER_INFO);
if (signerInfoResource != null) {
ModifiableValueMap signvm = signerInfoResource.adaptTo(ModifiableValueMap.class);
signvm.put(FMConstants.ADOBE_SIGN_CONFIG_PATH, metadataProperties.getString(FMConstants.ADOBE_SIGN_CONFIG_PATH));
}
}
} else if (assetType == FMConstants.CoreAssetType.AFFRAGMENT) {
switch (form_model) {
case FORM_TEMPLATE:
mvm.put(FMConstants.PROPERTYNAME_XDP_REFERENCE, metadataProperties.getString(FMConstants.PROPERTYNAME_XDP_REFERENCE));
mvm.put(FMConstants.PROPERTYNAME_FRAGMENT_MODEL_ROOT, metadataProperties.getString(FMConstants.PROPERTYNAME_FRAGMENT_MODEL_ROOT));
break;
case XML_SCHEMA:
mvm.put(FMConstants.PROPERTYNAME_XSD_REFERENCE, metadataProperties.getString(FMConstants.PROPERTYNAME_XSD_REFERENCE));
mvm.put(FMConstants.PROPERTYNAME_FRAGMENT_MODEL_ROOT, metadataProperties.getString(FMConstants.PROPERTYNAME_FRAGMENT_MODEL_ROOT));
mvm.put(FMConstants.PROPERTYNAME_SCHEMA_TYPE, FMConstants.PROPERTYVAL_FORMMODEL_XMLSCHEMA);
break;
case JSON_SCHEMA:
mvm.put(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE, metadataProperties.getString(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE));
mvm.put(FMConstants.PROPERTYNAME_FRAGMENT_MODEL_ROOT, metadataProperties.getString(FMConstants.PROPERTYNAME_FRAGMENT_MODEL_ROOT));
mvm.put(FMConstants.PROPERTYNAME_SCHEMA_TYPE, FMConstants.PROPERTYVAL_FORMMODEL_JSONSCHEMA);
break;
case FORM_DATA_MODEL:
mvm.put(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE, metadataProperties.getString(FMConstants.PROPERTYNAME_SCHEMA_REFERENCE));
mvm.put(FMConstants.PROPERTYNAME_FRAGMENT_MODEL_ROOT, metadataProperties.getString(FMConstants.PROPERTYNAME_FRAGMENT_MODEL_ROOT));
mvm.put(FMConstants.PROPERTYNAME_SCHEMA_TYPE, FMConstants.PROPERTYVAL_FORMMODEL_FORMDATAMODEL);
break;
}
}
} else {
log.error("Error. Unable to add metadata to guide container while form generation as guide container resource should not be null. Path: " + cqPagePath);
}
}
/**
* Create the Node hierarchy under FM_AF_ROOT and delete all the rootPanel item nodes.
* Session is not saved by this method.
* @param resourceResolver
* @param paramsJson
* @param assetType
* @param form_model
* @param templatePath
* @return cqPageNode
* @throws FormsMgrException
*/
public static Node createCQPageNode(ResourceResolver resourceResolver, JSONObject paramsJson, FMConstants.CoreAssetType assetType, FMConstants.FORM_MODEL form_model, String templatePath)
throws FormsMgrException{
try {
String cqPagePath = FMUtils.getPagePathFromAsset(paramsJson.getString(FMConstants.ASSET_PATH_JSONPROPERTY));
JSONObject metadataProperties = paramsJson.getJSONObject(FMConstants.METADATA_PROPERTIES_JSONPROPERTY);
Resource cqPageResource = createCQPageResource(resourceResolver,cqPagePath,metadataProperties,assetType,form_model,templatePath);
return cqPageResource.adaptTo(Node.class);
} catch (FormsMgrException e){
log.error("Error while creating cq page Node : ", e);
throw e;
} catch (Exception e){
log.error("Error while creating cq page Node : ", e);
throw new FormsMgrException(ExceptionCodes.FORM_NODE_CREATION_FAILED);
}
}
/**
* Returns a Template object for the AF template path provided. Returns null if the template path is invalid.
* @param resourceResolver
* @param afTemplatePath
* @throws RepositoryException
* @return Template
*/
public static Template getValidAFTemplate (ResourceResolver resourceResolver, String afTemplatePath, String assetPathSuffix) throws RepositoryException {
if(afTemplatePath != null && !afTemplatePath.isEmpty())
{
Resource afTemplateResource = resourceResolver.getResource(afTemplatePath);
if (afTemplateResource != null) {
Template afTemplate = afTemplateResource.adaptTo(Template.class);
if (afTemplate != null) {
if (afTemplate.hasStructureSupport()) {
//This is an authored template that is stored in /conf and has a different structure. Validating if it is enabled.
ValueMap templateProperties = afTemplate.getProperties();
String status = templateProperties.get(FMConstants.PROPERTYNAME_STATUS, String.class);
if (status != null && FMConstants.STR_ENABLED.equals(status) && TemplateUtils.isTemplateAllowed(resourceResolver.adaptTo(Session.class), afTemplatePath, assetPathSuffix)) {
return afTemplate;
} else {
log.error("Invalid Adaptive Form Template {}. This authored template is not enabled.", afTemplatePath);
}
} else {
//This is a static template and so no more validation required.
return afTemplate;
}
}
}
}
return null;
}
/**
* Method to create jcr nodes from json. This behaves similar to sling post but doesn't include all the node types.
* Session is not saved by this method.
* jcr:mixinTypes property - it is skipped, if found, while setting properties on node.
* nt:File node - It is skipped(not added), if found, while adding nodes.
* @param node - Json structure will be mapped under this node.
* @param jsonObject
* @return Node
* @throws FormsMgrException
*/
public static void JsonToJcrNode(Node node, JSONObject jsonObject)
throws JSONException, RepositoryException {
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Object property = jsonObject.get(key);
handleProperty(node, key, property);
}
}
private static void handleProperty(Node node, String name, Object property)
throws JSONException, RepositoryException {
if (JSONObject.class.isAssignableFrom(property.getClass())) {
Node childNode;
JSONObject nodeJson = (JSONObject) property;
if(nodeJson.has(FMConstants.JCR_PRIMARY_TYPE) && nodeJson.getString(FMConstants.JCR_PRIMARY_TYPE).equals(FMConstants.NT_FILE_NODETYPE)) {
// nt:file would be binary data. skipping it.
return;
}
if (node.hasNode(name)) {
childNode = node.getNode(name);
} else {
childNode = node.addNode(name, FMConstants.NT_UNSTRUCTURED_NODETYPE);
}
JsonToJcrNode(childNode, (JSONObject) property);
} else {
if(name.equals(FMConstants.JCR_PRIMARY_TYPE) || name.equals(FMConstants.JCR_MIXIN_TYPES)) {
return;
}
Object propertyValue = property;
if (property instanceof String) {
propertyValue = StringUtils.trim((String) property);
} else if(property instanceof JSONArray) {
JSONArray arrJson = (JSONArray) property;
int len = arrJson.length();
String[] strArr = new String[len];
for(int i=0; i T notNulOrDefault(T getValue, T defaultValue) {
return (getValue == null) ? defaultValue : getValue;
}
/**
* This API sets the identifier at node.
* @param node at which identifier is to be set
* @param assetType to be set as an identifier
* @throws FormsMgrException
*/
public static void setAssetIdentifier(Node node, String assetType, int validOrdinal) throws FormsMgrException {
try {
node.setProperty(assetType, validOrdinal);
node.setProperty(FMConstants.TYPE_PROPERTY, assetType);
} catch (ValueFormatException e) {
throw new FormsMgrException(e);
} catch (VersionException e) {
throw new FormsMgrException(e);
} catch (LockException e) {
throw new FormsMgrException(e);
} catch (ConstraintViolationException e) {
throw new FormsMgrException(e);
} catch (RepositoryException e) {
throw new FormsMgrException(e);
}
}
/**
* API checks whether given client lib category does exist across aem or not
* @param clientlibCategoryName
* @param htmlLibraryManager
* @return
*/
public static boolean clientlibExists(String clientlibCategoryName, HtmlLibraryManager htmlLibraryManager) {
boolean clientLibExists = false;
Map libraries = htmlLibraryManager.getLibraries();
if(libraries != null) {
for(ClientLibrary library : libraries.values()) {
String categories[] = library.getCategories();
if(categories != null && ArrayUtils.contains(categories, clientlibCategoryName)) {
clientLibExists = true;
break;
}
}
}
return clientLibExists;
}
/**
* This function retrieves string value of a request parameter.
*
* @param paramMap
* @param param
* @return String value of the req parameter. null is no such param is found.
*/
public static String getRequestParamValue (RequestParameterMap paramMap, String param){
String paramValue = null;
if(paramMap.containsKey(param)) {
if (StringUtils.isNotBlank(paramMap.getValue(param).getString())) {
paramValue = paramMap.getValue(param).getString();
}
}
return paramValue;
}
/**
* This API returns title of an asset. If title is empty then it returns name of node.
* @param resource
* @return String
*/
public static String getTitle(Resource resource) {
String title = "";
try {
Node childAsset = resource.adaptTo(Node.class);
if (childAsset != null) {
Node metadataNode = getMetadataNode(childAsset, false);
Node contentNode;
if (metadataNode != null && metadataNode.hasProperty(FMConstants.PROPERTYNAME_TITLE)) {
title = metadataNode.getProperty(FMConstants.PROPERTYNAME_TITLE).getString();
} else {
contentNode = getContentNode(childAsset, false);
if (contentNode != null && contentNode.hasProperty(FMConstants.JCR_TITLE)) {
title = contentNode.getProperty(FMConstants.JCR_TITLE).getString();
}
}
if (StringUtils.isEmpty(title)) {
title = childAsset.getName();
}
}
} catch (Exception e) {
log.error("Exception while fetching title of resource: "+resource.getPath(), e);
}
return title.trim();
}
/**
* This API returns display type of an Asset.
* @param resource
* @return String
*/
public static String getDisplayType(Resource resource) {
String displayType = "";
try {
Node childAsset = resource.adaptTo(Node.class);
Session session = resource.getResourceResolver().adaptTo(Session.class);
if (childAsset != null) {
if (childAsset.isNodeType(FMConstants.SLING_FOLDER_NODETYPE)) {
displayType = FMConstants.FOLDER;
if (childAsset.hasProperty(FMConstants.LC_APPLICATION)) {
displayType = FMConstants.FORMS_WORKFLOW_APPLICATION;
}
} else {
String childPath = childAsset.getPath();
CoreAssetType type = FMUtils.getAssetType(session, childPath);
AssetInfo assetInfo = new AssetInfo(resource, type);
displayType = assetInfo.getPublishAssetType();
if (FMConstants.PUBLISH_ASSET_TYPE_THEME.equals(displayType)) {
displayType = FMConstants.FOLDER;
if (childAsset.hasProperty(FMConstants.LC_APPLICATION)) {
displayType = FMConstants.FORMS_WORKFLOW_APPLICATION;
}
}
}
}
} catch (Exception e) {
log.error("Exception while fetching display type of resource: "+resource.getPath(), e);
}
return displayType;
}
/**
* This API returns size of Asset. Its applicable for externally authored forms since they have a binary representation.
* @param resource
* @return long
*/
public static long getSize(Resource resource) {
long bytes = 0;
try {
Asset asset = resource.adaptTo(Asset.class);
if (asset != null) {
Rendition rendition = asset.getRendition(FMConstants.ORIGINAL_RENDITION_NODE_NAME);
if (rendition != null) {
bytes = rendition.getSize();
}
}
} catch (Exception e) {
log.error("Exception while fetching size of resource: "+resource.getPath(), e);
}
return bytes;
}
/**
* This API returns description of an Asset.
* @param resource
* @return String
*/
public static String getDescription(Resource resource) {
String desc = "";
try {
Node childAsset = resource.adaptTo(Node.class);
if (childAsset != null) {
Node metadataNode = getMetadataNode(childAsset, false);
if (metadataNode != null && metadataNode.hasProperty(FMConstants.PROPERTYNAME_DESCRIPTION)) {
desc = metadataNode.getProperty(FMConstants.PROPERTYNAME_DESCRIPTION).getString();
}
}
} catch (Exception e) {
log.error("Exception while fetching description of resource: "+resource.getPath(), e);
}
return desc.trim();
}
/**
* This API returns current status of an Asset.
* @param resource
* @return String
*/
public static String getStatus(Resource resource) {
String status = "";
try {
Node childAsset = resource.adaptTo(Node.class);
Node contentNode;
long modificationDateInMillis = -1;
long publishDateInMillis = -2;
if (childAsset != null) {
contentNode = getContentNode(childAsset, false);
if (contentNode != null) {
if (contentNode.hasProperty(JcrConstants.JCR_LASTMODIFIED)) {
Calendar cal = contentNode.getProperty(JcrConstants.JCR_LASTMODIFIED).getDate();
if (cal != null) {
modificationDateInMillis = cal.getTimeInMillis();
}
}
if (contentNode.hasProperty(FMConstants.CQ_LAST_REPLICATED)) {
Calendar cal = contentNode.getProperty(FMConstants.CQ_LAST_REPLICATED).getDate();
if (cal != null)
publishDateInMillis = cal.getTimeInMillis();
}
}
if (modificationDateInMillis > publishDateInMillis && publishDateInMillis > 0) {
status = FMConstants.DISPLAY_STATUS_MODIFIED;
} else if (publishDateInMillis > 0) {
status = FMConstants.DISPLAY_STATUS_PUBLISHED;
}
}
} catch (Exception e) {
log.error("Exception while fetching status of resource: "+resource.getPath(), e);
}
return status;
}
/**
* This API returns last modified time of an Asset.
* @param resource
* @return long
*/
public static long getLastModified(Resource resource) {
long modificationDateInMillis = -1;
try {
Node childAsset = resource.adaptTo(Node.class);
Session session = resource.getResourceResolver().adaptTo(Session.class);
if (childAsset != null) {
modificationDateInMillis = getLastModifiedOrCreated(session, childAsset.getPath());
}
} catch (Exception e) {
log.error("Exception while fetching last modified time of resource: "+resource.getPath(), e);
}
return modificationDateInMillis;
}
/**
* @param resource a multichhanel document asset resource residing under /content/dam/formsanddocuments/
* It's the responsibility of the caller to make sure that the resource refers to a valid multichannel document
* @return Resource representing Print channel of the multichannel document
* @throws FormsMgrException if any exception occurs while trying to load the resource and its hierarchy
*/
public static Resource getPrintChannelResource(Resource resource) throws FormsMgrException {
String pagepath = getPagePathFromAsset(resource.getPath());
try{
ResourceResolver resolver = resource.getResourceResolver();
Resource pageResource = resolver.getResource(pagepath);
Resource printChannelResource = pageResource.getChild(FMConstants.DOCUMENT_CHANNELS_NODENAME + FMConstants.DELIMITER_SLASH + FMConstants.CHANNEL_TYPE_PRINT);
return printChannelResource;
} catch (Exception e) {
throw new FormsMgrException(e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy