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

com.adobe.fd.fp.util.DataBaseService 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.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Calendar;

import javax.jcr.ItemExistsException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
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.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.jcr.api.SlingRepository;
import org.apache.sling.settings.SlingSettingsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.service.FPKeyGeneratorService;
import com.adobe.granite.resourceresolverhelper.ResourceResolverHelper;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.Replicator;

/**
 * @author sharoon
 * @date 13-Oct-2016
 * @time 4:11:50 pm
 */
@Component
public abstract class DataBaseService {
	
	private final Logger logger = LoggerFactory.getLogger(DataBaseService.class);
	
	@Reference
	protected ResourceResolverHelper resourceResolverHelper;
	
	@Reference
	protected FormsPortalDraftsandSubmissionConfigService draftsandSubmissionConfiguration;
	
	@Reference
	protected  SlingRepository slingRepository;
	
	@Reference
	protected SlingSettingsService slingSettingService;
	
	@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY, policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY)
	protected  FPKeyGeneratorService fpKeyGeneratorService;
	
	@Reference
	protected  Replicator replicator;
	
	@Reference
	protected  PortalUtilsComponent portalUtilsComponent;

	protected String instanceType;
	
	protected String saveDataInternal(byte[] data, String ownerName) throws FormsPortalException {
		String id;
        RepositoryUtils repUtils = RepositoryUtils.getInstance(draftsandSubmissionConfiguration);
        Session sysUserSession = null;
        try {
            sysUserSession = PortalUtils.getFnDServiceUserSession(slingRepository);
            Node userNode = repUtils.getUserNode(getUserName(sysUserSession, ownerName), true, sysUserSession);
            Node submissionFolder = repUtils.getChildNode(userNode, instanceType, FormsPortalConstants.STR_SLING_ORDERED_FOLDER, true);
            Node dataFolder = repUtils.getChildNode(submissionFolder, FormsPortalConstants.STR_DATA, FormsPortalConstants.STR_SLING_ORDERED_FOLDER, true);

            id = fpKeyGeneratorService.getUniqueId();
            Node dataNode = repUtils.getChildNode(dataFolder, id, NodeType.NT_UNSTRUCTURED, true);
            PropertyUtils.setBinaryValue(dataNode, FormsPortalConstants.STR_JCR_DATA, data, sysUserSession.getValueFactory());
            updateLastModified(dataNode);

            sysUserSession.save();
            if(slingSettingService.getRunModes().contains("publish")){
                PortalUtils.reverseReplicate(sysUserSession, dataNode.getPath().toString(), ReplicationActionType.ACTIVATE, replicator, draftsandSubmissionConfiguration.getFormsPortalOutboxes());
            }
            return dataNode.getPath().toString();
        }  catch (FormsPortalException e) {
			throw e;
		} catch (Exception e) {
	        throw new FormsPortalException(e);
        } finally {
            if (sysUserSession != null) {
                sysUserSession.logout();
            }
        }
    }
	
	protected String updateDataInternal (String userDataID, byte[] data) throws FormsPortalException {
		if (StringUtils.isEmpty(userDataID)) {
			throw new FormsPortalException(ErrorMessages.ALC_FMP_001_016);
		}
        boolean isAnonymous = false;
        Session currentSession = null;
        try{  
            currentSession = resourceResolverHelper.getResourceResolverAs(Session.class);
            Node currentInstanceUserdataNode = currentSession.getNode(userDataID);
            PropertyUtils.setBinaryValue(currentInstanceUserdataNode, FormsPortalConstants.STR_JCR_DATA, data, currentSession.getValueFactory());
            updateLastModified(currentInstanceUserdataNode);
            
            currentSession.save();           
            if(slingSettingService.getRunModes().contains("publish")){
                PortalUtils.reverseReplicate(currentSession, currentInstanceUserdataNode.getPath().toString(), ReplicationActionType.ACTIVATE, replicator, draftsandSubmissionConfiguration.getFormsPortalOutboxes());
            }           
            if (isAnonymous) {
            	return "\"" + currentInstanceUserdataNode.getPath() + ".html" + "\"";
            } else {
            	return currentInstanceUserdataNode.getPath().toString();
            }
        
		}  catch (FormsPortalException e) {
			throw e;
		} catch (Exception e) {
			throw new FormsPortalException(e);
		}
	}
	
	protected byte[] getDataInternal(String userDataID) throws FormsPortalException {
		Session sysUserSession = null;
		try {
			sysUserSession = PortalUtils.getFnDServiceUserSession(slingRepository);
			Node dataNode = sysUserSession.getNode(userDataID);
			if (dataNode != null) {
				InputStream is = null;
				if(dataNode.hasProperty(FormsPortalConstants.STR_JCR_DATA)){
					is = dataNode.getProperty(FormsPortalConstants.STR_JCR_DATA).getBinary().getStream();
				}else if(dataNode.hasNode(FormsPortalConstants.STR_JCR_CONTENT)){
					Node jcrDataNode = dataNode.getNode(FormsPortalConstants.STR_JCR_CONTENT);
					is = jcrDataNode.getProperty(FormsPortalConstants.STR_JCR_DATA).getBinary().getStream();
				}else{
					throw new FormsPortalException(ErrorMessages.ALC_FMP_001_021);
				}
				BufferedInputStream bis = new BufferedInputStream(is);
				ByteArrayOutputStream buf = new ByteArrayOutputStream();
				int result = bis.read();
				while (result != -1) {
				    byte b = (byte) result;
				    buf.write(b);
				    result = bis.read();
				}
				return buf.toByteArray();
			}else{
				throw new FormsPortalException(ErrorMessages.ALC_FMP_001_021);
			}
		}  catch (FormsPortalException e) {
			throw e;
		} catch (Exception e) {
			throw new FormsPortalException(e);
		} finally {
			sysUserSession.logout();
		}
	}
	
	protected boolean deleteDataInternal(String userDataID) throws FormsPortalException {
		boolean status = false;
		boolean isAnonymous    = portalUtilsComponent.isLoginAnonymous();
		Session currentSession = resourceResolverHelper.getResourceResolverAs(Session.class);
		String userName = resourceResolverHelper.getResourceResolver().getUserID();
		Session sysUserSession = null;
		if(StringUtils.isEmpty(userDataID)){
			throw new FormsPortalException(ErrorMessages.ALC_FMP_001_016);
		}
        try{
            sysUserSession   = PortalUtils.getFnDServiceUserSession(slingRepository);
            //CQ-107306: make currentSession as service session if user is anonymous and trying to delete anonymous userDataID
            if(isAnonymous &&  userDataID.startsWith(FormsPortalConstants.STR_CONTENT_FORMS_FP + "/" + userName)) {
                currentSession = sysUserSession;
            }
            RepositoryUtils repUtils = RepositoryUtils.getInstance(draftsandSubmissionConfiguration);
            Node userNode = repUtils.getUserNode(userName, false, currentSession);
            if(((sysUserSession.getUserID().equals(userName)) ||userNode!= null) && currentSession.nodeExists(userDataID)){
                if(slingSettingService.getRunModes().contains("publish")){
                    PortalUtils.reverseReplicate(sysUserSession, userDataID, ReplicationActionType.DELETE, replicator, draftsandSubmissionConfiguration.getFormsPortalOutboxes());
                } else {
                    PortalUtils.replicate(sysUserSession, userDataID, ReplicationActionType.DELETE, replicator);
                }
                // Local node is always deleted immediately, because delete as a result of replication may take some time
                currentSession.getNode(userDataID).remove();
                currentSession.save();
                status = true;
            } else{
                throw new FormsPortalException(ErrorMessages.ALC_FMP_001_013);
            }
        } catch (FormsPortalException e) {
            throw e;
        } catch (Exception e) {
            throw new FormsPortalException(e);
        } finally {
            if(sysUserSession != null){
                sysUserSession.logout();
            }
        }
        return status;	
    }

	protected String saveAttachmentInternal(byte[] attachmentBytes, String ownerName) throws FormsPortalException {
		RepositoryUtils repUtils = RepositoryUtils.getInstance(draftsandSubmissionConfiguration);
        Session sysUserSession = null;
        try{  
            sysUserSession = PortalUtils.getFnDServiceUserSession(slingRepository);
            Node userNode = null;
   			userNode = repUtils.getUserNode(getUserName(sysUserSession, ownerName), true, sysUserSession);
            //create a new folder for attachments under current userdata node folder
			Node submitFolder = repUtils.getChildNode(userNode, instanceType, FormsPortalConstants.STR_SLING_ORDERED_FOLDER, true);
			Node attachmentRootFolder = repUtils.getChildNode(submitFolder, FormsPortalConstants.STR_ATTACHMENTS, FormsPortalConstants.STR_SLING_ORDERED_FOLDER, true);
			String currentAttachmentNodeName = fpKeyGeneratorService.getUniqueId();
			Node currentAttachmentNode = attachmentRootFolder.addNode(currentAttachmentNodeName, NodeType.NT_UNSTRUCTURED);
			PropertyUtils.setBinaryValue(currentAttachmentNode, FormsPortalConstants.STR_JCR_DATA, attachmentBytes , sysUserSession.getValueFactory());
			String attachmentNodePath = currentAttachmentNode.getPath().toString();
                 	      
            sysUserSession.save();            
            if(slingSettingService.getRunModes().contains("publish")){
                PortalUtils.reverseReplicate(sysUserSession, currentAttachmentNode.getPath().toString(), ReplicationActionType.ACTIVATE, replicator, draftsandSubmissionConfiguration.getFormsPortalOutboxes());
            }
            
            return attachmentNodePath;
		}  catch (FormsPortalException e) {
			throw e;
		} catch (Exception e) {
			throw new FormsPortalException(e);
		}
        finally {
            if (sysUserSession != null) {
                sysUserSession.logout();
            }
        }
	}
	
	public boolean deleteAttachment(String attachmentID) throws FormsPortalException {
		return deleteDataInternal(attachmentID);
    }
	
	public byte[] getAttachment(String attachmentID) throws FormsPortalException {
        return getDataInternal(attachmentID);
	}
	
	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;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy