Powered By Blogger

Monday, January 31, 2011

import org.springframework.extensions.surf.util.Base64; encding

import org.springframework.extensions.surf.util.Base64;

It is the encoding used
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

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

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.

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.

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;
}

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.

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();

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()
{
public Object doWork() throws Exception
{
NodeRef person = personService.createPerson(properties);
permissionService.setPermission(person, finalUserName, PermissionService.ALL_PERMISSIONS, true);

return null;
}

}, AuthenticationUtil.getSystemUserName());




Code to start workflow on the empty package. This illustration is been done in the
Inviting the external user to the Alfresco

/**
* Starts the Invite workflow
*
* @param inviteeFirstName first name of invitee
* @param inviteeLastNamme last name of invitee
* @param inviteeEmail email address of invitee
* @param siteShortName short name of site that the invitee is being invited
* to by the inviter
* @param inviteeSiteRole role under which invitee is being invited to the
* site by the inviter
* @param serverPath externally accessible server address of server hosting
* invite web scripts
*/
private NominatedInvitation startNominatedInvite(String inviteeFirstName, String inviteeLastName,
String inviteeEmail, String inviteeUserName, Invitation.ResourceType resourceType,
String siteShortName, String inviteeSiteRole, String serverPath, String acceptUrl, String rejectUrl)
{

// get the inviter user name (the name of user web script is executed
// under)
String inviterUserName = this.authenticationService.getCurrentUserName();
boolean created = false;

checkManagerRole(inviterUserName, resourceType, siteShortName);

if (logger.isDebugEnabled())
{
logger.debug("startInvite() inviterUserName=" + inviterUserName + " inviteeUserName=" + inviteeUserName
+ " inviteeFirstName=" + inviteeFirstName + " inviteeLastName=" + inviteeLastName
+ " inviteeEmail=" + inviteeEmail + " siteShortName=" + siteShortName + " inviteeSiteRole="
+ inviteeSiteRole);
}
//
// if we have not explicitly been passed an existing user's user name
// then ....
//
// if a person already exists who has the given invitee email address
//
// 1) obtain invitee user name from first person found having the
// invitee email address, first name and last name
// 2) handle error conditions -
// (invitee already has an invitation in progress for the given site,
// or he/she is already a member of the given site
//
if (inviteeUserName == null || inviteeUserName.trim().length() == 0)
{

inviteeUserName = null;

Set peopleWithInviteeEmail = this.personService.getPeopleFilteredByProperty(
ContentModel.PROP_EMAIL, inviteeEmail);

if (peopleWithInviteeEmail.size() > 0)
{
// get person already existing who has the given
// invitee email address
for (NodeRef personRef : peopleWithInviteeEmail)
{
Serializable firstNameVal = this.getNodeService().getProperty(personRef,
ContentModel.PROP_FIRSTNAME);
Serializable lastNameVal = this.getNodeService().getProperty(personRef, ContentModel.PROP_LASTNAME);

String personFirstName = DefaultTypeConverter.INSTANCE.convert(String.class, firstNameVal);
String personLastName = DefaultTypeConverter.INSTANCE.convert(String.class, lastNameVal);

if (personFirstName != null && personFirstName.equalsIgnoreCase(inviteeFirstName))
{
if (personLastName != null && personLastName.equalsIgnoreCase(inviteeLastName))
{
// got a match on email, lastname, firstname
// get invitee user name of that person
Serializable userNamePropertyVal = this.getNodeService().getProperty(personRef,
ContentModel.PROP_USERNAME);
inviteeUserName = DefaultTypeConverter.INSTANCE.convert(String.class, userNamePropertyVal);

if (logger.isDebugEnabled())
{
logger
.debug("not explictly passed username - found matching email, resolved inviteeUserName="
+ inviteeUserName);
}
}
}
}
}

if (inviteeUserName == null)
{
// This shouldn't normally happen. Due to the fix for ETHREEOH-3268, the link to invite external users
// should be disabled when the authentication chain does not allow it.
if (!authenticationService.isAuthenticationCreationAllowed())
{
throw new InvitationException("invitation.invite.authentication_chain");
}
// else there are no existing people who have the given invitee
// email address so create new person
inviteeUserName = createInviteePerson(inviteeFirstName, inviteeLastName, inviteeEmail);
created = true;
if (logger.isDebugEnabled())
{
logger.debug("not explictly passed username - created new person, inviteeUserName="
+ inviteeUserName);
}
}
}
else
{
// TODO MER - Is the code block neccessary - seems to do nothing ?
// inviteeUserName was specified
NodeRef person = this.personService.getPerson(inviteeUserName);

// TODO
Serializable firstNameVal = this.getNodeService().getProperty(person, ContentModel.PROP_FIRSTNAME);
Serializable lastNameVal = this.getNodeService().getProperty(person, ContentModel.PROP_LASTNAME);
Serializable emailVal = this.getNodeService().getProperty(person, ContentModel.PROP_EMAIL);
firstNameVal = DefaultTypeConverter.INSTANCE.convert(String.class, firstNameVal);
lastNameVal = DefaultTypeConverter.INSTANCE.convert(String.class, lastNameVal);
emailVal = DefaultTypeConverter.INSTANCE.convert(String.class, emailVal);
}

/**
* throw exception if person is already a member of the given site
*/
if (this.siteService.isMember(siteShortName, inviteeUserName))
{
if (logger.isDebugEnabled())
logger.debug("Failed - invitee user is already a member of the site.");

Object objs[] = { inviteeUserName, inviteeEmail, siteShortName };
throw new InvitationExceptionUserError("invitation.invite.already_member", objs);
}

//
// If a user account does not already exist for invitee user name
// then create a disabled user account for the invitee.
// Hold a local reference to generated password if disabled invitee
// account
// is created, otherwise if a user account already exists for invitee
// user name, then local reference to invitee password will be "null"
//
final String initeeUserNameFinal = inviteeUserName;

String inviteePassword = created ? AuthenticationUtil.runAs(new RunAsWork()
{
public String doWork()
{
return createInviteeDisabledAccount(initeeUserNameFinal);
}
}, AuthenticationUtil.getSystemUserName()) : null;

// create a ticket for the invite - this is used
String inviteTicket = GUID.generate();

//
// Start the invite workflow with inviter, invitee and site properties
//

WorkflowDefinition wfDefinition = this.workflowService
.getDefinitionByName(WorkflowModelNominatedInvitation.WORKFLOW_DEFINITION_NAME);

if (wfDefinition == null)
{
// handle workflow definition does not exist
Object objs[] = { WorkflowModelNominatedInvitation.WORKFLOW_DEFINITION_NAME };
throw new InvitationException("invitation.error.noworkflow", objs);
}

// Get invitee person NodeRef to add as assignee
NodeRef inviteeNodeRef = this.personService.getPerson(inviteeUserName);

SiteInfo siteInfo = this.siteService.getSite(siteShortName);
String siteDescription = siteInfo.getDescription();
if (siteDescription == null)
{
siteDescription = "";
}
else if (siteDescription.length() > 255)
{
siteDescription = siteDescription.substring(0, 255);
}
// create workflow properties
Map workflowProps = new HashMap(16);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_INVITER_USER_NAME, inviterUserName);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_INVITEE_USER_NAME, inviteeUserName);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_INVITEE_EMAIL, inviteeEmail);
workflowProps.put(WorkflowModel.ASSOC_ASSIGNEE, inviteeNodeRef);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_INVITEE_FIRSTNAME, inviteeFirstName);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_INVITEE_LASTNAME, inviteeLastName);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_INVITEE_GEN_PASSWORD, inviteePassword);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_RESOURCE_NAME, siteShortName);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_RESOURCE_TITLE, siteInfo.getTitle());
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_RESOURCE_DESCRIPTION, siteDescription);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_RESOURCE_TYPE, resourceType.toString());
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_INVITEE_ROLE, inviteeSiteRole);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_SERVER_PATH, serverPath);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_ACCEPT_URL, acceptUrl);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_REJECT_URL, rejectUrl);
workflowProps.put(WorkflowModelNominatedInvitation.WF_PROP_INVITE_TICKET, inviteTicket);

