All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.adobe.fd.fp.util.MetadataBaseService Maven / Gradle / Ivy

/*************************************************************************
 *
 * ADOBE CONFIDENTIAL
 * ___________________
 *
 *  Copyright 2016 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 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.fd.fp.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
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.ItemExistsException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFormatException;
import javax.jcr.lock.LockException;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NoSuchNodeTypeException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.version.VersionException;

import org.apache.commons.lang.StringUtils;
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.felix.scr.annotations.ReferencePolicyOption;
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.jcr.api.SlingRepository;
import org.apache.sling.settings.SlingSettingsService;

import com.adobe.fd.fp.common.PortalUtilsComponent;
import com.adobe.fd.fp.config.FormsPortalDraftsandSubmissionConfigService;
import com.adobe.fd.fp.exception.ErrorMessages;
import com.adobe.fd.fp.exception.FormsPortalException;
import com.adobe.fd.fp.model.DraftMetadata;
import com.adobe.fd.fp.service.FPKeyGeneratorService;
import com.adobe.fd.fp.service.Statement;
import com.adobe.fd.fp.service.Statement.Operator;
import com.adobe.fd.fp.service.StatementGroup;
import com.adobe.fd.fp.service.StatementGroup.JoinOperator;
import com.adobe.granite.resourceresolverhelper.ResourceResolverHelper;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.Replicator;
import com.day.cq.search.Predicate;
import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.eval.JcrPropertyPredicateEvaluator;
import com.day.cq.search.eval.PathPredicateEvaluator;
import com.day.cq.search.eval.TypePredicateEvaluator;
import com.day.cq.search.result.SearchResult;

/**
 * Base class for all meta data service implementations like DraftsMetadata, 
 * SubmitMetadata, PendingSignMetdata, etc.
 * 
 * @author sharoon
 * @date 10-Oct-2016
 * @time 4:59:25 pm
 */
@Component
public abstract class MetadataBaseService {

	@Reference
	protected ResourceResolverHelper resourceResolverHelper;
	
	@Reference
	protected FormsPortalDraftsandSubmissionConfigService draftsandSubmissionConfiguration;
	
	@Reference
    protected PortalUtilsComponent portalUtilsComponent;
	
	@Reference
	protected SlingRepository slingRepository;
	
