gt: 		PermissionAPI perAPI = APILocator.getPermissionAPI();
context: package com.dotmarketing.portlets.contentlet.ajax;
  
  import static com.dotmarketing.business.PermissionAPI.PERMISSION_PUBLISH;
  import static com.dotmarketing.business.PermissionAPI.PERMISSION_READ;
  import static com.dotmarketing.business.PermissionAPI.PERMISSION_WRITE;
  
  import java.io.File;
  import java.io.IOException;
  import java.util.ArrayList;
  import java.util.Date;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.List;
  import java.util.Map;
  import java.util.Map.Entry;
  import java.util.Set;
  
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpSession;
  
  import com.dotcms.repackage.org.directwebremoting.WebContextFactory;
  import com.dotcms.content.elasticsearch.util.ESUtils;
  import com.dotcms.enterprise.FormAJAXProxy;
  import com.dotmarketing.beans.Host;
  import com.dotmarketing.beans.Identifier;
  import com.dotmarketing.beans.Permission;
  import com.dotmarketing.business.APILocator;
  import com.dotmarketing.business.CacheLocator;
  import com.dotmarketing.business.DotCacheException;
  import com.dotmarketing.business.DotStateException;
  import com.dotmarketing.business.PermissionAPI;
  import com.dotmarketing.business.PublishStateException;
  import com.dotmarketing.business.web.WebAPILocator;
  import com.dotmarketing.cache.FieldsCache;
  import com.dotmarketing.cache.StructureCache;
  import com.dotmarketing.db.HibernateUtil;
  import com.dotmarketing.exception.DotDataException;
  import com.dotmarketing.exception.DotHibernateException;
  import com.dotmarketing.exception.DotLanguageException;
  import com.dotmarketing.exception.DotRuntimeException;
  import com.dotmarketing.exception.DotSecurityException;
  import com.dotmarketing.portlets.categories.business.CategoryAPI;
  import com.dotmarketing.portlets.categories.model.Category;
  import com.dotmarketing.portlets.contentlet.business.ContentletAPI;
  import com.dotmarketing.portlets.contentlet.business.DotContentletStateException;
  import com.dotmarketing.portlets.contentlet.business.DotContentletValidationException;
  import com.dotmarketing.portlets.contentlet.business.DotLockException;
  import com.dotmarketing.portlets.contentlet.business.web.ContentletWebAPI;
  import com.dotmarketing.portlets.contentlet.model.Contentlet;
  import com.dotmarketing.portlets.contentlet.util.ContentletUtil;
  import com.dotmarketing.portlets.fileassets.business.FileAssetAPI;
  import com.dotmarketing.portlets.fileassets.business.FileAssetValidationException;
  import com.dotmarketing.portlets.form.business.FormAPI;
  import com.dotmarketing.portlets.hostadmin.business.CopyHostContentUtil;
  import com.dotmarketing.portlets.htmlpageasset.model.HTMLPageAsset;
  import com.dotmarketing.portlets.languagesmanager.business.LanguageAPI;
  import com.dotmarketing.portlets.languagesmanager.model.Language;
  import com.dotmarketing.portlets.languagesmanager.model.LanguageKey;
  import com.dotmarketing.portlets.structure.StructureUtil;
  import com.dotmarketing.portlets.structure.factories.FieldFactory;
  import com.dotmarketing.portlets.structure.factories.RelationshipFactory;
  import com.dotmarketing.portlets.structure.model.Field;
  import com.dotmarketing.portlets.structure.model.Field.FieldType;
  import com.dotmarketing.portlets.structure.model.Relationship;
  import com.dotmarketing.portlets.structure.model.Structure;
  import com.dotmarketing.portlets.workflows.actionlet.PushPublishActionlet;
  import com.dotmarketing.portlets.workflows.model.WorkflowAction;
  import com.dotmarketing.portlets.workflows.model.WorkflowActionClass;
  import com.dotmarketing.portlets.workflows.model.WorkflowScheme;
  import com.dotmarketing.util.Config;
  import com.dotmarketing.util.DateUtil;
  import com.dotmarketing.util.InodeUtils;
  import com.dotmarketing.util.Logger;
  import com.dotmarketing.util.PaginatedArrayList;
  import com.dotmarketing.util.RegEX;
  import com.dotmarketing.util.RegExMatch;
  import com.dotmarketing.util.UUIDGenerator;
  import com.dotmarketing.util.UtilHTML;
  import com.dotmarketing.util.UtilMethods;
  import com.dotmarketing.util.VelocityUtil;
  import com.dotmarketing.util.WebKeys;
  import com.dotmarketing.util.json.JSONArray;
  import com.dotmarketing.util.json.JSONException;
  import com.dotmarketing.util.json.JSONObject;
  import com.liferay.portal.PortalException;
  import com.liferay.portal.SystemException;
  import com.liferay.portal.language.LanguageException;
  import com.liferay.portal.language.LanguageUtil;
  import com.liferay.portal.model.User;
  import com.liferay.util.FileUtil;
  import com.liferay.util.servlet.SessionMessages;
  
  /**
   * @author David
   */
  public class ContentletAjax {
  
  	private java.text.DateFormat modDateFormat = java.text.DateFormat.getDateTimeInstance(java.text.DateFormat.SHORT,
  			java.text.DateFormat.SHORT);
  
  	private ContentletAPI conAPI = APILocator.getContentletAPI();
  	private ContentletWebAPI contentletWebAPI = WebAPILocator.getContentletWebAPI();
  	private LanguageAPI langAPI = APILocator.getLanguageAPI();
  	private FormAPI formAPI = APILocator.getFormAPI();
  
  	public List<Map<String, Object>> getContentletsData(String inodesStr) {
  		List<Map<String,Object>> rows = new ArrayList<Map<String, Object>>();
  
  		if(inodesStr == null || !UtilMethods.isSet(inodesStr)) {
  			return rows;
  		}
  
  		String[] inodes =  inodesStr.split(",");
  		for (String inode : inodes) {
  			Map<String, Object> contenletData = getContentletData(inode);
  			if(contenletData != null)
  				rows.add(contenletData);
  		}
  
  		return rows;
  	}
  
  	public Map<String, Object> getContentletData(String inode) {
  
  		Map<String,Object> result = new HashMap<String, Object>();
  
  		try {
  
  			HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();
  			User currentUser = com.liferay.portal.util.PortalUtil.getUser(req);
  			Contentlet contentlet = null;
  
  			try{// This is to avoid non-inode strings from throwing exception
  				contentlet = conAPI.find(inode, currentUser, true);
  			}catch(Exception e){
  				Logger.debug(this, e.getMessage());
  			}
  			if(contentlet == null || !UtilMethods.isSet(contentlet.getInode()))
  				return null;
  
  			Structure targetStructure = contentlet.getStructure();
  			List<Field> targetFields = FieldsCache.getFieldsByStructureInode(targetStructure.getInode());
  
  			String identifier = String.valueOf(contentlet.getIdentifier());
  
  			boolean hasListedFields = false;
  
  			for (Field f : targetFields) {
  
  				if (f.isIndexed() || f.isListed()) {
  					hasListedFields = true;
  					String fieldName = f.getFieldName();
  					Object fieldValueObj = "";
  					try{
  						fieldValueObj = conAPI.getFieldValue(contentlet, f);
  					}catch (Exception e) {
  						Logger.error(ContentletAjax.class, "Unable to get value for field", e);
  					}
  					String fieldValue = "";
  					if (fieldValueObj instanceof java.util.Date) {
  						if (fieldValueObj != null)
  							fieldValue = modDateFormat.format(fieldValueObj);
  					} else if (fieldValueObj instanceof java.sql.Timestamp) {
  						if (fieldValueObj != null) {
  							java.util.Date fieldDate = new java.util.Date(((java.sql.Timestamp) fieldValueObj).getTime());
  							fieldValue = modDateFormat.format(fieldDate);
  						}
  					} else {
  						if (fieldValueObj != null)
  							fieldValue = fieldValueObj.toString();
  					}
  					result.put(fieldName, fieldValue);
  				}
  			}
  			if( !hasListedFields ) {
  				result.put("identifier", identifier);
  			}
  
  			result.put("inode", String.valueOf(contentlet.getInode()));
  			result.put("working", String.valueOf(contentlet.isWorking()));
  			result.put("live", String.valueOf(contentlet.isLive()));
  			result.put("deleted", String.valueOf(contentlet.isArchived()));
  			result.put("locked", String.valueOf(contentlet.isLocked()));
  			result.put("id", identifier); // Duplicates value for identifier key in map so that UI does not get broken
  			Language language = langAPI.getLanguage(contentlet.getLanguageId());
  			String languageCode = langAPI.getLanguageCodeAndCountry(contentlet.getLanguageId(),null);
  			String languageName =  language.getLanguage();
  			result.put("langCode", languageCode);
  			result.put("langName", languageName);
  			result.put("langId", language.getId()+"");
  			result.put("hasListedFields", Boolean.toString(hasListedFields) );
  			result.put("siblings", getContentSiblingsData(inode));
  
  		} catch (DotDataException e) {
  			Logger.error(this, "Error trying to obtain the contentlets from the relationship.", e);
  		} catch (PortalException e) {
  			Logger.error(this, "Portal exception.", e);
  		} catch (SystemException e) {
  			Logger.error(this, "System exception.", e);
  		} catch (DotSecurityException e) {
  			Logger.error(this, "Security exception.", e);
  		}
  
  		return result;
  	}
  
  	private List<Map<String, String>> getContentSiblingsData(String inode) {//GIT-1057
  
  		List<Map<String, String>> result = new ArrayList<Map<String, String>>();
  
  		try {
  
  			HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();
  			User currentUser = com.liferay.portal.util.PortalUtil.getUser(req);
  
  			Contentlet firstContentlet = conAPI.find(inode, currentUser, true);
  
  			List<Map<String,String>> contentletList = new ArrayList<Map<String,String>>();
  
  			LanguageAPI langAPI = APILocator.getLanguageAPI();
  			ContentletAPI contentletAPI = APILocator.getContentletAPI();
  			List<Language> langs = langAPI.getLanguages();
  			Contentlet languageContentlet = null;
  
  			String identifier = String.valueOf(firstContentlet.getIdentifier());
  
  			Structure targetStructure = firstContentlet.getStructure();
  			List<Field> targetFields = FieldsCache.getFieldsByStructureInode(targetStructure.getInode());
  
  			boolean parent = false;
  			try{
  		        parent = firstContentlet.getBoolProperty("dotCMSParentOnTree") ;
  		    }
  		    catch(Exception e){
  
  		    }
  
  			for(Language lang : langs){
  
  				Map<String, String> contentDetails = new HashMap<String, String>();
  				try{
  					languageContentlet = null;
  					languageContentlet = contentletAPI.findContentletByIdentifier(firstContentlet.getIdentifier(), true, lang.getId(), currentUser, false);
  				}catch (Exception e) {
  					try{
  					languageContentlet = contentletAPI.findContentletByIdentifier(firstContentlet.getIdentifier(), false, lang.getId(), currentUser, false);
  					}catch (Exception e1) {	}
  				}
  
  				boolean hasListedFields = false;
  
  				if((languageContentlet == null) || (!UtilMethods.isSet(languageContentlet.getInode()))){
  
  					contentDetails.put( "langCode" , langAPI.getLanguageCodeAndCountry(lang.getId(),null));
  					contentDetails.put("langName", lang.getLanguage());
  					contentDetails.put("langId", lang.getId()+"");
  			    	contentDetails.put("inode", "");
  					contentDetails.put("parent", parent+"");
  					contentDetails.put("working", "false");
  					contentDetails.put("live", "false");
  					contentDetails.put("deleted", "true");
  					contentDetails.put("locked", "false");
  					contentDetails.put("siblingInode", firstContentlet.getInode());
  
  					for (Field f : targetFields) {
  						if (f.isIndexed() || f.isListed()) {
  							hasListedFields = true;
  							String fieldName = f.getFieldName();
  							String fieldValue = "";
  							contentDetails.put(fieldName, fieldValue);
  						}
  					}
  					if( !hasListedFields ) {
  						contentDetails.put("identifier", identifier);
  					}
  
  
  				}else{
  
  					contentDetails.put( "langCode" , langAPI.getLanguageCodeAndCountry(lang.getId(),null));
  					contentDetails.put("langName", lang.getLanguage());
  					contentDetails.put("langId", lang.getId()+"");
  			    	contentDetails.put("inode", languageContentlet.getInode());
  					contentDetails.put("parent", parent+"");
  					contentDetails.put("working", languageContentlet.isWorking()+"");
  					contentDetails.put("live", languageContentlet.isLive()+"");
  					contentDetails.put("deleted", languageContentlet.isArchived()+"");
  					contentDetails.put("locked", languageContentlet.isLocked()+"");
  					contentDetails.put("siblingInode", firstContentlet.getInode());
  
  					for (Field f : targetFields) {
  						if (f.isIndexed() || f.isListed()) {
  							hasListedFields = true;
  							String fieldName = f.getFieldName();
  							Object fieldValueObj = "";
  							try{
  								fieldValueObj = conAPI.getFieldValue(languageContentlet, f);
  							}catch (Exception e) {
  								Logger.error(ContentletAjax.class, "Unable to get value for field", e);
  							}
  							String fieldValue = "";
  							if (fieldValueObj instanceof java.util.Date) {
  								if (fieldValueObj != null)
  									fieldValue = modDateFormat.format(fieldValueObj);
  							} else if (fieldValueObj instanceof java.sql.Timestamp) {
  								if (fieldValueObj != null) {
  									java.util.Date fieldDate = new java.util.Date(((java.sql.Timestamp) fieldValueObj).getTime());
  									fieldValue = modDateFormat.format(fieldDate);
  								}
  							} else {
  								if (fieldValueObj != null)
  									fieldValue = fieldValueObj.toString();
  							}
  							contentDetails.put(fieldName, fieldValue);
  						}
  					}
  					if( !hasListedFields ) {
  						contentDetails.put("identifier", identifier);
  					}
  				}
  				contentletList.add(contentDetails);
  			}
  
  			result = contentletList;
  
  
  
  		} catch (DotDataException e) {
  			Logger.error(this, "Error trying to obtain the contentlets from the relationship.", e);
  		} catch (PortalException e) {
  			Logger.error(this, "Portal exception.", e);
  		} catch (SystemException e) {
  			Logger.error(this, "System exception.", e);
  		} catch (DotSecurityException e) {
  			Logger.error(this, "Security exception.", e);
  		}
  
  		return result;
  	}
  
  
  	/**
  	 * This method is used by the backend to pull the content from the lucene
  	 * index and also checks the user permissions to see the content
  	 *
  	 * @param structureInode
  	 *            Inode of the structure content to be listed
  	 * @param fields
  	 *            Fields to filters, where the position i (where i is odd)
  	 *            represent the field name and the position i + 1 represent the
  	 *            field value to filter
  	 * @param categories
  	 *            The categories inodes to filter
  	 * @param showDeleted
  	 *            If true show the deleted elements only
  	 * @param filterSystemHost
  	 *            If true filter elements of system host
  	 * @param page
  	 *            The page number to show (starting with 1)
  	 *            If page is 0, this will return all possible contentlets
  	 * @param perPage
  	 * @param orderBy
  	 *            The field name to be used to sort the content
  	 * @return The list of contents that match the parameters at the position 0
  	 *         the result included a hashmap with some useful information like
  	 *         the total number of results, ...
  	 * @throws DotSecurityException
  	 * @throws DotDataException
  	 * @throws DotStateException
  	 */
  	public List searchContentlet(String structureInode, List<String> fields, List<String> categories, boolean showDeleted, boolean filterSystemHost, int page, int perPage, String orderBy) throws DotStateException, DotDataException, DotSecurityException {
  
  		PermissionAPI perAPI = APILocator.getPermissionAPI();
  		HttpSession sess = WebContextFactory.get().getSession();
  		HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();
  
  		// User info
  		User currentUser = null;
  		String userId = "";
  		try {
  			currentUser = com.liferay.portal.util.PortalUtil.getUser(req);
  			userId = currentUser.getUserId();
  		} catch (Exception e) {
  			Logger.error(this, "Error trying to obtain the current liferay user from the request.", e);
  		}
  
  		return searchContentletsByUser(structureInode, fields, categories, showDeleted, filterSystemHost, false, false, page, orderBy, perPage, currentUser, sess, null, null);
  	}
  
  	public List searchContentlets(String structureInode, List<String> fields, List<String> categories, boolean showDeleted, boolean filterSystemHost, int page, String orderBy, String modDateFrom, String modDateTo) throws DotStateException, DotDataException, DotSecurityException {
  	    return searchContentlets(structureInode, fields, categories, showDeleted, filterSystemHost, page, orderBy, modDateFrom, modDateTo, true);
  	}
  
  	public List searchContentlets(String structureInode, List<String> fields, List<String> categories, boolean showDeleted, boolean filterSystemHost, int page, String orderBy, String modDateFrom, String modDateTo, boolean saveLastSearch) throws DotStateException, DotDataException, DotSecurityException {
  	    HttpSession sess = null;
          if(saveLastSearch)
              sess = WebContextFactory.get().getSession();
  		HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();
  
  		// User info
  		User currentUser = null;
  		String userId = "";
  		try {
  			currentUser = com.liferay.portal.util.PortalUtil.getUser(req);
  			userId = currentUser.getUserId();
  		} catch (Exception e) {
  			Logger.error(this, "Error trying to obtain the current liferay user from the request.", e);
  		}
  
  		return searchContentletsByUser(structureInode, fields, categories, showDeleted, filterSystemHost, false, false, page, orderBy, 0,currentUser, sess, modDateFrom, modDateTo);
  	}
  
  	public List searchContentlets(String structureInode, List<String> fields, List<String> categories, boolean showDeleted,
  	        boolean filterSystemHost,  boolean filterUnpublish, boolean filterLocked, int page, String orderBy, String modDateFrom,
  	        String modDateTo) throws DotStateException, DotDataException, DotSecurityException {
  	    return searchContentlets(structureInode,fields,categories,showDeleted,filterSystemHost,filterUnpublish,filterLocked,page,0,orderBy,modDateFrom,modDateTo);
  	}
  
  	public List searchContentlets(String structureInode, List<String> fields, List<String> categories, boolean showDeleted,
  	        boolean filterSystemHost,  boolean filterUnpublish, boolean filterLocked, int page, int perPage,String orderBy, String modDateFrom,
  	        String modDateTo) throws DotStateException, DotDataException, DotSecurityException {
  
  