// start the workflow
WorkflowPath wfPath = this.workflowService.startWorkflow(wfDefinition.getId(), workflowProps);

//
// complete invite workflow start task to send out the invite email
//

// get the workflow tasks
String workflowId = wfPath.instance.id;
String wfPathId = wfPath.id;
List wfTasks = this.workflowService.getTasksForWorkflowPath(wfPathId);

// throw an exception if no tasks where found on the workflow path
if (wfTasks.size() == 0)
{
Object objs[] = { WorkflowModelNominatedInvitation.WORKFLOW_DEFINITION_NAME };
throw new InvitationException("invitation.error.notasks", objs);
}

//
// first task in workflow task list (there should only be one)
// associated
// with the workflow path id (above) should be "wf:inviteToSiteTask",
// otherwise
// throw web script exception
//
String wfTaskName = wfTasks.get(0).name;
QName wfTaskNameQName = QName.createQName(wfTaskName, this.namespaceService);
QName inviteToSiteTaskQName = WorkflowModelNominatedInvitation.WF_INVITE_TASK_INVITE_TO_SITE;
if (!wfTaskNameQName.equals(inviteToSiteTaskQName))
{
Object objs[] = { wfPathId, WorkflowModelNominatedInvitation.WF_INVITE_TASK_INVITE_TO_SITE };
throw new InvitationException("invitation.error.wrong_first_task", objs);
}