	@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY)
	protected FPKeyGeneratorService fpKeyGeneratorService;
	
	@Reference
	protected QueryBuilder queryBuilder;
	
	@Reference
	protected Replicator replicator;
    
    @Reference
    protected SlingSettingsService slingSettingService;
	
	protected String instanceType;
	
	protected String nodeType;
	
	protected String idProperty;
	
	private static final Map jcrOperatorMap = new HashMap();
	
	static {
		jcrOperatorMap.put(Operator.EQUALS, JcrPropertyPredicateEvaluator.OP_EQUALS);
		jcrOperatorMap.put(Operator.NOT_EQUALS, JcrPropertyPredicateEvaluator.OP_EQUALS);
		jcrOperatorMap.put(Operator.EXISTS, JcrPropertyPredicateEvaluator.OP_EXISTS);
		jcrOperatorMap.put(Operator.NOT, JcrPropertyPredicateEvaluator.OP_NOT);
		jcrOperatorMap.put(Operator.LIKE, JcrPropertyPredicateEvaluator.OP_LIKE);
	}
	
	protected JSONObject saveMetadataInternal(Map metadataPropMap) throws FormsPortalException {
		RepositoryUtils repUtils = RepositoryUtils.getInstance(draftsandSubmissionConfiguration);
		boolean isOwner = false;
        Session sysUserSession = null;
        JSONObject jsonObject = null;
        try{  
            sysUserSession    = PortalUtils.getFnDServiceUserSession(slingRepository);
            String instanceID   = (String)metadataPropMap.get(idProperty);                     
            Node currentInstanceMetadataNode = null;
            boolean isUserAllowed = false;
            Session currentSession = resourceResolverHelper.getResourceResolverAs(Session.class);
            
            if(instanceID == null || instanceID.trim().isEmpty()){
		        instanceID = fpKeyGeneratorService.getUniqueId();
	            currentInstanceMetadataNode = addMetadataNode(metadataPropMap,
						repUtils, sysUserSession, instanceID);
	            isUserAllowed = true;
            } else {
                currentInstanceMetadataNode = getMetadataNodeFromInstanceID(instanceID, sysUserSession);
                if (currentInstanceMetadataNode == null) {
                    currentInstanceMetadataNode = getInstanceNodeForProperty(instanceID, sysUserSession);
                    if (currentInstanceMetadataNode == null) {
                        currentInstanceMetadataNode = addMetadataNode(metadataPropMap, repUtils, sysUserSession, instanceID);
                    }
                }
                String formPath = currentInstanceMetadataNode.hasProperty(FormsPortalConstants.STR_FORM_PATH) ? currentInstanceMetadataNode.getProperty(FormsPortalConstants.STR_FORM_PATH).getString() : null;
                isUserAllowed = portalUtilsComponent.isReviewer(currentSession, formPath);
                isOwner = isOwner(currentSession, instanceID);
                if(isOwner && !isUserAllowed) {
                    Set allowedKeys = new HashSet(Arrays.asList(FormsPortalConstants.STR_UPDATION_ALLOWED_PROPERTIES));
                    metadataPropMap.keySet().retainAll(allowedKeys);
                }
            }
            if(isUserAllowed || isOwner){
	            PortalUtils.updatePropertiesOnNode(metadataPropMap, currentInstanceMetadataNode);

	            currentInstanceMetadataNode.setProperty(instanceType + FormsPortalConstants.STR_ID_CAPS, instanceID);
	            updateLastModified(currentInstanceMetadataNode);
	            sysUserSession.save();

	            if(slingSettingService.getRunModes().contains("publish")){
	                PortalUtils.reverseReplicate(sysUserSession, currentInstanceMetadataNode.getPath().toString(), ReplicationActionType.ACTIVATE, replicator, draftsandSubmissionConfiguration.getFormsPortalOutboxes());
	            }

	            jsonObject = postProcessMetadataNode(currentInstanceMetadataNode);
            }
		}  catch (FormsPortalException e) {
			throw e;
		} catch (Exception e) {
			throw new FormsPortalException(e);
		}
        finally {
            if (sysUserSession != null) {
                sysUserSession.logout();
            }
        }
        return jsonObject;
	}

	protected Node addMetadataNode(Map metadataPropMap,
			RepositoryUtils repUtils, Session sysUserSession, String instanceID)
			throws ItemExistsException, PathNotFoundException,
			NoSuchNodeTypeException, LockException, VersionException,
			ConstraintViolationException, RepositoryException,
			UnsupportedEncodingException, FormsPortalException {
		Node userNode;
		Node rootNode;
		Node currentInstanceNode;
		Node currentInstanceMetadataNode;
		userNode = repUtils.getUserNode(getUserName(sysUserSession,(String) metadataPropMap.get(FormsPortalConstants.STR_OWNER)), true, sysUserSession);
		rootNode = repUtils.getChildNode(userNode, instanceType, FormsPortalConstants.STR_SLING_ORDERED_FOLDER, true);
		currentInstanceNode = repUtils.getChildNode(rootNode, FormsPortalConstants.STR_METADATA, FormsPortalConstants.STR_SLING_ORDERED_FOLDER, true);
		currentInstanceMetadataNode = repUtils.getChildNode(currentInstanceNode, instanceID, NodeType.NT_UNSTRUCTURED, true);
		return currentInstanceMetadataNode;
	}
	
	protected boolean deleteMetadataInternal(String id) throws FormsPortalException {
		boolean status = false;
		boolean isAnonymous     = portalUtilsComponent.isLoginAnonymous();
		Session currentSession  = resourceResolverHelper.getResourceResolverAs(Session.class);
		Session sysUserSession  = null; 
		if(id == null || id.trim().isEmpty()){
			throw new FormsPortalException(ErrorMessages.ALC_FMP_001_016);
		}
		try{
			sysUserSession   = PortalUtils.getFnDServiceUserSession(slingRepository);
			RepositoryUtils repUtils = RepositoryUtils.getInstance(draftsandSubmissionConfiguration);
			String userName = resourceResolverHelper.getResourceResolver().getUserID();

			if(isAnonymous) {
				currentSession = sysUserSession;
			}
			Node userNode = repUtils.getUserNode(userName, false, currentSession);
			Node instanceMetadataNode = getMetadataNodeFromInstanceID(id, currentSession);
			if((userName.equals(sysUserSession.getUserID())||userNode != null) && instanceMetadataNode != null){
				if(instanceMetadataNode.hasProperty(idProperty)){
					if (currentSession != null) {
						if(slingSettingService.getRunModes().contains("publish")){
							PortalUtils.reverseReplicate(sysUserSession, instanceMetadataNode.getPath(), ReplicationActionType.DELETE, replicator, draftsandSubmissionConfiguration.getFormsPortalOutboxes());
						} else {
							PortalUtils.replicate(sysUserSession, instanceMetadataNode.getPath(), ReplicationActionType.DELETE, replicator);
						}
						// Local node is always deleted immediately, because delete as a result of replication may take some time
						currentSession.getNode(instanceMetadataNode.getPath()).remove();
						currentSession.save();
						status = true;
					} else{
						throw new FormsPortalException(ErrorMessages.ALC_FMP_001_017);
					}
				} else{
					throw new FormsPortalException(ErrorMessages.ALC_FMP_001_051, new Object[]{instanceType, id});
				}
			} else{
				throw new FormsPortalException(ErrorMessages.ALC_FMP_001_020);
			}
		}  catch (FormsPortalException e) {
			throw e;
		} catch (Exception e) {
			throw new FormsPortalException(e);
		} finally {
			if(sysUserSession != null){
				sysUserSession.logout();
			}
		}
		return status;	
	}
	
	protected JSONArray getInstances(String cutPoints) throws FormsPortalException {

		List instancesList = new ArrayList();
		RepositoryUtils repUtils = RepositoryUtils.getInstance(draftsandSubmissionConfiguration);
		String userName = resourceResolverHelper.getResourceResolver().getUserID();
		Session currentSession = resourceResolverHelper.getResourceResolverAs(Session.class);
		JSONArray instancesArray = new JSONArray();
		try {
			Node userNode = repUtils.getUserNode(userName, false, currentSession);
			if (userNode != null && !portalUtilsComponent.isLoginAnonymous()) {
				Node instanceRootnode = repUtils.getChildNode(userNode, instanceType, FormsPortalConstants.STR_SLING_ORDERED_FOLDER, false);
				if (instanceRootnode != null && instanceRootnode.hasNode(FormsPortalConstants.STR_METADATA)) {					
					Node metaDataRootNode = repUtils.getChildNode(instanceRootnode, FormsPortalConstants.STR_METADATA, FormsPortalConstants.STR_SLING_ORDERED_FOLDER, false);
					instancesList.addAll(readInstances(metaDataRootNode, cutPoints));
					Collections.sort(instancesList);
					JSONObject formJson = null;
					for (DraftMetadata instanceMetadata: instancesList) {
						formJson = instanceMetadata.getJSONObject();
						instancesArray.put(formJson);
					}
				}
			}
		}  catch (FormsPortalException e) {
			throw e;
		} catch (ItemExistsException e) {
			throw new FormsPortalException(e);
		} catch (PathNotFoundException e) {
			throw new FormsPortalException(e);
		} catch (NoSuchNodeTypeException e) {
			throw new FormsPortalException(e);
		} catch (LockException e) {
			throw new FormsPortalException(e);
		} catch (VersionException e) {
			throw new FormsPortalException(e);
		} catch (ConstraintViolationException e) {
			throw new FormsPortalException(e);
		} catch (RepositoryException e) {
			throw new FormsPortalException(e);
		} catch (Exception e) {
			throw new FormsPortalException(e);
		}
		
		return instancesArray;
	
	}
	
    protected boolean deletePropertyInternal(String instanceID, String propertyName) throws FormsPortalException {
        boolean isAnonymous    = portalUtilsComponent.isLoginAnonymous();
        Session currentSession = resourceResolverHelper.getResourceResolverAs(Session.class);
        Session sysUserSession = null;
        try{
            RepositoryUtils repUtils = RepositoryUtils.getInstance(draftsandSubmissionConfiguration);
            sysUserSession = PortalUtils.getFnDServiceUserSession(slingRepository);
            String userName          = resourceResolverHelper.getResourceResolver().getUserID();
            if(isAnonymous){
                 currentSession  = sysUserSession;
            }
 
    	    Node instanceMetadataNode 	= getMetadataNodeFromInstanceID(instanceID, currentSession);
    	    Node userNode                		 	= repUtils.getUserNode(userName, false, currentSession);
    	    if((userName.equals(sysUserSession.getUserID()) || userNode != null) && instanceMetadataNode != null) {
    	        if(instanceMetadataNode != null && instanceMetadataNode.hasProperty(propertyName)){
    	        	javax.jcr.Property prop = instanceMetadataNode.getProperty(propertyName);
    	        	prop.setValue((String[])null);
    	        	currentSession.save();
    	        	return true;
    	        }
    	    }
    	    return false;
    	}  catch (FormsPortalException e) {
			throw e;
		} catch(Exception e){
    		throw new FormsPortalException(ErrorMessages.ALC_FMP_001_052, e, new Object[]{propertyName, instanceType, instanceID});
    	} finally {
    		if(isAnonymous){
    			currentSession.logout();
    		}
            if(sysUserSession != null) {
                sysUserSession.logout();
            }
    	}
	}
	
	public String[] getProperty (String instanceID, String propertyName)  throws FormsPortalException {
		String[] result = new String[]{""};
		Session sysUserSession = null;
		try {
			sysUserSession = PortalUtils.getFnDServiceUserSession(slingRepository);
			Session currentSession = resourceResolverHelper.getResourceResolverAs(Session.class);
			String userName = currentSession.getUserID();
			Node instanceMetadataNode = getMetadataNodeFromInstanceID(instanceID, currentSession);
			if (instanceMetadataNode == null) {
				if (portalUtilsComponent.isLoginAnonymous()) {	//Anonymous use case
					String metadatNodePathForAnon = draftsandSubmissionConfiguration.getFormsPortalRoot() + "/" + userName + "/" +
                            instanceType + "/" + FormsPortalConstants.STR_METADATA + "/" + instanceID;
					if (sysUserSession.nodeExists(metadatNodePathForAnon)) {
						instanceMetadataNode = sysUserSession.getNode(metadatNodePathForAnon);
					}
				} else {
					instanceMetadataNode = getInstanceNodeForProperty(instanceID, sysUserSession);
				}
			}
			if (instanceMetadataNode != null && instanceMetadataNode.hasProperty(propertyName)) {
				 javax.jcr.Property prop = instanceMetadataNode.getProperty(propertyName);
                if(prop != null){
                    if(!prop.isMultiple()){
                        String propValue = instanceMetadataNode.getProperty(propertyName).getString();
                        result = new String[]{propValue};
                    } else {
                        Value [] propValueList = instanceMetadataNode.getProperty(propertyName).getValues();
                        List attachmentStringList = new ArrayList();
                        for(Value propVals : propValueList){
						    String propValStr = propVals.getString();
						    attachmentStringList.add(propValStr);
					    }
					    result = attachmentStringList.toArray(new String[0]);
                    }
                }
			}
		} catch (FormsPortalException e) {
			throw e;
		}  catch(Exception e){
    		throw new FormsPortalException(ErrorMessages.ALC_FMP_001_052, e, new Object[]{propertyName, instanceType, instanceID});
        } finally {
            if(sysUserSession != null){
                sysUserSession.logout();
            }
        }
		return result;
	}
	
	protected Node getInstanceNodeForProperty(String instanceID, Session sysUserSession) throws Exception {
		return null;
	}
	private List readInstances(Node instanceRootNode, String cutPoints) throws ValueFormatException, 
	PathNotFoundException, RepositoryException, Exception {
		List instancesList = new ArrayList();
		NodeIterator itr = instanceRootNode.getNodes();
		while(itr.hasNext()) {
			instancesList.add(readInstance(itr.nextNode(), cutPoints));
		}
		return instancesList;
	}
 	protected abstract JSONObject postProcessMetadataNode(Node currentInstanceNode) throws FormsPortalException;
	
	protected abstract DraftMetadata readInstance(Node instanceMetadataNode, String cutPoints) throws FormsPortalException;
	
	protected JSONObject readInstance(String instanceID, String cutPoints) throws FormsPortalException {
		if (StringUtils.isEmpty(instanceID)) {
			throw new FormsPortalException(ErrorMessages.ALC_FMP_001_016);
		}
        Session currentSession = null;
        try{  
            currentSession = resourceResolverHelper.getResourceResolverAs(Session.class);
            Node currentInstanceUserdataNode = getMetadataNodeFromInstanceID(instanceID, currentSession);
            return readInstance(currentInstanceUserdataNode, cutPoints).getJSONObject();
		}  catch (FormsPortalException e) {
			throw e;
		} catch (Exception e) {
			throw new FormsPortalException(e);
		}
	}
	protected void readCommonProperties(Node instanceMetadataNode, DraftMetadata metadata, String cutPoints) 
			throws PathNotFoundException, RepositoryException, Exception {

		if (instanceMetadataNode.hasProperty(FormsPortalConstants.STR_FORM_NAME)) {
			metadata.setName((String)PropertyUtils.getPropertyValue(instanceMetadataNode.getProperty(FormsPortalConstants.STR_FORM_NAME)));
		} else if (instanceMetadataNode.hasProperty(FormsPortalConstants.STR_GUIDE_NAME)) {
			metadata.setName((String)PropertyUtils.getPropertyValue(instanceMetadataNode.getProperty(FormsPortalConstants.STR_GUIDE_NAME)));
		}
		if (instanceMetadataNode.hasProperty(FormsPortalConstants.STR_OWNER)) {
			metadata.setOwner((String)PropertyUtils.getPropertyValue(instanceMetadataNode.getProperty(FormsPortalConstants.STR_OWNER)));
		}
		Object lastModifiedObj = PropertyUtils.getPropertyValue(instanceMetadataNode.getProperty(FormsPortalConstants.STR_JCR_LAST_MODIFIED));
		
		Date lastModifiedDate = null;
		if(lastModifiedObj instanceof Date){
			lastModifiedDate = (Date)lastModifiedObj;
		} else if(lastModifiedObj instanceof String){
			lastModifiedDate = new Date(Long.valueOf((String)lastModifiedObj));
		} else if(lastModifiedObj instanceof Long){
			lastModifiedDate = new Date((Long) lastModifiedObj);
		}
		metadata.setLastModified(lastModifiedDate);
		
		if (instanceMetadataNode.hasProperty(FormsPortalConstants.STR_DESCRIPTION)) {
			metadata.setDescription((String)PropertyUtils.getPropertyValue(instanceMetadataNode.getProperty(FormsPortalConstants.STR_DESCRIPTION)));
		}
		List cutPointsList = Arrays.asList(cutPoints.split(","));
		for(String cutPoint : cutPointsList){
			if(instanceMetadataNode.hasProperty(cutPoint)){
				metadata.setCustomProperty(cutPoint, String.valueOf(PropertyUtils.getPropertyValue(instanceMetadataNode.getProperty(cutPoint))));
			} else if (cutPoint.equals(FormsPortalConstants.STR_NAME)) {
				metadata.setCustomProperty(FormsPortalConstants.STR_NAME, metadata.getName());
			} else {
				metadata.setCustomProperty(cutPoint, "");
			}
			if(cutPoint.equalsIgnoreCase(FormsPortalConstants.STR_SHOW_DOR_CLASS)){
				String rt = instanceMetadataNode.getProperty(FormsPortalConstants.STR_SLING_RESOURCE_TYPE).getString();
				if(!rt.equalsIgnoreCase(FormsPortalConstants.STR_FD_FP_COMP_OPEN_SUBMITTED_GUIDE_XFA)){
					metadata.setCustomProperty(cutPoint, FormsPortalConstants.STR_FP_DISPLAY_NONE);
				}
			}
		}
		
		String instanceNodePath = instanceMetadataNode.getPath();
		String[] instanceNodeSplit = instanceNodePath.split("/");

		// /content/forms/fp//instanceType/metadata/
		// Only encoding username in this case as per current requiremnet.  will be at 4th index (0 based index).
		if(instanceNodeSplit != null){
			instanceNodeSplit[4] = URLEncoder.encode(instanceNodeSplit[4], "UTF-8"); 
		}		
		instanceNodePath = StringUtils.join(instanceNodeSplit, "/");			
		metadata.setPath(instanceNodePath);
	
	}
	
	protected Node getMetadataNodeFromInstanceID(String instanceID, Session session) throws FormsPortalException{
		Node instanceMetadataNode   = null;
		try {
			RepositoryUtils repUtils = RepositoryUtils.getInstance(draftsandSubmissionConfiguration);
	        String userName          = resourceResolverHelper.getResourceResolver().getUserID();
	        Node userNode            = repUtils.getUserNode(userName, false, session);
	        String instanceNodeRelativePath = instanceType + "/" + FormsPortalConstants.STR_METADATA + "/" + instanceID;
	        if(userNode != null && userNode.hasNode(instanceNodeRelativePath)) {
	            instanceMetadataNode   = userNode.getNode(instanceNodeRelativePath);
	        }
		} catch(Exception e){
            throw new FormsPortalException(e);
        }
		return instanceMetadataNode;
	}
	
	protected Node searchInstanceMetadataNode(String instanceID, Session session) throws Exception {
        Map queryMap = new HashMap();
        queryMap.put(FormsPortalConstants.STR_PATH, FormsPortalConstants.STR_CONTENT_FORMS_FP);
        queryMap.put(FormsPortalConstants.STR_TYPE, FormsPortalConstants.STR_NT_UNSTRUCTURED);
        queryMap.put("0_property", idProperty);
        queryMap.put("0_property.value", instanceID);
        queryMap.put("1_property", FormsPortalConstants.STR_NODE_TYPE);
        queryMap.put("1_property.value", nodeType);

        //Creating predicate group from Query Map
        PredicateGroup predicates = PredicateGroup.create(queryMap);
        //Creating query from predicate group
        Query query               = queryBuilder.createQuery(predicates, session);
        //Get result after executing the query
        SearchResult result       = query.getResult ();
        Node instanceMetadataNode   = null;
        if(result.getTotalMatches() == 1){
            Iterator it = result.getNodes();
            it.hasNext();
            instanceMetadataNode = it.next();
        } 
        return instanceMetadataNode;
        
    }
	
	/**
	 * @param node
	 * @throws ValueFormatException
	 * @throws VersionException
	 * @throws LockException
	 * @throws ConstraintViolationException
	 * @throws RepositoryException
	 */
	protected void updateLastModified(Node node) throws ValueFormatException, VersionException, LockException,
    ConstraintViolationException, RepositoryException {
		Calendar lastModified = Calendar.getInstance();
		node.setProperty(FormsPortalConstants.STR_JCR_LAST_MODIFIED, lastModified);
	}

	private String getUserName(Session sysUserSession, String userName) throws FormsPortalException{
		String currentUserName = resourceResolverHelper.getResourceResolver().getUserID();
		if (currentUserName.equals(sysUserSession.getUserID())) {
			currentUserName = userName;
		}
		return currentUserName;
	}
	
	public boolean isOwner(Session currentSession, String submitID) throws FormsPortalException {
	    if(currentSession != null && submitID != null) {
	        return getMetadataNodeFromInstanceID(submitID, currentSession) != null;
	    }
	    return false;
	}

	
	protected JSONArray searchInstances(com.adobe.fd.fp.service.Query query, Session session)  throws FormsPortalException {
		JSONArray jsonArray = new JSONArray();
		if (query != null && query.getStatementGroup() != null) {
			PredicateGroup predicates = transformStatementGroup(query.getStatementGroup());
			Query cqQuery = queryBuilder.createQuery(predicates, session);
			cqQuery.setStart(query.getOffset());
			cqQuery.setHitsPerPage(query.getLimit());
			 //Get result after executing the query
            SearchResult result = cqQuery.getResult ();
            Iterator itr = result.getNodes();
            while(itr.hasNext()) {
            	Node node = itr.next();
            	try {
					jsonArray.put(readInstance(node, query.getCutPoints()).getJSONObject());
				} catch (JSONException e) {
					throw new FormsPortalException(e);
				}
            }
		}
		return jsonArray;
	}
	
	private Predicate transformStatement(Statement statement) {
		Predicate predicate = null;
		if (!StringUtils.isEmpty(statement.getAttributeName()) && !StringUtils.isEmpty(statement.getAttributeValue())) {
			predicate = new Predicate(JcrPropertyPredicateEvaluator.PROPERTY);
			predicate.set(JcrPropertyPredicateEvaluator.PROPERTY, statement.getAttributeName());
			if (statement.getOperator() != Operator.EXISTS) {
				predicate.set(JcrPropertyPredicateEvaluator.VALUE, statement.getAttributeValue());
			}
			predicate.set(JcrPropertyPredicateEvaluator.OPERATION, jcrOperatorMap.get(statement.getOperator()));
		}
		return predicate;
	}
	
	private PredicateGroup transformStatementGroup(StatementGroup statementGroup) {
		PredicateGroup predicates = null;
		if (statementGroup.getStatements() != null) {
			predicates = new PredicateGroup();
			for (Statement statement: statementGroup.getStatements()) {
				Predicate predicate = transformStatement(statement);
				if (predicate != null) {
					predicates.add(predicate);
				}
			}
			if (statementGroup.getJoinOperator() == JoinOperator.OR) {
				predicates.setAllRequired(false);
			}
		}
		
		addDefaultPredicates(predicates);
		
		return predicates;
	}

	private void addDefaultPredicates(PredicateGroup predicates) {
		//Add the path predicate
		Predicate pathPedicate = new Predicate(PathPredicateEvaluator.PATH);
		pathPedicate.set(PathPredicateEvaluator.PATH, FormsPortalConstants.STR_CONTENT_FORMS_FP);
		predicates.add(pathPedicate);
		
		//Add the node type predicate
		Predicate typePredicate = new Predicate(TypePredicateEvaluator.TYPE);
		typePredicate.set(TypePredicateEvaluator.TYPE, FormsPortalConstants.STR_NT_UNSTRUCTURED);
		predicates.add(typePredicate);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy