import org.springframework.extensions.surf.util.Base64;
It is the encoding used
Monday, January 31, 2011
LoginController present in package
org.springframework.extensions.surf.mvc
is the entry point for setting the user related data.
Using this we can do anything.
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception
{
request.setCharacterEncoding("UTF-8");
String username = (String) request.getParameter("username");
String password = (String) request.getParameter("password");
String successPage = (String) request.getParameter("success");
String failurePage = (String) request.getParameter("failure");
boolean success = false;
try
{
// check whether there is already a user logged in
HttpSession session = request.getSession(false);
if (session != null)
{
// destroy old session and log out the current user
AuthenticationUtil.logout(request, response);
}
UserFactory userFactory = FrameworkUtil.getServiceRegistry().getUserFactory();
// see if we can authenticate the user
boolean authenticated = userFactory.authenticate(request, username, password);
if (authenticated)
{
// this will fully reset all connector sessions
RequestContext context = FrameworkUtil.getCurrentRequestContext();
AuthenticationUtil.login(request, response, username, false);
// mark the fact that we succeeded
success = true;
}
}
catch (Throwable err)
{
throw new ServletException(err);
}
// If they succeeded in logging in, redirect to the success page
// Otherwise, redirect to the failure page
if (success)
{
if (successPage != null)
{
response.sendRedirect(successPage);
}
else
{
response.sendRedirect(request.getContextPath());
}
}
else
{
// inval
_______________________________________
AuthenticationUtil in the org.springframework.extensions.surf.site has the code for handling the user and cookies, which will be used for the future calls
org.springframework.extensions.surf.mvc
is the entry point for setting the user related data.
Using this we can do anything.
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception
{
request.setCharacterEncoding("UTF-8");
String username = (String) request.getParameter("username");
String password = (String) request.getParameter("password");
String successPage = (String) request.getParameter("success");
String failurePage = (String) request.getParameter("failure");
boolean success = false;
try
{
// check whether there is already a user logged in
HttpSession session = request.getSession(false);
if (session != null)
{
// destroy old session and log out the current user
AuthenticationUtil.logout(request, response);
}
UserFactory userFactory = FrameworkUtil.getServiceRegistry().getUserFactory();
// see if we can authenticate the user
boolean authenticated = userFactory.authenticate(request, username, password);
if (authenticated)
{
// this will fully reset all connector sessions
RequestContext context = FrameworkUtil.getCurrentRequestContext();
AuthenticationUtil.login(request, response, username, false);
// mark the fact that we succeeded
success = true;
}
}
catch (Throwable err)
{
throw new ServletException(err);
}
// If they succeeded in logging in, redirect to the success page
// Otherwise, redirect to the failure page
if (success)
{
if (successPage != null)
{
response.sendRedirect(successPage);
}
else
{
response.sendRedirect(request.getContextPath());
}
}
else
{
// inval
_______________________________________
AuthenticationUtil in the org.springframework.extensions.surf.site has the code for handling the user and cookies, which will be used for the future calls
Initializing share framework
AlfrescoUserFactory present in org.springframework.extensions.surf.support
is responsible for giving all the data related to Alfresco user in share.
LoginController tells about how to authenticate the user and initialize the framework
is responsible for giving all the data related to Alfresco user in share.
LoginController tells about how to authenticate the user and initialize the framework
Thursday, January 27, 2011
Storing the complex type in the content model
In the alfresco content model property you can store List, HashMap,Set etc
For this do the below
In your model define the property
d:any
To store the value use the below code
//storing all the selected regions
final HashMap regionMap = new HashMap();
for(String region : selectedRegions){
regionMap.put(region, region);
}
_map.put(PowerGridContentModel.PROP_REGIONS, (Serializable)regionMap);
To retrieve use the below code, I am considering example of getting property from executionContext
HashMap regionsMap = (HashMap) executionContext.getContextInstance().getVariables().get("pcm_regions");
if(regionsMap != null){
for (Map.Entry pair : regionsMap.entrySet()) {
System.out.println("Region name::"+pair.getKey() + " = " + pair.getValue());
}
Hope it helps.
For this do the below
In your model define the property
To store the value use the below code
//storing all the selected regions
final HashMap
for(String region : selectedRegions){
regionMap.put(region, region);
}
_map.put(PowerGridContentModel.PROP_REGIONS, (Serializable)regionMap);
To retrieve use the below code, I am considering example of getting property from executionContext
HashMap
if(regionsMap != null){
for (Map.Entry
System.out.println("Region name::"+pair.getKey() + " = " + pair.getValue());
}
Hope it helps.
Run Action
Refer to classes
ScriptActionExecuter class finishImpl() to find the code to
execute the script.
refer to the ActionExecuter class implemented classes to find out the implementation of each method.
ScriptActionExecuter class finishImpl() to find the code to
execute the script.
refer to the ActionExecuter class implemented classes to find out the implementation of each method.
Code for creating the links in alfresco
/**
* It links the source noderef to the destination noderef.
* Code needs to be tested
* Refer to WorkspaceClipboardItem.
* @param sourceNodeRef the noderef which is to be linked
* @param destNodeRef where the new link to be put
*/
private void establishLinkages(NodeRef sourceNodeRef , NodeRef destNodeRef){
boolean operationComplete = false;
// TODO: Should we be using primary parent here?
// We are assuming that the item exists in only a single parent and that the source for
// the clipboard operation (e.g. the source folder) is specifically that parent node.
// So does not allow for more than one possible parent node - or for linked objects!
// This code should be refactored to use a parent ID when appropriate.
// ChildAssociationRef assocRef = nodeService.getPrimaryParent(getNodeRef());
ChildAssociationRef assocRef = this.getServiceRegistry().getNodeService().getPrimaryParent(sourceNodeRef);
String name = getName(sourceNodeRef);
String linkTo ="Link to";
name = linkTo + ' ' + name;
//Now perform linking
// LINK operation
LOGGER.debug("Attempting to link node ID: " + sourceNodeRef + " into node: " + destNodeRef.toString());
// we create a special Link Object node that has a property to reference the original
// create the node using the nodeService (can only use FileFolderService for content)
String LINK_NODE_EXTENSION = ".url";
if (checkExists(name + LINK_NODE_EXTENSION, destNodeRef) == false)
{
Map props = new HashMap(2, 1.0f);
String newName = name + LINK_NODE_EXTENSION;
props.put(ContentModel.PROP_NAME, newName);
props.put(ContentModel.PROP_LINK_DESTINATION, sourceNodeRef);
DictionaryService dd = getServiceRegistry().getDictionaryService();
if (dd.isSubClass(getType(sourceNodeRef), ContentModel.TYPE_CONTENT))
{
// create File Link node
ChildAssociationRef childRef = this.getServiceRegistry().getNodeService().createNode(
destNodeRef,
ContentModel.ASSOC_CONTAINS,
QName.createQName(assocRef.getQName().getNamespaceURI(), newName),
ApplicationModel.TYPE_FILELINK,
props);
// apply the titled aspect - title and description
Map titledProps = new HashMap(2, 1.0f);
titledProps.put(ContentModel.PROP_TITLE, name);
titledProps.put(ContentModel.PROP_DESCRIPTION, name);
this.getServiceRegistry().getNodeService().addAspect(childRef.getChildRef(), ContentModel.ASPECT_TITLED, titledProps);
}
else
{
// create Folder link node
ChildAssociationRef childRef = this.getServiceRegistry().getNodeService().createNode(
destNodeRef,
ContentModel.ASSOC_CONTAINS,
assocRef.getQName(),
ApplicationModel.TYPE_FOLDERLINK,
props);
// apply the uifacets aspect - icon, title and description props
Map uiFacetsProps = new HashMap(4, 1.0f);
uiFacetsProps.put(ApplicationModel.PROP_ICON, "space-icon-link");
uiFacetsProps.put(ContentModel.PROP_TITLE, name);
uiFacetsProps.put(ContentModel.PROP_DESCRIPTION, name);
this.getServiceRegistry().getNodeService().addAspect(childRef.getChildRef(), ApplicationModel.ASPECT_UIFACETS, uiFacetsProps);
}
// if we get here without an exception, the clipboard link operation was successful
operationComplete = true;
}
LOGGER.debug("Is Linkage operation complete????"+ operationComplete);
}
public String getName(NodeRef sourceNodeRef)
{
String name = (String)getServiceRegistry().getNodeService().getProperty(
sourceNodeRef, ContentModel.PROP_NAME);
return name;
}
protected boolean checkExists(String name, NodeRef parent)
{
/** Shallow search for nodes with a name pattern */
String XPATH_QUERY_NODE_MATCH = "./*[like(@cm:name, $cm:name, false)]";
QueryParameterDefinition[] params = new QueryParameterDefinition[1];
params[0] = new QueryParameterDefImpl(
ContentModel.PROP_NAME,
getServiceRegistry().getDictionaryService().getDataType(
DataTypeDefinition.TEXT),
true,
name);
// execute the query
List nodeRefs = getServiceRegistry().getSearchService().selectNodes(
parent,
XPATH_QUERY_NODE_MATCH,
params,
getServiceRegistry().getNamespaceService(),
false);
return (nodeRefs.size() != 0);
}
public QName getType(NodeRef nodeRef)
{
QName type = getServiceRegistry().getNodeService().getType(nodeRef);
return type;
}
* It links the source noderef to the destination noderef.
* Code needs to be tested
* Refer to WorkspaceClipboardItem.
* @param sourceNodeRef the noderef which is to be linked
* @param destNodeRef where the new link to be put
*/
private void establishLinkages(NodeRef sourceNodeRef , NodeRef destNodeRef){
boolean operationComplete = false;
// TODO: Should we be using primary parent here?
// We are assuming that the item exists in only a single parent and that the source for
// the clipboard operation (e.g. the source folder) is specifically that parent node.
// So does not allow for more than one possible parent node - or for linked objects!
// This code should be refactored to use a parent ID when appropriate.
// ChildAssociationRef assocRef = nodeService.getPrimaryParent(getNodeRef());
ChildAssociationRef assocRef = this.getServiceRegistry().getNodeService().getPrimaryParent(sourceNodeRef);
String name = getName(sourceNodeRef);
String linkTo ="Link to";
name = linkTo + ' ' + name;
//Now perform linking
// LINK operation
LOGGER.debug("Attempting to link node ID: " + sourceNodeRef + " into node: " + destNodeRef.toString());
// we create a special Link Object node that has a property to reference the original
// create the node using the nodeService (can only use FileFolderService for content)
String LINK_NODE_EXTENSION = ".url";
if (checkExists(name + LINK_NODE_EXTENSION, destNodeRef) == false)
{
Map
String newName = name + LINK_NODE_EXTENSION;
props.put(ContentModel.PROP_NAME, newName);
props.put(ContentModel.PROP_LINK_DESTINATION, sourceNodeRef);
DictionaryService dd = getServiceRegistry().getDictionaryService();
if (dd.isSubClass(getType(sourceNodeRef), ContentModel.TYPE_CONTENT))
{
// create File Link node
ChildAssociationRef childRef = this.getServiceRegistry().getNodeService().createNode(
destNodeRef,
ContentModel.ASSOC_CONTAINS,
QName.createQName(assocRef.getQName().getNamespaceURI(), newName),
ApplicationModel.TYPE_FILELINK,
props);
// apply the titled aspect - title and description
Map
titledProps.put(ContentModel.PROP_TITLE, name);
titledProps.put(ContentModel.PROP_DESCRIPTION, name);
this.getServiceRegistry().getNodeService().addAspect(childRef.getChildRef(), ContentModel.ASPECT_TITLED, titledProps);
}
else
{
// create Folder link node
ChildAssociationRef childRef = this.getServiceRegistry().getNodeService().createNode(
destNodeRef,
ContentModel.ASSOC_CONTAINS,
assocRef.getQName(),
ApplicationModel.TYPE_FOLDERLINK,
props);
// apply the uifacets aspect - icon, title and description props
Map
uiFacetsProps.put(ApplicationModel.PROP_ICON, "space-icon-link");
uiFacetsProps.put(ContentModel.PROP_TITLE, name);
uiFacetsProps.put(ContentModel.PROP_DESCRIPTION, name);
this.getServiceRegistry().getNodeService().addAspect(childRef.getChildRef(), ApplicationModel.ASPECT_UIFACETS, uiFacetsProps);
}
// if we get here without an exception, the clipboard link operation was successful
operationComplete = true;
}
LOGGER.debug("Is Linkage operation complete????"+ operationComplete);
}
public String getName(NodeRef sourceNodeRef)
{
String name = (String)getServiceRegistry().getNodeService().getProperty(
sourceNodeRef, ContentModel.PROP_NAME);
return name;
}
protected boolean checkExists(String name, NodeRef parent)
{
/** Shallow search for nodes with a name pattern */
String XPATH_QUERY_NODE_MATCH = "./*[like(@cm:name, $cm:name, false)]";
QueryParameterDefinition[] params = new QueryParameterDefinition[1];
params[0] = new QueryParameterDefImpl(
ContentModel.PROP_NAME,
getServiceRegistry().getDictionaryService().getDataType(
DataTypeDefinition.TEXT),
true,
name);
// execute the query
List
parent,
XPATH_QUERY_NODE_MATCH,
params,
getServiceRegistry().getNamespaceService(),
false);
return (nodeRefs.size() != 0);
}
public QName getType(NodeRef nodeRef)
{
QName type = getServiceRegistry().getNodeService().getType(nodeRef);
return type;
}
Mapping of javascript and Java
sitedata object of Alfresco share(Surf) is availbale through
the class ScriptSiteData class present in the spring-surf-1.0.0.CI-SNAPSHOT.jar
Explore this to get the newPreset method.
the class ScriptSiteData class present in the spring-surf-1.0.0.CI-SNAPSHOT.jar
Explore this to get the newPreset method.
Wednesday, January 26, 2011
Hiding Guest Home, UserHomes , DataDictionary in Alfresco share
Follow the below steps
1. Hide in the tree.
Basically share will make the call to alfresco get all the nodeRef so we need to change the corresponding javascript.
Script responsible for the tree population of Repository is treenode.get.js present in the location
D:\Alfresco3.3\tomcat\webapps\alfresco\WEB-INF\classes\alfresco\templates\webscripts\org\alfresco\slingshot\documentlibrary\treenode.get.js
/**
* Document List Component: treenode
*/
model.treenode = getTreeNode();
/* Create collection of folders in the given space */
function getTreeNode()
{
try
{
var items = new Array(),
hasSubfolders = true,
ignoredTypes =
{
"{http://www.alfresco.org/model/forum/1.0}forum": true,
"{http://www.alfresco.org/model/forum/1.0}topic": true,
"{http://www.alfresco.org/model/content/1.0}systemfolder": true
},
evalChildFolders = args["children"] !== "false",
resultsTrimmed = false,
argMax = parseInt(args["max"], 10),
maxItems = isNaN(argMax) ? -1 : argMax;
// Use helper function to get the arguments
var parsedArgs = ParseArgs.getParsedArgs();
if (parsedArgs === null)
{
return;
}
// Look for folders in the pathNode
for each (item in parsedArgs.pathNode.children)
{ //added by patil to check folders
if (item.isSubType("cm:folder") && !(item.type in ignoredTypes) && !( (item.properties.name =="Data Dictionary") || (item.properties.name =="Guest Home")|| (item.properties.name =="User Homes")|| (item.properties.name =="Imap Home")))
{
if (evalChildFolders)
{
hasSubfolders = item.childFileFolders(false, true, "fm:forum").length > 0;
}
items.push(
{
node: item,
hasSubfolders: hasSubfolders
});
}
if (maxItems !== -1 && items.length > maxItems)
{
items.pop();
resultsTrimmed = true;
break;
}
}
items.sort(sortByName);
return (
{
parent: parsedArgs.pathNode,
resultsTrimmed: resultsTrimmed,
items: items
});
}
catch(e)
{
status.setCode(status.STATUS_INTERNAL_SERVER_ERROR, e.toString());
return;
}
}
/* Sort the results by case-insensitive name */
function sortByName(a, b)
{
return (b.node.name.toLowerCase() > a.node.name.toLowerCase() ? -1 : 1);
}
Similarly in the body part the listing will happen from the script doclist.get.js
/**
* Main entry point: Create collection of documents and folders in the given space
*
* @method getDoclist
*/
function getDoclist()
{
// Use helper function to get the arguments
var parsedArgs = ParseArgs.getParsedArgs();
if (parsedArgs === null)
{
return;
}
var filter = args.filter,
items = [];
// Try to find a filter query based on the passed-in arguments
var allNodes = [],
favourites = Common.getFavourites(),
filterParams = Filters.getFilterParams(filter, parsedArgs,
{
favourites: favourites
}),
query = filterParams.query;
// Query the nodes - passing in sort and result limit parameters
if (query !== "")
{
allNodes = search.query(
{
query: query,
language: filterParams.language,
page:
{
maxItems: (filterParams.limitResults ? parseInt(filterParams.limitResults, 10) : 0)
},
sort: filterParams.sort,
templates: filterParams.templates,
namespace: (filterParams.namespace ? filterParams.namespace : null)
});
}
// Ensure folders and folderlinks appear at the top of the list
var folderNodes = [],
documentNodes = [];
for each (node in allNodes)
{
try
{
if (node.isContainer || node.typeShort == "app:folderlink")
{
//added by patil to filter
if(!( (node.properties.name =="Data Dictionary") || (node.properties.name =="Guest Home")|| (node.properties.name =="User Homes")|| (node.properties.name =="Imap Home"))){
folderNodes.push(node);
}
}
else
{
documentNodes.push(node);
}
}
catch (e)
{
// Possibly an old indexed node - ignore it
}
}
// Node type counts
var folderNodesCount = folderNodes.length,
documentNodesCount = documentNodes.length,
nodes, totalRecords;
if (parsedArgs.type === "documents")
{
nodes = documentNodes;
}
else
{
nodes = folderNodes.concat(documentNodes);
}
totalRecords = nodes.length;
// Pagination
var pageSize = args.size || nodes.length,
pagePos = args.pos || "1",
startIndex = (pagePos - 1) * pageSize;
// Trim the nodes array down to the page size
nodes = nodes.slice(startIndex, pagePos * pageSize);
// Common or variable parent container?
var parent = null;
if (!filterParams.variablePath)
{
// Parent node permissions (and Site role if applicable)
parent =
{
node: parsedArgs.pathNode,
userAccess: Evaluator.run(parsedArgs.pathNode, true).actionPermissions
};
}
var isThumbnailNameRegistered = thumbnailService.isThumbnailNameRegistered(THUMBNAIL_NAME),
thumbnail = null,
locationNode,
item;
// Loop through and evaluate each node in this result set
for each (node in nodes)
{
// Get evaluated properties.
item = Evaluator.run(node);
item.isFavourite = (favourites[item.node.nodeRef] === true);
// Does this collection of nodes have potentially differering paths?
if (filterParams.variablePath || item.isLink)
{
locationNode = (item.isLink && item.type == "document") ? item.linkNode : item.node;
location = Common.getLocation(locationNode);
}
else
{
location =
{
site: parsedArgs.location.site,
siteTitle: parsedArgs.location.siteTitle,
container: parsedArgs.location.container,
path: parsedArgs.location.path,
file: node.name
};
}
// Resolved location
item.location = location;
// Is our thumbnail type registered?
if (isThumbnailNameRegistered)
{
// Make sure we have a thumbnail.
thumbnail = item.node.getThumbnail(THUMBNAIL_NAME);
if (thumbnail === null)
{
// No thumbnail, so queue creation
item.node.createThumbnail(THUMBNAIL_NAME, true);
}
}
items.push(item);
}
return (
{
luceneQuery: query,
paging:
{
totalRecords: totalRecords,
startIndex: startIndex
},
parent: parent,
onlineEditing: utils.moduleInstalled("org.alfresco.module.vti"),
itemCount:
{
folders: folderNodesCount,
documents: documentNodesCount
},
items: items
});
}
/**
* Document List Component: doclist
*/
model.doclist = getDoclist();
1. Hide in the tree.
Basically share will make the call to alfresco get all the nodeRef so we need to change the corresponding javascript.
Script responsible for the tree population of Repository is treenode.get.js present in the location
D:\Alfresco3.3\tomcat\webapps\alfresco\WEB-INF\classes\alfresco\templates\webscripts\org\alfresco\slingshot\documentlibrary\treenode.get.js
/**
* Document List Component: treenode
*/
model.treenode = getTreeNode();
/* Create collection of folders in the given space */
function getTreeNode()
{
try
{
var items = new Array(),
hasSubfolders = true,
ignoredTypes =
{
"{http://www.alfresco.org/model/forum/1.0}forum": true,
"{http://www.alfresco.org/model/forum/1.0}topic": true,
"{http://www.alfresco.org/model/content/1.0}systemfolder": true
},
evalChildFolders = args["children"] !== "false",
resultsTrimmed = false,
argMax = parseInt(args["max"], 10),
maxItems = isNaN(argMax) ? -1 : argMax;
// Use helper function to get the arguments
var parsedArgs = ParseArgs.getParsedArgs();
if (parsedArgs === null)
{
return;
}
// Look for folders in the pathNode
for each (item in parsedArgs.pathNode.children)
{ //added by patil to check folders
if (item.isSubType("cm:folder") && !(item.type in ignoredTypes) && !( (item.properties.name =="Data Dictionary") || (item.properties.name =="Guest Home")|| (item.properties.name =="User Homes")|| (item.properties.name =="Imap Home")))
{
if (evalChildFolders)
{
hasSubfolders = item.childFileFolders(false, true, "fm:forum").length > 0;
}
items.push(
{
node: item,
hasSubfolders: hasSubfolders
});
}
if (maxItems !== -1 && items.length > maxItems)
{
items.pop();
resultsTrimmed = true;
break;
}
}
items.sort(sortByName);
return (
{
parent: parsedArgs.pathNode,
resultsTrimmed: resultsTrimmed,
items: items
});
}
catch(e)
{
status.setCode(status.STATUS_INTERNAL_SERVER_ERROR, e.toString());
return;
}
}
/* Sort the results by case-insensitive name */
function sortByName(a, b)
{
return (b.node.name.toLowerCase() > a.node.name.toLowerCase() ? -1 : 1);
}
Similarly in the body part the listing will happen from the script doclist.get.js
/**
* Main entry point: Create collection of documents and folders in the given space
*
* @method getDoclist
*/
function getDoclist()
{
// Use helper function to get the arguments
var parsedArgs = ParseArgs.getParsedArgs();
if (parsedArgs === null)
{
return;
}
var filter = args.filter,
items = [];
// Try to find a filter query based on the passed-in arguments
var allNodes = [],
favourites = Common.getFavourites(),
filterParams = Filters.getFilterParams(filter, parsedArgs,
{
favourites: favourites
}),
query = filterParams.query;
// Query the nodes - passing in sort and result limit parameters
if (query !== "")
{
allNodes = search.query(
{
query: query,
language: filterParams.language,
page:
{
maxItems: (filterParams.limitResults ? parseInt(filterParams.limitResults, 10) : 0)
},
sort: filterParams.sort,
templates: filterParams.templates,
namespace: (filterParams.namespace ? filterParams.namespace : null)
});
}
// Ensure folders and folderlinks appear at the top of the list
var folderNodes = [],
documentNodes = [];
for each (node in allNodes)
{
try
{
if (node.isContainer || node.typeShort == "app:folderlink")
{
//added by patil to filter
if(!( (node.properties.name =="Data Dictionary") || (node.properties.name =="Guest Home")|| (node.properties.name =="User Homes")|| (node.properties.name =="Imap Home"))){
folderNodes.push(node);
}
}
else
{
documentNodes.push(node);
}
}
catch (e)
{
// Possibly an old indexed node - ignore it
}
}
// Node type counts
var folderNodesCount = folderNodes.length,
documentNodesCount = documentNodes.length,
nodes, totalRecords;
if (parsedArgs.type === "documents")
{
nodes = documentNodes;
}
else
{
nodes = folderNodes.concat(documentNodes);
}
totalRecords = nodes.length;
// Pagination
var pageSize = args.size || nodes.length,
pagePos = args.pos || "1",
startIndex = (pagePos - 1) * pageSize;
// Trim the nodes array down to the page size
nodes = nodes.slice(startIndex, pagePos * pageSize);
// Common or variable parent container?
var parent = null;
if (!filterParams.variablePath)
{
// Parent node permissions (and Site role if applicable)
parent =
{
node: parsedArgs.pathNode,
userAccess: Evaluator.run(parsedArgs.pathNode, true).actionPermissions
};
}
var isThumbnailNameRegistered = thumbnailService.isThumbnailNameRegistered(THUMBNAIL_NAME),
thumbnail = null,
locationNode,
item;
// Loop through and evaluate each node in this result set
for each (node in nodes)
{
// Get evaluated properties.
item = Evaluator.run(node);
item.isFavourite = (favourites[item.node.nodeRef] === true);
// Does this collection of nodes have potentially differering paths?
if (filterParams.variablePath || item.isLink)
{
locationNode = (item.isLink && item.type == "document") ? item.linkNode : item.node;
location = Common.getLocation(locationNode);
}
else
{
location =
{
site: parsedArgs.location.site,
siteTitle: parsedArgs.location.siteTitle,
container: parsedArgs.location.container,
path: parsedArgs.location.path,
file: node.name
};
}
// Resolved location
item.location = location;
// Is our thumbnail type registered?
if (isThumbnailNameRegistered)
{
// Make sure we have a thumbnail.
thumbnail = item.node.getThumbnail(THUMBNAIL_NAME);
if (thumbnail === null)
{
// No thumbnail, so queue creation
item.node.createThumbnail(THUMBNAIL_NAME, true);
}
}
items.push(item);
}
return (
{
luceneQuery: query,
paging:
{
totalRecords: totalRecords,
startIndex: startIndex
},
parent: parent,
onlineEditing: utils.moduleInstalled("org.alfresco.module.vti"),
itemCount:
{
folders: folderNodesCount,
documents: documentNodesCount
},
items: items
});
}
/**
* Document List Component: doclist
*/
model.doclist = getDoclist();
Tuesday, January 25, 2011
Sample codes in Alfresco share
Code to get the Email Template
private NodeRef getEmailTemplateNodeRef()
{
StoreRef spacesStore = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
String query = " PATH:\"app:company_home/app:dictionary/app:email_templates/cm:invite/cm:invite-email.ftl\"";
SearchParameters searchParams = new SearchParameters();
searchParams.addStore(spacesStore);
searchParams.setLanguage(SearchService.LANGUAGE_LUCENE);
searchParams.setQuery(query);
ResultSet results = null;
try
{
results = searchService.query(searchParams);
List nodeRefs = results.getNodeRefs();
if (nodeRefs.size() == 1)
return nodeRefs.get(0);
else
throw new InvitationException("Cannot find the email templatte!");
}
catch (SearcherException e)
{
throw new InvitationException("Cannot find the email templatte!", e);
}
finally
{
if (results != null)
results.close();
}
}
Using the WorkflowTaskQuery
/**
* Invitee accepts this invitation Nominated Invitaton process only
*
* @param invitationId the invitation id
* @param ticket the ticket produced when creating the invitation.
*/
public Invitation accept(String invitationId, String ticket)
{
Invitation invitation = getInvitation(invitationId);
if (invitation instanceof NominatedInvitation)
{
// Check invitationId and ticket match
if (ticket == null || (!ticket.equals(((NominatedInvitation) invitation).getTicket())))
{
throw new InvitationException("Response to invite has supplied an invalid ticket. The response to the "
+ "invitation could thus not be processed");
}
/**
* Nominated invitation complete the wf:invitePendingTask along the
* 'accept' transition because the invitation has been accepted
*/
// create workflow task query
WorkflowTaskQuery wfTaskQuery = new WorkflowTaskQuery();
// set the given invite ID as the workflow process ID in the
// workflow query
wfTaskQuery.setProcessId(invitationId);
// find incomplete invite workflow tasks with given task name
wfTaskQuery.setActive(Boolean.TRUE);
wfTaskQuery.setTaskState(WorkflowTaskState.IN_PROGRESS);
wfTaskQuery.setTaskName(WorkflowModelNominatedInvitation.WF_INVITE_TASK_INVITE_PENDING);
// set process name to "wf:invite" so that only
// invite workflow instances are considered by this query
wfTaskQuery.setProcessName(WorkflowModelNominatedInvitation.WF_PROCESS_INVITE);
// query for invite workflow tasks with the constructed query
List wf_invite_tasks = workflowService.queryTasks(wfTaskQuery);
if (wf_invite_tasks.size() == 0)
{
Object objs[] = { invitationId };
throw new InvitationExceptionUserError("invitation.invite.already_finished", objs);
}
// end all tasks found with this name
for (WorkflowTask workflowTask : wf_invite_tasks)
{
workflowService.endTask(workflowTask.id, WorkflowModelNominatedInvitation.WF_TRANSITION_ACCEPT);
}
return invitation;
}
throw new InvitationException("State error, cannot call accept a moderated invitation");
}
Code for Running as system user
AuthenticationUtil.runAs(new RunAsWork
private NodeRef getEmailTemplateNodeRef()
{
StoreRef spacesStore = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
String query = " PATH:\"app:company_home/app:dictionary/app:email_templates/cm:invite/cm:invite-email.ftl\"";
SearchParameters searchParams = new SearchParameters();
searchParams.addStore(spacesStore);
searchParams.setLanguage(SearchService.LANGUAGE_LUCENE);
searchParams.setQuery(query);
ResultSet results = null;
try
{
results = searchService.query(searchParams);
List
if (nodeRefs.size() == 1)
return nodeRefs.get(0);
else
throw new InvitationException("Cannot find the email templatte!");
}
catch (SearcherException e)
{
throw new InvitationException("Cannot find the email templatte!", e);
}
finally
{
if (results != null)
results.close();
}
}
Using the WorkflowTaskQuery
/**
* Invitee accepts this invitation Nominated Invitaton process only
*
* @param invitationId the invitation id
* @param ticket the ticket produced when creating the invitation.
*/
public Invitation accept(String invitationId, String ticket)
{
Invitation invitation = getInvitation(invitationId);
if (invitation instanceof NominatedInvitation)
{
// Check invitationId and ticket match
if (ticket == null || (!ticket.equals(((NominatedInvitation) invitation).getTicket())))
{
throw new InvitationException("Response to invite has supplied an invalid ticket. The response to the "
+ "invitation could thus not be processed");
}
/**
* Nominated invitation complete the wf:invitePendingTask along the
* 'accept' transition because the invitation has been accepted
*/
// create workflow task query
WorkflowTaskQuery wfTaskQuery = new WorkflowTaskQuery();
// set the given invite ID as the workflow process ID in the
// workflow query
wfTaskQuery.setProcessId(invitationId);
// find incomplete invite workflow tasks with given task name
wfTaskQuery.setActive(Boolean.TRUE);
wfTaskQuery.setTaskState(WorkflowTaskState.IN_PROGRESS);
wfTaskQuery.setTaskName(WorkflowModelNominatedInvitation.WF_INVITE_TASK_INVITE_PENDING);
// set process name to "wf:invite" so that only
// invite workflow instances are considered by this query
wfTaskQuery.setProcessName(WorkflowModelNominatedInvitation.WF_PROCESS_INVITE);
// query for invite workflow tasks with the constructed query
List
if (wf_invite_tasks.size() == 0)
{
Object objs[] = { invitationId };
throw new InvitationExceptionUserError("invitation.invite.already_finished", objs);
}
// end all tasks found with this name
for (WorkflowTask workflowTask : wf_invite_tasks)
{
workflowService.endTask(workflowTask.id, WorkflowModelNominatedInvitation.WF_TRANSITION_ACCEPT);
}
return invitation;
}
throw new InvitationException("State error, cannot call accept a moderated invitation");
}
Code for Running as system user
AuthenticationUtil.runAs(new RunAsWork