// get "inviteToSite" task
WorkflowTask wfStartTask = wfTasks.get(0);

// attach empty package to start task, end it and follow with transition
// that sends out the invite
if (logger.isDebugEnabled())
logger.debug("Starting Invite workflow task by attaching empty package...");
NodeRef wfPackage = this.workflowService.createPackage(null);
Map wfTaskProps = new HashMap(1, 1.0f);
wfTaskProps.put(WorkflowModel.ASSOC_PACKAGE, wfPackage);
wfTaskProps.put(WorkflowModel.PROP_WORKFLOW_INSTANCE_ID, workflowId);

if (logger.isDebugEnabled())
logger.debug("Updating Invite workflow task...");
this.workflowService.updateTask(wfStartTask.id, wfTaskProps, null, null);

if (logger.isDebugEnabled())
logger.debug("Transitioning Invite workflow task...");
try
{
this.workflowService.endTask(wfStartTask.id, WorkflowModelNominatedInvitation.WF_TRANSITION_SEND_INVITE);
}
catch (RuntimeException err)
{
if (logger.isDebugEnabled())
logger.debug("Failed - caught error during Invite workflow transition: " + err.getMessage());
throw err;
}

NominatedInvitationImpl result = new NominatedInvitationImpl(workflowProps);
result.setTicket(inviteTicket);
result.setInviteId(workflowId);
result.setSentInviteDate(new Date());
return result;
}

Inviting external users to Share site

Check org.alfresco.repo.invitation.InvitationServiceImplTest to
test the functionality related to inviting the users to the site, mail generation etc


The actual implementation class is present in the class
InvitationServiceImpl present in the package
org.alfresco.repo.invitation

SIte Service, Alfresco Share

Craeting the site

SiteInfo siteInfo = this.siteService.createSite(TEST_SITE_PRESET, "mySiteTest", TEST_TITLE, TEST_DESCRIPTION, SiteVisibility.PUBLIC);



Setting the users for the site
// Add the test group as a member of the site
this.siteService.setMembership(siteShortName, testGroup, SiteModel.SITE_CONTRIBUTOR);


For any changes refer to SiteServiceImplTest
present in the package org.alfresco.repo.site

Monday, January 24, 2011

Hiding Guest Home, Data dictionary , Sites from the normal users

Make the below entry in faces-config-custom.xml



The bean that holds folder browse state.

BrowseBean
com.powergrid.web.bean.PowerGridBrowseBean
session

navigator
#{NavigationBean}


nodeService
#{NodeService}


searchService
#{SearchService}


lockService
#{LockService}


dictionaryService
#{DictionaryService}


fileFolderService
#{FileFolderService}


userPreferencesBean
#{UserPreferencesBean}


multilingualContentService
#{MultilingualContentService}


authorityService
#{AuthorityService}







Bean that returns manages the tree data for the navigator component.
Removes Companyhome

NavigatorPluginBean
com.powergrid.web.bean.ajax.CustomNavigatorPluginBean
session

nodeService
#{NodeService}


internalNodeService
#{nodeService}


dictionaryService
#{DictionaryService}





The java files are


/**
*
*/
package com.powergrid.web.bean.ajax;

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

