Powered By Blogger

Monday, November 10, 2014

Alfresco preset

/**
 *
 */
package com.patil.twentyfourseven.web.scripts;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.surf.policy.SurfConfigCleaner;
import org.alfresco.service.cmr.model.FileFolderService;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.search.ResultSet;
import org.alfresco.service.cmr.search.ResultSetRow;
import org.alfresco.service.cmr.search.SearchParameters;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.cmr.site.SiteService;
import org.alfresco.service.namespace.QName;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptRequest;

import com.patil.repo.util.patilUtil;
import com.patil.repo.web.scripts.gsa.patilConstants;


/**
 * @author basanagowda.patil
 *
 */
public class UserDashboardCreation  extends DeclarativeWebScript{

private static final Logger LOGGER = Logger.getLogger(UserDashboardCreation.class);
private static final String SURF_CONFIG = "surf-config";
private static final String PATH_COMPONENTS = "components";
private static final String PATH_PAGES      = "pages";
private static final String PATH_USER       = "user";
 
AuthenticationService authenticationService;
NodeService nodeService;
FileFolderService fileFolderService;
ContentService contentService;
SurfConfigCleaner surfConfigCleaner;
PersonService personService;
SiteService siteService;
PermissionService permissionService;
SearchService searchService;

private final Map model = new HashMap(1);


@Override
protected Map executeImpl(WebScriptRequest req,
Status status, Cache cache) {

boolean error = false ;
String errorCode = StringUtils.EMPTY;

try {
String userid = req.getParameter("userid");
String jobTitle = req.getParameter("jobtitle");
LOGGER.info("Resetting the preset for the jobtitle:: " + jobTitle);
LOGGER.info("Resetting the preset for the user:: " + userid);
String currentUser = AuthenticationUtil.getFullyAuthenticatedUser();
AuthenticationUtil.setRunAsUserSystem();


//get the nodeRef of the folders
final NodeRef componentsNodeRef = getGlobalComponentsNodeRef();
final NodeRef pageUserNodeRef = getGlobalUserFolderNodeRef();

//holders for processing the users
List usersList = new ArrayList();
List successUsersList = new ArrayList();


//if userid is not passed then we need to set the preset based on the jobTitle
if(StringUtils.isBlank(userid)){
LOGGER.debug("Setting the preset for all the users");
usersList = searchUsersByJobTitle(jobTitle);
if(usersList != null && usersList.size() > 0 ){
for(int i = 0  ; i < usersList.size() ; i++){
if( ! setPreset(componentsNodeRef, pageUserNodeRef, (String)this.getNodeService().getProperty(usersList.get(i), ContentModel.PROP_USERNAME), usersList.get(i))){
successUsersList.add(usersList.get(i));
}
}

}
}else{
LOGGER.debug("Setting the preset for the user " + userid);
NodeRef personNodeRef =   this.personService.getPerson(userid);
if(personNodeRef == null ){
error = true ;
errorCode = "Userid is invalid";
}else{

usersList.add(personNodeRef);
//call the preset for the single user
error = setPreset(componentsNodeRef, pageUserNodeRef, userid, personNodeRef);
if(! error){
successUsersList.add(personNodeRef);
}
}


}

//Prepare the message to display
List successUsers = new ArrayList();
for( NodeRef personNodeRef : successUsersList){
successUsers.add(prepareMessage(personNodeRef));
}

List allUsersList = new ArrayList();
for( NodeRef personNodeRef : usersList){
allUsersList.add(prepareMessage(personNodeRef));
}

model.put("successUsers", successUsers);
model.put("allusers", allUsersList);
model.put("summary", "Total Users matching Job Title  " +usersList.size() +"
Preset processed for the users " + successUsersList.size() );


//Now put the userlist and the successUsersList in the model

AuthenticationUtil.setRunAsUser(currentUser);

} catch (Exception e) {
LOGGER.error("Error happened while setting the preset for the user " + e.getMessage());
error = true;
errorCode = "Exception setting the preset";

model.put(patilConstants.RESPONSEMESSAGE,
patilUtil.prepareJsonMessage(patilConstants.CODE, "Exception setting the preset"));

}finally{
//prepare the model
if(StringUtils.EMPTY.equals(errorCode)){
model.put(patilConstants.RESPONSEMESSAGE, "Updated the preset");
}

}
return model;
}




/**
* Prepares the row for the content
* @param personNodeRef
* @return
*/
String prepareMessage(NodeRef personNodeRef){
Map properties =  this.nodeService.getProperties(personNodeRef);
StringBuffer buffer = new StringBuffer();
buffer.append(" ");
buffer.append("");
buffer.append(properties.get(ContentModel.PROP_USERNAME));
buffer.append("
"); buffer.append("");
buffer.append(properties.get(ContentModel.PROP_FIRSTNAME));
buffer.append("
"); buffer.append("");
buffer.append(properties.get(ContentModel.PROP_LASTNAME));
buffer.append("
"); buffer.append("");
buffer.append(properties.get(ContentModel.PROP_JOBTITLE));
buffer.append("
"); buffer.append("
"); return buffer.toString();

}




/**
* Sets the preset for the user configured
* @param componentsNodeRef
* @param pageUserNodeRef
* @param userid
* @param personNodeRef
* @return
*/
boolean setPreset(NodeRef componentsNodeRef, NodeRef pageUserNodeRef, String userid , NodeRef personNodeRef){
boolean error = false ;
try{
String fullWidthDashlet = "page.full-width-dashlet.user~"+userid+"~dashboard.xml";      
String fullWidthtwentyfoursevenDashlet = "page.full-width-twentyfourseven-dashlet.user~"+userid+"~dashboard.xml";      
String title = "page.title.user~"+userid+"~dashboard.xml";
String dashboardName = "dashboard.xml";

if(componentsNodeRef != null  && pageUserNodeRef != null ){
//clear the previous dashboard settings for this user
surfConfigCleaner.beforeDeleteNode(personNodeRef);
//create under components folder
createFile(componentsNodeRef, fullWidthDashlet, getFullWidthDashletContent(userid), userid);
createFile(componentsNodeRef, fullWidthtwentyfoursevenDashlet, getFullWidthTwentyFourSevenDashletContent(userid), userid);
createFile(componentsNodeRef, title, getTitleContent(userid), userid);
//create under page folder
FileInfo folderInfo = this.fileFolderService.create(pageUserNodeRef, userid, ContentModel.TYPE_FOLDER);      
createFile(folderInfo.getNodeRef(), dashboardName, getDashboardContent(userid), userid); //createUserDashboard(userid);

}else{
LOGGER.error("SurfConfig folder is not been created yet, please create one user and login with that user from share and they retry...");
error = true;
}

}catch(Exception e){
LOGGER.error("Exception in setting the preset for the user " + userid +"Error " + e.getMessage());
error = true;
}

return error;
}





private String getFullWidthDashletContent(String userid){
String fullWidthDashletContent = ""
+ "  page.full-width-dashlet.user~"+userid+"~dashboard"
+ "      page      full-width-dashlet"
+ "     user/"+userid+"/dashboard      /components/dashlets/dynamic-welcome"
+ "              user        
";
return fullWidthDashletContent;

}


private String getFullWidthTwentyFourSevenDashletContent(String userid){
String fullWidthtwentyfoursevenDashletContent = ""
+ "      page.full-width-twentyfourseven-dashlet.user~"+userid+"~dashboard"
+ "      page      full-width-twentyfourseven-dashlet"
+ "     user/"+userid+"/dashboard"
+ "      /components/dashlets/departmentsearch"
+ "              user        
";
return fullWidthtwentyfoursevenDashletContent;
}



private String getTitleContent(String userid){
String titleContent = ""
+ "      page.title.user~"+userid+"~dashboard      page"
+ "      title      user/"+userid+"/dashboard"
+ "      /components/title/user-dashboard-title  
"; return titleContent;
}


private String getDashboardContent(String userid){

 String dashboardContent = ""
        + "     User Dashboard"
        + "      page.userDashboard.title"
        + "      Users dashboard page"
        + "      page.userDashboard.description"
        + "      user"
        + "      dashboard-1-column  
";  return dashboardContent;

}


 /**
     * @return NodeRef to the shared components config folder
     */
    protected NodeRef getGlobalComponentsNodeRef()
    {
        NodeRef result = null;      
        NodeRef surfRef = getSurfConfigNodeRef(siteService.getSiteRoot());
        if (surfRef != null)
        {
            result = nodeService.getChildByName(surfRef, ContentModel.ASSOC_CONTAINS, PATH_COMPONENTS);
        }
       
        return result;
    }

    /**
     * @return NodeRef to the shared user config folder
     */
    protected NodeRef getGlobalUserFolderNodeRef()
    {
        NodeRef result = null;      
        NodeRef surfRef = getSurfConfigNodeRef(siteService.getSiteRoot());
        if (surfRef != null)
        {
            NodeRef pagesRef = nodeService.getChildByName(surfRef, ContentModel.ASSOC_CONTAINS, PATH_PAGES);
            if (pagesRef != null)
            {
                result = nodeService.getChildByName(pagesRef, ContentModel.ASSOC_CONTAINS, PATH_USER);
            }
        }
       
        return result;
    }

   
    /**
     * Gets the nodeRef of the surf-config folder
     * @param rootRef
     * @return
     */
    private NodeRef getSurfConfigNodeRef(NodeRef rootRef){
    NodeRef surfConfigRef = this.nodeService.getChildByName(    
    rootRef, ContentModel.ASSOC_CONTAINS, SURF_CONFIG);
   
    return surfConfigRef;
    }
   
 



/**
* Creates the appropriate xml file for showing the dashlet
* @param parentNodeRef
* @param fileName
* @param Content
* @param userid
*/
void createFile(NodeRef parentNodeRef , String fileName , String Content , String userid ){
 FileInfo fileInfo =  fileFolderService.create(parentNodeRef, fileName, ContentModel.TYPE_CONTENT);
       final ContentWriter writer = this.contentService.getWriter(fileInfo.getNodeRef(), ContentModel.PROP_CONTENT, true);
       writer.setMimetype(MimetypeMap.MIMETYPE_XML);
       writer.setEncoding("UTF-8");    
       writer.putContent(Content);
       //give the cordinator role to the content after creation
      permissionService.setPermission(fileInfo.getNodeRef(), userid, PermissionService.COORDINATOR, true);  

}




/**
* Searches the users based on the job title
* @param jobTitle
* @return
*/
List searchUsersByJobTitle(final String jobTitle){
//Search based on jobtitle
SearchParameters sp = new SearchParameters();
sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
sp.setLanguage(SearchService.LANGUAGE_LUCENE);
StringBuffer sb=new StringBuffer("");
sb.append("TYPE:\"cm:person\"");
sb.append(" AND ");
sb.append("@cm\\:jobtitle:\""+jobTitle+"\"");
LOGGER.debug("Query is ::" + sb.toString());
sp.setQuery(sb.toString());
List usersNodeRefList = new ArrayList();

ResultSet results = null;
try {
results = getSearchService().query(sp);
for (ResultSetRow row : results) {
usersNodeRefList.add(row.getNodeRef());
}

}catch(Exception e){
LOGGER.error("Exception happened while searching the users" + e.getMessage());

} finally {
if (results != null) {
results.close();
}
}

return usersNodeRefList;

}



/*void createUserDashboard(String userid){


  final RequestContext rc = ThreadLocalRequestContext.getRequestContext();
WebFrameworkServiceRegistry serviceRegistry = rc.getServiceRegistry();

if (serviceRegistry.getModelObjectService().getPage("user/" + userid + "/dashboard") == null){
// no dashboard found! create initial dashboard for this user...
            Map tokens = new HashMap(2);
            tokens.put("userid", userid);
            serviceRegistry.getPresetsManager().constructPreset("user-dashboard", tokens);  
           
            System.out.println("constructing preset");

}
}
*/

public AuthenticationService getAuthenticationService() {
return authenticationService;
}

public void setAuthenticationService(AuthenticationService authenticationService) {
this.authenticationService = authenticationService;
}

public NodeService getNodeService() {
return nodeService;
}

public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}

public FileFolderService getFileFolderService() {
return fileFolderService;
}

public void setFileFolderService(FileFolderService fileFolderService) {
this.fileFolderService = fileFolderService;
}



public PermissionService getPermissionService() {
return permissionService;
}

public void setPermissionService(PermissionService permissionService) {
this.permissionService = permissionService;
}

public ContentService getContentService() {
return contentService;
}


public void setContentService(ContentService contentService) {
this.contentService = contentService;
}



public SurfConfigCleaner getSurfConfigCleaner() {
return surfConfigCleaner;
}



public void setSurfConfigCleaner(SurfConfigCleaner surfConfigCleaner) {
this.surfConfigCleaner = surfConfigCleaner;
}

public PersonService getPersonService() {
return personService;
}


public void setPersonService(PersonService personService) {
this.personService = personService;
}


public SiteService getSiteService() {
return siteService;
}


public void setSiteService(SiteService siteService) {
this.siteService = siteService;
}

public SearchService getSearchService() {
return searchService;
}





public void setSearchService(SearchService searchService) {
this.searchService = searchService;
}



}