import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.transaction.UserTransaction;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.namespace.RegexQNamePattern;
import org.alfresco.web.app.Application;
import org.alfresco.web.bean.ajax.NavigatorPluginBean;
import org.alfresco.web.bean.repository.Repository;
import org.alfresco.web.data.IDataContainer;
import org.alfresco.web.data.QuickSort;
import org.alfresco.web.ui.common.Utils;
import org.alfresco.web.ui.repo.component.UITree.TreeNode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* @author basanagowda.patil
* This class is been written to hide some of the folders which are not required to be shown
*
*/
public class CustomNavigatorPluginBean extends NavigatorPluginBean {


private static final long serialVersionUID = 5223411855251335195L;
private static final Log logger = LogFactory.getLog(CustomNavigatorPluginBean.class);
//added by cignex start
NodeService nodeService = null ;
AuthorityService authorityService = null;
// ------------------------------------------------------------------------------
// AJAX handler methods

public AuthorityService getAuthorityService() {
return authorityService;
}




public void setAuthorityService(AuthorityService authorityService) {
this.authorityService = authorityService;
}

//added by cignex ends



/*
*//**
* Retrieves the child folders for the noderef given in the
* 'noderef' parameter and caches the nodes against the area in
* the 'area' parameter.
*//*
public void retrieveChildren() throws IOException
{
FacesContext context = FacesContext.getCurrentInstance();
ResponseWriter out = context.getResponseWriter();

UserTransaction tx = null;
try
{
tx = Repository.getUserTransaction(context, true);
tx.begin();

Map params = context.getExternalContext().getRequestParameterMap();
String nodeRefStr = (String)params.get("nodeRef");
String area = (String)params.get("area");

if (logger.isDebugEnabled())
logger.debug("retrieveChildren: area = " + area + ", nodeRef = " + nodeRefStr);

// work out which list to cache the nodes in
Map currentNodes = getNodesMapForArea(area);

if (nodeRefStr != null && currentNodes != null)
{
// get the given node's details
NodeRef parentNodeRef = new NodeRef(nodeRefStr);
TreeNode parentNode = currentNodes.get(parentNodeRef.toString());
parentNode.setExpanded(true);

if (logger.isDebugEnabled())
logger.debug("retrieving children for noderef: " + parentNodeRef);

// remove any existing children as the latest ones will be added below
parentNode.removeChildren();

// get all the child folder objects for the parent
//added by cignex

if (nodeService == null)
{
nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService();
}

List childRefs = nodeService.getChildAssocs(parentNodeRef,
ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
List sortedNodes = new ArrayList();
for (ChildAssociationRef ref: childRefs)
{
NodeRef nodeRef = ref.getChildRef();

if (isAddableChild(nodeRef))
{
// build the XML representation of the child node
TreeNode childNode = createTreeNode(nodeRef);
parentNode.addChild(childNode);
currentNodes.put(childNode.getNodeRef(), childNode);
sortedNodes.add(childNode);
}
}

// order the tree nodes by the tree label
if (sortedNodes.size() > 1)
{
QuickSort sorter = new QuickSort(sortedNodes, "name", true, IDataContainer.SORT_CASEINSENSITIVE);
sorter.sort();
}

// generate the XML representation
StringBuilder xml = new StringBuilder("");
for (TreeNode childNode : sortedNodes)
{ //cignex code to remove datdictionary
if(!childNode.getName().equals("Data Dictionary")){
xml.append(childNode.toXML());
}else{
logger.debug("Excluding datadictionary folder");
}

}
xml.append("
");

// send the generated XML back to the tree
out.write(xml.toString());

if (logger.isDebugEnabled())
logger.debug("returning XML: " + xml.toString());
}

// commit the transaction
tx.commit();
}
catch (Throwable err)
{
try { if (tx != null) {tx.rollback();} } catch (Exception tex) {}
}
}
*/



/**
* Returns the root nodes for the company home panel.
*


* As the user expands and collapses nodes in the client this
* cache will be updated with the appropriate nodes and states.
*


*
* @return List of root nodes for the company home panel
*/
public List getCompanyHomeRootNodes()
{
if (this.companyHomeRootNodes == null)
{
this.companyHomeRootNodes = new ArrayList();
this.companyHomeNodes = new HashMap();

UserTransaction tx = null;
try
{
FacesContext fc = FacesContext.getCurrentInstance();
tx = Repository.getUserTransaction(fc, true);
tx.begin();

// query for the child nodes of company home
NodeRef root = new NodeRef(Repository.getStoreRef(), Application.getCompanyRootId(fc));
if (nodeService == null)
{
nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService();
}
List childRefs = this.getNodeService().getChildAssocs(root,
ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
//added by Cignex to show only to admin
String user = AuthenticationUtil.getRunAsUser();
for (ChildAssociationRef ref: childRefs)
{
NodeRef child = ref.getChildRef();
//added anothe r condition. Cignex.
if (isAddableChild(child) && validFolder(child , user))
{
TreeNode node = createTreeNode(child);
this.companyHomeRootNodes.add(node);
this.companyHomeNodes.put(node.getNodeRef(), node);
}
}

tx.commit();
}
catch (Throwable err)
{
Utils.addErrorMessage("NavigatorPluginBean exception in getCompanyHomeRootNodes()", err);
try { if (tx != null) {tx.rollback();} } catch (Exception tex) {}
}
}

return this.companyHomeRootNodes;
}

/**
* Checks whether to show it or not. Added by cignex
* @param child
* @return
*/
private boolean validFolder(NodeRef child, String user ){
boolean validFolder = true;



if (nodeService == null)
{
nodeService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getNodeService();
}

String name = (String)nodeService.getProperty(child , ContentModel.PROP_NAME);
if(name.equals("Sites") || name.equals("Data Dictionary") || name.equals("User Homes") || name.equals("Guest Home")){
validFolder = false ;
}

if (authorityService == null)
{
authorityService = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getAuthorityService();
}

//if user is having admin role then show evrything
if(authorityService.isAdminAuthority(user)){
validFolder = true;
}



return validFolder;
}


public NodeService getNodeService() {
return nodeService;
}




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



}





_________________________________



/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see .
*/
package com.powergrid.web.bean;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.faces.context.FacesContext;
import javax.transaction.UserTransaction;

import org.alfresco.model.ApplicationModel;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.search.SearcherException;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.dictionary.TypeDefinition;
import org.alfresco.service.cmr.model.FileInfo;
import org.alfresco.service.cmr.repository.InvalidNodeRefException;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.search.LimitBy;
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.AuthorityService;
import org.alfresco.service.cmr.security.PermissionService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.QName;
import org.alfresco.web.app.Application;
import org.alfresco.web.app.servlet.FacesHelper;
import org.alfresco.web.bean.BrowseBean;
import org.alfresco.web.bean.NodeEventListener;
import org.alfresco.web.bean.repository.MapNode;
import org.alfresco.web.bean.repository.Node;
import org.alfresco.web.bean.repository.Repository;
import org.alfresco.web.bean.search.SearchContext;
import org.alfresco.web.ui.common.Utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.config.Config;
import org.springframework.extensions.config.ConfigElement;




/**
* Bean providing properties and behaviour for the main folder/document browse screen and
* search results screens.
*
* @author Kevin Roast
*/
public class PowerGridBrowseBean extends BrowseBean
{

private static final long serialVersionUID = -4529711713073442787L;
private static Log logger = LogFactory.getLog(PowerGridBrowseBean.class);
PersonService personService = null;
AuthorityService authorityService = null;
public AuthorityService getAuthorityService() {
return authorityService;
}


public void setAuthorityService(AuthorityService authorityService) {
this.authorityService = authorityService;
}


public PersonService getPersonService() {
return personService;
}


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


@Override
public List getNodes() {

// the references to container nodes and content nodes are transient for one use only
// we do this so we only query/search once - as we cannot distinguish between node types
// until after the query. The logic is a bit confusing but otherwise we would need to
// perform the same query or search twice for every screen refresh.
if (this.containerNodes == null)
{
if (this.navigator.getSearchContext() == null)
{
queryBrowseNodes(this.navigator.getCurrentNodeId());
}
else
{
searchBrowseNodes(this.navigator.getSearchContext());
}
}
List result = this.containerNodes;

// we clear the member variable during invalidateComponents()

/*
if(this.containerNodes != null){
int index= 0;
for(Node node : this.containerNodes){
if(node.getName().equals("Sites") || node.getName().equals("Data Dictionary") || node.getName().equals("User Homes")){
result.remove(index);
logger.debug("Removed the folders:::"+node.getName());
}
index ++;

}


}*/

return result;

}


/**
* Query a list of nodes for the specified parent node Id
*
* @param parentNodeId Id of the parent node or null for the root node
*/
private void queryBrowseNodes(String parentNodeId)
{
long startTime = 0;
if (logger.isDebugEnabled())
startTime = System.currentTimeMillis();

UserTransaction tx = null;
try
{
FacesContext context = FacesContext.getCurrentInstance();
tx = Repository.getUserTransaction(context, true);
tx.begin();

NodeRef parentRef;
if (parentNodeId == null)
{
// no specific parent node specified - use the root node
parentRef = this.getNodeService().getRootNode(Repository.getStoreRef());
}
else
{
// build a NodeRef for the specified Id and our store
parentRef = new NodeRef(Repository.getStoreRef(), parentNodeId);
}

List children = this.getFileFolderService().list(parentRef);
this.containerNodes = new ArrayList(children.size());
this.contentNodes = new ArrayList(children.size());

// in case of dynamic config, only lookup once
Set nodeEventListeners = this.getNodeEventListeners();

for (FileInfo fileInfo : children)
{
// create our Node representation from the NodeRef
NodeRef nodeRef = fileInfo.getNodeRef();

// find it's type so we can see if it's a node we are interested in
QName type = this.getNodeService().getType(nodeRef);

// make sure the type is defined in the data dictionary
TypeDefinition typeDef = this.getDictionaryService().getType(type);

if (typeDef != null)
{
MapNode node = null;

// look for File content node
if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT))
{
// create our Node representation
node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
setupCommonBindingProperties(node);

this.contentNodes.add(node);
}
// look for Space folder node
else if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true &&
this.getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false)
{
// create our Node representation
node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
node.addPropertyResolver("icon", this.resolverSpaceIcon);
node.addPropertyResolver("smallIcon", this.resolverSmallIcon);
//added by cignex to filter the folders
if(!filterFoldes(node.getName())) {
this.containerNodes.add(node);
}






}
// look for File Link object node
else if (ApplicationModel.TYPE_FILELINK.equals(type))
{
// create our File Link Node representation
node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
// only display the user has the permissions to navigate to the target of the link
NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
if (destRef != null && new Node(destRef).hasPermission(PermissionService.READ) == true)
{
node.addPropertyResolver("url", this.resolverLinkUrl);
node.addPropertyResolver("downloadUrl", this.resolverLinkDownload);
node.addPropertyResolver("webdavUrl", this.resolverLinkWebdavUrl);
node.addPropertyResolver("cifsPath", this.resolverLinkCifsPath);
node.addPropertyResolver("fileType16", this.resolverFileType16);
node.addPropertyResolver("fileType32", this.resolverFileType32);
node.addPropertyResolver("size", this.resolverSize);
node.addPropertyResolver("lang", this.resolverLang);

this.contentNodes.add(node);
}
}
else if (ApplicationModel.TYPE_FOLDERLINK.equals(type))
{
// create our Folder Link Node representation
node = new MapNode(nodeRef, this.getNodeService(), fileInfo.getProperties());
// only display the user has the permissions to navigate to the target of the link
NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
if (destRef != null && new Node(destRef).hasPermission(PermissionService.READ) == true)
{
node.addPropertyResolver("icon", this.resolverSpaceIcon);
node.addPropertyResolver("smallIcon", this.resolverSmallIcon);

this.containerNodes.add(node);
}
}

// inform any listeners that a Node wrapper has been created
if (node != null)
{
for (NodeEventListener listener : nodeEventListeners)
{
listener.created(node, type);
}
}
}
else
{
if (logger.isWarnEnabled())
logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type);
}
}

// commit the transaction
tx.commit();
}
catch (InvalidNodeRefException refErr)
{
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {refErr.getNodeRef()}), refErr );
this.containerNodes = Collections.emptyList();
this.contentNodes = Collections.emptyList();
try { if (tx != null) {tx.rollback();} } catch (Exception tex) {}
}
catch (Throwable err)
{
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err);
this.containerNodes = Collections.emptyList();
this.contentNodes = Collections.emptyList();
try { if (tx != null) {tx.rollback();} } catch (Exception tex) {}
}

if (logger.isDebugEnabled())
{
long endTime = System.currentTimeMillis();
logger.debug("Time to query and build map nodes: " + (endTime - startTime) + "ms");
}
}




/**
* Search for a list of nodes using the specific search context
*
* @param searchContext To use to perform the search
*/
private void searchBrowseNodes(SearchContext searchContext)
{
long startTime = 0;
if (logger.isDebugEnabled())
startTime = System.currentTimeMillis();

// get the searcher object to build the query
String query = searchContext.buildQuery(getMinimumSearchLength());
if (query == null)
{
// failed to build a valid query, the user probably did not enter the
// minimum text required to construct a valid search
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), MSG_SEARCH_MINIMUM),
new Object[] {getMinimumSearchLength()}));
this.containerNodes = Collections.emptyList();
this.contentNodes = Collections.emptyList();
return;
}

// perform the search against the repo
UserTransaction tx = null;
ResultSet results = null;
try
{
tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
tx.begin();

// build up the search parameters
SearchParameters sp = new SearchParameters();
sp.setLanguage(SearchService.LANGUAGE_LUCENE);
sp.setQuery(query);
sp.addStore(Repository.getStoreRef());

// limit search results size as configured
int searchLimit = Application.getClientConfig(FacesContext.getCurrentInstance()).getSearchMaxResults();
if (searchLimit > 0)
{
sp.setLimitBy(LimitBy.FINAL_SIZE);
sp.setLimit(searchLimit);
}

results = this.getSearchService().query(sp);
if (logger.isDebugEnabled())
logger.debug("Search results returned: " + results.length());

// create a list of items from the results
this.containerNodes = new ArrayList(results.length());
this.contentNodes = new ArrayList(results.length());
if (results.length() != 0)
{
// in case of dynamic config, only lookup once
Set nodeEventListeners = getNodeEventListeners();

for (ResultSetRow row: results)
{
NodeRef nodeRef = row.getNodeRef();

if (this.getNodeService().exists(nodeRef))
{
// find it's type so we can see if it's a node we are interested in
QName type = this.getNodeService().getType(nodeRef);

// make sure the type is defined in the data dictionary
TypeDefinition typeDef = this.getDictionaryService().getType(type);

if (typeDef != null)
{
MapNode node = null;

// look for Space or File nodes
if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) &&
this.getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false)
{
// create our Node representation
node = new MapNode(nodeRef, this.getNodeService(), false);

node.addPropertyResolver("path", this.resolverPath);
node.addPropertyResolver("displayPath", this.resolverDisplayPath);
node.addPropertyResolver("icon", this.resolverSpaceIcon);
node.addPropertyResolver("smallIcon", this.resolverSmallIcon);
if(!filterFoldes(node.getName())) {
this.containerNodes.add(node);
}

}
else if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT))
{
// create our Node representation
node = new MapNode(nodeRef, this.getNodeService(), false);

setupCommonBindingProperties(node);

node.addPropertyResolver("path", this.resolverPath);
node.addPropertyResolver("displayPath", this.resolverDisplayPath);

this.contentNodes.add(node);
}
// look for File Link object node
else if (ApplicationModel.TYPE_FILELINK.equals(type))
{
// create our File Link Node representation
node = new MapNode(nodeRef, this.getNodeService(), false);
// only display the user has the permissions to navigate to the target of the link
NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
if (new Node(destRef).hasPermission(PermissionService.READ) == true)
{
node.addPropertyResolver("url", this.resolverLinkUrl);
node.addPropertyResolver("downloadUrl", this.resolverLinkDownload);
node.addPropertyResolver("webdavUrl", this.resolverLinkWebdavUrl);
node.addPropertyResolver("cifsPath", this.resolverLinkCifsPath);
node.addPropertyResolver("fileType16", this.resolverFileType16);
node.addPropertyResolver("fileType32", this.resolverFileType32);
node.addPropertyResolver("size", this.resolverSize);
node.addPropertyResolver("lang", this.resolverLang);
node.addPropertyResolver("path", this.resolverPath);
node.addPropertyResolver("displayPath", this.resolverDisplayPath);

this.contentNodes.add(node);
}
}
else if (ApplicationModel.TYPE_FOLDERLINK.equals(type))
{
// create our Folder Link Node representation
node = new MapNode(nodeRef, this.getNodeService(), false);
// only display the user has the permissions to navigate to the target of the link
NodeRef destRef = (NodeRef)node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
if (new Node(destRef).hasPermission(PermissionService.READ) == true)
{
node.addPropertyResolver("icon", this.resolverSpaceIcon);
node.addPropertyResolver("smallIcon", this.resolverSmallIcon);
node.addPropertyResolver("path", this.resolverPath);
node.addPropertyResolver("displayPath", this.resolverDisplayPath);

this.containerNodes.add(node);
}
}

// inform any listeners that a Node wrapper has been created
if (node != null)
{
for (NodeEventListener listener : nodeEventListeners)
{
listener.created(node, type);
}
}
}
else
{
if (logger.isWarnEnabled())
logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type);
}
}
else
{
if (logger.isWarnEnabled())
logger.warn("Missing object returned from search indexes: id = " + nodeRef + " search query: " + query);
}
}
}

// commit the transaction
tx.commit();
}
catch (InvalidNodeRefException refErr)
{
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] {refErr.getNodeRef()}), refErr );
this.containerNodes = Collections.emptyList();
this.contentNodes = Collections.emptyList();
try { if (tx != null) {tx.rollback();} } catch (Exception tex) {}
}
catch (SearcherException serr)
{
logger.info("Search failed for: " + query, serr);
Utils.addErrorMessage(Application.getMessage(
FacesContext.getCurrentInstance(), Repository.ERROR_QUERY));
this.containerNodes = Collections.emptyList();
this.contentNodes = Collections.emptyList();
try { if (tx != null) {tx.rollback();} } catch (Exception tex) {}
}
catch (Throwable err)
{
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(
FacesContext.getCurrentInstance(), Repository.ERROR_SEARCH), new Object[] {err.getMessage()}), err );
this.containerNodes = Collections.emptyList();
this.contentNodes = Collections.emptyList();
try { if (tx != null) {tx.rollback();} } catch (Exception tex) {}
}
finally
{
if (results != null)
{
results.close();
}
}

if (logger.isDebugEnabled())
{
long endTime = System.currentTimeMillis();
logger.debug("Time to query and build map nodes: " + (endTime - startTime) + "ms");
}
}



/**
* @return the Set of NodeEventListeners registered against this bean
*/
private Set getNodeEventListeners()
{
if ((this.nodeEventListeners == null) || (Application.isDynamicConfig(FacesContext.getCurrentInstance())))
{
Set allNodeEventListeners = new HashSet();

if (Application.isDynamicConfig(FacesContext.getCurrentInstance()) && (this.nodeEventListeners != null))
{
// for dynamic config, can add/remove node event listeners dynamically ...
// however, in case anyone is using public methods (add/removeNodeEventListener)
// we merge list here with list returned from the config
allNodeEventListeners.addAll(this.nodeEventListeners);
}

FacesContext fc = FacesContext.getCurrentInstance();
Config listenerConfig = Application.getConfigService(fc).getConfig("Node Event Listeners");
if (listenerConfig != null)
{
ConfigElement listenerElement = listenerConfig.getConfigElement("node-event-listeners");
if (listenerElement != null)
{
for (ConfigElement child : listenerElement.getChildren())
{
if (child.getName().equals("listener"))
{
// retrieved the JSF Managed Bean identified in the config
String listenerName = child.getValue().trim();
Object bean = FacesHelper.getManagedBean(fc, listenerName);
if (bean instanceof NodeEventListener)
{
allNodeEventListeners.add((NodeEventListener)bean);
}
}
}
}
}

if (Application.isDynamicConfig(FacesContext.getCurrentInstance()))
{
return allNodeEventListeners;
}
else
{
this.nodeEventListeners = allNodeEventListeners;
}
}
return this.nodeEventListeners;
}




/**
* Added code filter the folders not required
* @param name
* @return
*/
private boolean filterFoldes(String name){
boolean filter = false;

String user = AuthenticationUtil.getRunAsUser();
if(name.equals("Sites") || name.equals("Data Dictionary") || name.equals("User Homes") || name.equals("Guest Home")){
filter = true;
logger.debug("Removed the folders:::"+name);
}

if( authorityService.isAdminAuthority(user)){
logger.debug("Showing all the users since the user is admin");
filter = false;
}
return filter;

}


}

Thursday, January 20, 2011

Error Message in Dialg or Wizard

To pass the dynamic value to the error use below line

Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] { itemToWorkflowId }));
throw new AbortProcessingException("Invalid node reference");


To simply display the error message use below line
Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(),
"error_wizard_completed_already"));

Monday, January 17, 2011

Command to store and restore the DB in MYSQL

Open the command propmpt

First create the database by name alfrescotest

go to the location where your alfresco.sql is been stored which is been got from sqldump command and reun the below command
C:\Program Files\MySQL\MySQL Server 5.0\bin>mysql -u root -p alfrescotest < alfresco.sql

The command for exporting the databse is as below.
Open any location and run this command.

C:\Program Files\MySQL\MySQL Server 5.0\bin>mysqldump -u root -p alfresco > alfresco.sql

Friday, January 14, 2011

Folder structure in Share

D:\Alfresco3.3\tomcat\webapps\share

Inside webapps/share folder we have following folders

components
modules
templates
themes
yui

Basically these folders will have the css and javaScript, required by the modules
If you want change the look and feel then we have to touch these files.

For example if you take the example of creating the site then
C:\Alfresco3.4.3\tomcat\webapps\share\modules\create-site.js and C:\Alfresco3.4.3\tomcat\webapps\share\modules\create-site.css will be used.


The actual config files and logic will be available in the below folders.
D:\Alfresco3.3\tomcat\webapps\share\WEB-INF\classes\alfresco

site-webscripts : It will have the actaul webscript. WebScript response can be used as the dashlet by specifying the family, to use as user dashlet or site dashlet.


Alfresco uses the FormProcessor to do the validation of the fields,and changing the data from
our normal form to json format.

// Create the form that does the validation/submit
this.widgets.postForm = new Alfresco.forms.Form(this.id + "-form");
// To make the form submit json data
this.widgets.postForm.setSubmitAsJSON(true);


Page Component in Share

adasdasf

Folder Structure to be followed in Share for Dashlet

site-webscripts : This will have the ftl file, property file , description file and the controller file

site-welcome.get
site-welcome.get.desc
site-welcome.get.head.ftl
site-welcome.get.html.ftl



Configure custom dashlets
All of the dashlets provided by Alfresco Share are configured by using webscripts.
We just need to provide the family when configuring the webscripts.
Three families are available out of the box:
1. Site-dashlet
2. User-dashlet
3. Dashlet

If you want create new dashlet, just write the webscript which can be rendered by ftl. In the webscript mention the family to decide whether it is the dashlet to be available for the user or site or welcome page.

Property file in WebScript(Share)

if we write the code in ftl

${msg("header.featureBook")}




The property file should have the key as below

text.featureBook=Take a tour of some of the key features of the Alfresco Enterprise Content Management Implementation Book by Munwar Shariff.

Make sure the the names are as below

site-welcome.get.html.ftl
site-welcome.get.properties

By the name keys will be distinguished

Tuesday, January 11, 2011

Liferay And Alfresco Integration

1. Install Alfresco in port 9080, ftp 31
2. put the below lines in alfresco-global.properties

authentication.chain=alfrescoNtlm1:alfrescoNtlm,external1:external
external.authentication.proxyUserName=

For handling the authentication



In liferay
1. Change the catalina.properties inside conf folder to

shared.loader=${catalina.base}/shared/classes,${catalina.base}/shared/lib/*.jar
so that it will load the war file

2.Copy the webExtension folder to liferay tomcat/shared/classes/webextension
3. Now rename the sample file to shared-config-custom.xml and make sure the ports are correct

4. Now you should be able to acces

Monday, January 10, 2011

Alfresco Add Ons

Download the add on from the location

http://wiki.alfresco.com/wiki/Community_Edition_3.2_file_list

http://process.alfresco.com/ccdl/?file=release/community/build-2039/alfresco-community-office2003-addins-3.2.zip

Run throgh the wizard and install the plugin

Now open any Microsoft documents then you will be able to see the Addins tab in the
document

Now click on that and configure Alfresco by giving the correct userName and Password.

Now you can perform all the operations.