View Javadoc

1   /**
2    * Copyright 2005-2011 The Kuali Foundation
3    *
4    * Licensed under the Educational Community License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.opensource.org/licenses/ecl2.php
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.kuali.rice.kew.rule.web;
17  
18  import org.apache.commons.lang.StringUtils;
19  import org.apache.log4j.Logger;
20  import org.apache.struts.action.ActionForm;
21  import org.apache.struts.action.ActionForward;
22  import org.apache.struts.action.ActionMapping;
23  import org.kuali.rice.core.api.criteria.Predicate;
24  import org.kuali.rice.core.api.criteria.QueryByCriteria;
25  import org.kuali.rice.kew.doctype.bo.DocumentType;
26  import org.kuali.rice.kew.doctype.service.DocumentTypeService;
27  import org.kuali.rice.kew.engine.node.ProcessDefinitionBo;
28  import org.kuali.rice.kew.engine.node.RouteNode;
29  import org.kuali.rice.kew.engine.node.service.RouteNodeService;
30  import org.kuali.rice.kew.service.KEWServiceLocator;
31  import org.kuali.rice.kew.api.KewApiConstants;
32  import org.kuali.rice.kew.web.KewKualiAction;
33  import org.kuali.rice.kim.api.KimConstants;
34  import org.kuali.rice.kim.api.permission.Permission;
35  import org.kuali.rice.kim.api.permission.PermissionService;
36  import org.kuali.rice.kim.api.responsibility.Responsibility;
37  import org.kuali.rice.kim.api.responsibility.ResponsibilityService;
38  import org.kuali.rice.kim.api.role.Role;
39  import org.kuali.rice.kim.api.role.RoleService;
40  import org.kuali.rice.kim.api.services.KimApiServiceLocator;
41  import org.kuali.rice.kim.bo.impl.KimAttributes;
42  import org.kuali.rice.kim.impl.permission.PermissionBo;
43  import org.kuali.rice.kim.impl.permission.PermissionTemplateBo;
44  import org.kuali.rice.kim.impl.responsibility.ResponsibilityBo;
45  import org.kuali.rice.kns.service.DocumentHelperService;
46  import org.kuali.rice.kns.service.KNSServiceLocator;
47  import org.kuali.rice.kns.service.MaintenanceDocumentDictionaryService;
48  import org.kuali.rice.krad.service.DataDictionaryService;
49  import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
50  import org.kuali.rice.krad.util.GlobalVariables;
51  import org.kuali.rice.krad.util.KRADConstants;
52  
53  import javax.servlet.http.HttpServletRequest;
54  import javax.servlet.http.HttpServletResponse;
55  import java.util.ArrayList;
56  import java.util.Collections;
57  import java.util.HashMap;
58  import java.util.HashSet;
59  import java.util.LinkedHashMap;
60  import java.util.List;
61  import java.util.Map;
62  import java.util.Set;
63  
64  import static org.kuali.rice.core.api.criteria.PredicateFactory.*;
65  
66  
67  /**
68   * This is a description of what this class does - kellerj don't forget to fill this in. 
69   * 
70   * @author Kuali Rice Team (rice.collab@kuali.org)
71   *
72   */
73  public class DocumentConfigurationViewAction extends KewKualiAction {
74  
75  	private static final Logger LOG = Logger.getLogger(DocumentConfigurationViewAction.class);
76  	
77  	private PermissionService permissionService;
78  	private RoleService roleService;
79  	private ResponsibilityService responsibilityService;
80  	private DocumentTypeService documentTypeService;
81  	private DataDictionaryService dataDictionaryService;
82  	private RouteNodeService routeNodeService;
83  	private MaintenanceDocumentDictionaryService maintenanceDocumentDictionaryService;
84  	private DocumentHelperService documentHelperService;
85  	
86      public ActionForward start(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
87      	populateForm( (DocumentConfigurationViewForm)form );
88          return mapping.findForward("basic");
89      }
90      
91      protected void populateForm( DocumentConfigurationViewForm form ) {
92      	if ( StringUtils.isNotEmpty( form.getDocumentTypeName() ) ) {
93      		form.setDocumentType( getDocumentTypeService().findByName( form.getDocumentTypeName() ) ); 
94          	if ( form.getDocumentType() != null ) {
95  	    		form.getDocumentType().getChildrenDocTypes();
96  	    		form.setAttributeLabels( new HashMap<String, String>() );
97  	    		populateRelatedDocuments( form );
98  	    		populatePermissions( form );
99  	    		populateRoutingResponsibilities( form );
100 	    		populateRoutingExceptionResponsibility( form );
101 	    		checkPermissions( form );
102         	}
103     	}
104     }
105 
106     protected void checkPermissions( DocumentConfigurationViewForm form ) {
107     	String docTypeDocumentType = getMaintenanceDocumentDictionaryService().getDocumentTypeName(DocumentType.class);
108         try {
109             if ((docTypeDocumentType != null) && getDocumentHelperService().getDocumentAuthorizer(docTypeDocumentType).canInitiate(docTypeDocumentType, GlobalVariables.getUserSession().getPerson())) {
110                 form.setCanInitiateDocumentTypeDocument( true );
111             }
112         } catch (Exception ex) {
113 			// just skip - and don't display links
114         	LOG.error( "Unable to check DocumentType initiation permission for "+ docTypeDocumentType, ex );
115 		}
116     	String permissionDocumentType = getMaintenanceDocumentDictionaryService().getDocumentTypeName(PermissionBo.class);
117         try {
118             if ((permissionDocumentType != null) && getDocumentHelperService().getDocumentAuthorizer(permissionDocumentType).canInitiate(permissionDocumentType, GlobalVariables.getUserSession().getPerson())) {
119                 form.setCanInitiatePermissionDocument( true );
120             }
121         } catch (Exception ex) {
122 			// just skip - and don't display links
123         	LOG.error( "Unable to check Permission initiation permission for "+ permissionDocumentType, ex );
124 		}
125     	String responsibilityDocumentType = getMaintenanceDocumentDictionaryService().getDocumentTypeName(ResponsibilityBo.class);
126         try {
127             if ((responsibilityDocumentType != null) && getDocumentHelperService().getDocumentAuthorizer(responsibilityDocumentType).canInitiate(responsibilityDocumentType, GlobalVariables.getUserSession().getPerson())) {
128                 form.setCanInitiateResponsibilityDocument( true );
129             }
130         } catch (Exception ex) {
131 			// just skip - and don't display links
132         	LOG.error( "Unable to check Responsibility initiation permission for "+ responsibilityDocumentType, ex );
133 		}
134     }
135     
136     @SuppressWarnings("unchecked")
137 	public void populateRelatedDocuments( DocumentConfigurationViewForm form ) {
138     	form.setParentDocumentType( form.getDocumentType().getParentDocType() );
139     	form.setChildDocumentTypes( new ArrayList<DocumentType>( form.getDocumentType().getChildrenDocTypes() ) );
140     }
141     
142 	public void populatePermissions( DocumentConfigurationViewForm form ) {
143 		
144 		DocumentType docType = form.getDocumentType();
145 		Map<String,List<Role>> permRoles = new HashMap<String, List<Role>>();
146 		// loop over the document hierarchy
147 		Set<String> seenDocumentPermissions = new HashSet<String>();
148 		while ( docType != null) {
149 			String documentTypeName = docType.getName();
150             Predicate p = and(
151                 equal("active", "Y"),
152                 equal("attributes[" + KimConstants.AttributeConstants.DOCUMENT_TYPE_NAME + "]", docType.getName()));
153 			List<Permission> perms = getPermissionService().findPermissions(QueryByCriteria.Builder.fromPredicates(p)).getResults();
154 			for ( Permission perm : perms ) {
155                 PermissionBo permBo = PermissionBo.from(perm);
156 				List<String> roleIds = getPermissionService().getRoleIdsForPermission(perm.getNamespaceCode(),
157                         perm.getName(), Collections.<String, String>emptyMap());
158 				permRoles.put( perm.getId(), getRoleService().getRoles(roleIds) );
159 				for ( String attributeName : permBo.getDetails().keySet() ) {
160 					addAttributeLabel(form, attributeName);
161 				}
162 			}
163 			// show the section if the current document or permissions exist
164 			if ( perms.size() > 0 || documentTypeName.equals( form.getDocumentTypeName() ) ) {
165 				ArrayList<PermissionForDisplay> dispPerms = new ArrayList<PermissionForDisplay>( perms.size() );
166 				for ( Permission perm : perms ) {
167                     PermissionBo permBo = PermissionBo.from(perm);
168 					if ( permBo.getDetails().size() == 1  ) { // only the document type
169 						// this is a document type-specific permission, check if seen earlier
170 						if ( seenDocumentPermissions.contains(perm.getTemplate().getNamespaceCode()+"|"+perm.getTemplate().getName()) ) {
171 							dispPerms.add( new PermissionForDisplay( permBo, true ) );
172 						} else {
173 							dispPerms.add( new PermissionForDisplay( permBo, false ) );
174 							seenDocumentPermissions.add(perm.getTemplate().getNamespaceCode()+"|"+perm.getTemplate().getName());
175 						}
176 					} else {
177 						// other attributes, can't determine whether this is overridden at another level
178 						dispPerms.add( new PermissionForDisplay( permBo, false ) );
179 					}
180 				}
181 				form.setPermissionsForDocumentType(documentTypeName, dispPerms );
182 				form.addDocumentType(documentTypeName);
183 			}
184 			docType = docType.getParentDocType();			
185 		}
186 		
187 		form.setPermissionRoles( permRoles );
188 	}
189 	
190 	protected void populateRoutingExceptionResponsibility( DocumentConfigurationViewForm form ) {	
191 		DocumentType docType = form.getDocumentType();
192 		List<ResponsibilityForDisplay> responsibilities = new ArrayList<ResponsibilityForDisplay>();
193 		while ( docType != null) {
194             QueryByCriteria.Builder builder = QueryByCriteria.Builder.create();
195             Predicate p = and(
196                 equal("template.namespaceCode", KRADConstants.KUALI_RICE_WORKFLOW_NAMESPACE),
197                 equal("template.name", KewApiConstants.EXCEPTION_ROUTING_RESPONSIBILITY_TEMPLATE_NAME),
198                 equal("active", "Y"),
199                 equal("attributes[documentTypeName]", docType.getName())
200             );
201             builder.setPredicates(p);
202 			List<Responsibility> resps = getResponsibilityService().findResponsibilities(builder.build()).getResults();
203 			
204 			for ( Responsibility r : resps ) {
205 				if ( responsibilities.isEmpty() ) {
206 					responsibilities.add( new ResponsibilityForDisplay( r, false ) );
207 				} else {
208 					responsibilities.add( new ResponsibilityForDisplay( r, true ) );
209 				}
210 			}
211 			docType = docType.getParentDocType();			
212 		}
213 		form.setExceptionResponsibilities( responsibilities );
214 		for ( ResponsibilityForDisplay responsibility : responsibilities ) {
215 			List<String> roleIds = getResponsibilityService().getRoleIdsForResponsibility(responsibility.getResp().getId());
216 			form.getResponsibilityRoles().put( responsibility.getResponsibilityId(), getRoleService().getRoles(roleIds) );
217 		}
218 	}
219 
220 	protected void addAttributeLabel( DocumentConfigurationViewForm form, String attributeName ) {
221 		if ( !form.getAttributeLabels().containsKey(attributeName) ) {
222 			form.getAttributeLabels().put(attributeName, 
223 					getDataDictionaryService().getAttributeLabel(KimAttributes.class, attributeName) );
224 		}
225 	}
226 	
227 	// loop over nodes
228 	// if split node, push onto stack
229 		// note the number of children, this is the number of times the join node needs to be found
230 	// when join node found, return to last split on stack
231 		// move to next child of the split
232 	
233 	protected RouteNode flattenSplitNode( RouteNode splitNode, Map<String,RouteNode> nodes ) {
234 		nodes.put( splitNode.getRouteNodeName(), splitNode );
235 		RouteNode joinNode = null;
236 		
237 		for ( RouteNode nextNode : splitNode.getNextNodes() ) {
238 			joinNode = flattenRouteNodes(nextNode, nodes);
239 		}
240 		
241 		if ( joinNode != null ) {
242 			nodes.put( joinNode.getRouteNodeName(), joinNode );
243 		}
244 		return joinNode;
245 	}
246 	
247 	/**
248 	 * @param node
249 	 * @param nodes
250 	 * @return The last node processed by this method.
251 	 */
252 	protected RouteNode flattenRouteNodes( RouteNode node, Map<String,RouteNode> nodes ) {
253 		RouteNode lastProcessedNode = null;
254         if (node != null) {
255             // if we've seen the node before - skip, avoids infinite loop
256             if ( nodes.containsKey(node.getRouteNodeName()) ) {
257                 return node;
258             }
259 		
260             if ( node.getNodeType().contains( "SplitNode" ) ) { // Hacky - but only way when the class may not be present in the KEW JVM
261                 lastProcessedNode = flattenSplitNode(node, nodes); // special handling to process all split children before continuing
262                 // now, process the join node's children
263                 for ( RouteNode nextNode : lastProcessedNode.getNextNodes() ) {
264                     lastProcessedNode = flattenRouteNodes(nextNode, nodes);
265                 }
266             } else if ( node.getNodeType().contains( "JoinNode" ) ) {
267                 lastProcessedNode = node; // skip, handled by the split node
268             } else {
269                 // normal node, add to list and process all children
270                 nodes.put(node.getRouteNodeName(), node);
271                 for ( RouteNode nextNode : node.getNextNodes() ) {
272                     lastProcessedNode = flattenRouteNodes(nextNode, nodes);
273                 }
274             }
275         }
276 		return lastProcessedNode;
277 	}
278 	
279 	@SuppressWarnings("unchecked")
280 	public void populateRoutingResponsibilities( DocumentConfigurationViewForm form ) {
281 		// pull all the responsibilities
282 		// merge the data and attach to route levels
283 		// pull the route levels and store on form
284 		//List<RouteNode> routeNodes = getRouteNodeService().getFlattenedNodes(form.getDocumentType(), true);
285         Map<String,List<Role>> respToRoleMap = new HashMap<String, List<Role>>();
286         List<ProcessDefinitionBo> processes = (List<ProcessDefinitionBo>)form.getDocumentType().getProcesses();
287         if (!(processes.isEmpty())) {
288             RouteNode rootNode = processes.get(0).getInitialRouteNode();
289             LinkedHashMap<String, RouteNode> routeNodeMap = new LinkedHashMap<String, RouteNode>();
290             flattenRouteNodes(rootNode, routeNodeMap);
291 		
292             form.setRouteNodes( new ArrayList<RouteNode>( routeNodeMap.values() ) );
293             // pull all the responsibilities and store into a map for use by the JSP
294 		
295             // FILTER TO THE "Review" template only
296             // pull responsibility roles
297             DocumentType docType = form.getDocumentType();
298             Set<Responsibility> responsibilities = new HashSet<Responsibility>();
299             Map<String,List<ResponsibilityForDisplay>> nodeToRespMap = new LinkedHashMap<String, List<ResponsibilityForDisplay>>();
300             while ( docType != null) {
301                 QueryByCriteria.Builder builder = QueryByCriteria.Builder.create();
302                 Predicate p = and(
303                         equal("template.namespaceCode", KRADConstants.KUALI_RICE_WORKFLOW_NAMESPACE),
304                         equal("template.name", KewApiConstants.DEFAULT_RESPONSIBILITY_TEMPLATE_NAME),
305                         equal("active", "Y"),
306                         equal("attributes[documentTypeName]", docType.getName())
307                 );
308                 builder.setPredicates(p);
309                 List<Responsibility> resps = getResponsibilityService().findResponsibilities(builder.build()).getResults();
310 			
311                 for ( Responsibility r : resps ) {
312                     String routeNodeName = r.getAttributes().get(KimConstants.AttributeConstants.ROUTE_NODE_NAME);
313                     if ( StringUtils.isNotBlank(routeNodeName) ) {
314                         if ( !nodeToRespMap.containsKey( routeNodeName ) ) {
315                             nodeToRespMap.put(routeNodeName, new ArrayList<ResponsibilityForDisplay>() );
316                             nodeToRespMap.get(routeNodeName).add( new ResponsibilityForDisplay( r, false ) );
317                         } else {
318                             // check if the responsibility in the existing list is for the current document
319                             // if so, OK to add.  Otherwise, a lower level document has overridden this
320                             // responsibility (since we are walking up the hierarchy
321                             if ( nodeToRespMap.get(routeNodeName).get(0).getDetails().get( KimConstants.AttributeConstants.DOCUMENT_TYPE_NAME ).equals(docType.getName() ) ) {
322                                 nodeToRespMap.get(routeNodeName).add( new ResponsibilityForDisplay( r, false ) );
323                             } else { // doc type name did not match, mark as overridden
324                                 nodeToRespMap.get(routeNodeName).add( new ResponsibilityForDisplay( r, true ) );
325                             }
326                         }
327                         responsibilities.add(r);
328                     }
329                 }
330                 docType = docType.getParentDocType();			
331             }
332             form.setResponsibilityMap( nodeToRespMap );
333 		
334 		    for (Responsibility responsibility : responsibilities ) {
335 		        List<String> roleIds = getResponsibilityService().getRoleIdsForResponsibility(responsibility.getId());
336 		        respToRoleMap.put( responsibility.getId(), getRoleService().getRoles(roleIds) );
337 		    }
338         }
339 		form.setResponsibilityRoles( respToRoleMap );
340 	}
341 
342 	@Override
343 	public ActionForward toggleTab(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
344 		// Repopulating the form is necessary when toggling tab states on the server side.
345 		ActionForward actionForward = super.toggleTab(mapping, form, request, response);
346 		populateForm( (DocumentConfigurationViewForm)form );
347 		return actionForward;
348 	}
349 
350 	/**
351 	 * Internal delegate class to wrap a responsibility and add an overridden flag.
352 	 */
353 	public static class ResponsibilityForDisplay {
354 
355 		private Responsibility resp;
356 		private boolean overridden = false;
357 		
358 		public ResponsibilityForDisplay( Responsibility resp, boolean overridden ) {
359 			this.resp = resp;
360 			this.overridden = overridden;
361 		}
362 		
363 		/**
364 		 * @return the resp
365 		 */
366 		Responsibility getResp() {
367 			return this.resp;
368 		}
369 		
370 		public boolean isOverridden() {
371 			return this.overridden;
372 		}
373 
374 		public void setOverridden(boolean overridden) {
375 			this.overridden = overridden;
376 		}
377 
378 		public Map<String, String> getDetails() {
379 			return new HashMap<String, String>(this.resp.getAttributes());
380 		}
381 
382 		public String getName() {
383 			return this.resp.getName();
384 		}
385 
386 		public String getNamespaceCode() {
387 			return this.resp.getNamespaceCode();
388 		}
389 
390 		public String getResponsibilityId() {
391 			return this.resp.getId();
392 		}
393 	}
394 
395 	public static class PermissionForDisplay {
396 		private PermissionBo perm;
397 		private boolean overridden = false;
398 		
399 		public PermissionForDisplay( PermissionBo perm, boolean overridden ) {
400 			this.perm = perm;
401 			this.overridden = overridden;
402 		}
403 		public boolean isOverridden() {
404 			return this.overridden;
405 		}
406 
407 		public void setOverridden(boolean overridden) {
408 			this.overridden = overridden;
409 		}
410 		public Map<String, String> getDetails() {
411 			return this.perm.getDetails();
412 		}
413 		public String getName() {
414 			return this.perm.getName();
415 		}
416 		public String getNamespaceCode() {
417 			return this.perm.getNamespaceCode();
418 		}
419         public String getId() {
420             return this.perm.getId();
421         }
422 		public PermissionTemplateBo getTemplate() {
423 			return this.perm.getTemplate();
424 		}
425 		
426 	}
427 	
428 	/**
429 	 * @return the permissionService
430 	 */
431 	public PermissionService getPermissionService() {
432 		if ( permissionService == null ) {
433 			permissionService = KimApiServiceLocator.getPermissionService();
434 		}
435 		return permissionService;
436 	}
437 
438 	/**
439 	 * @return the roleService
440 	 */
441 	public RoleService getRoleService() {
442 		if ( roleService == null ) {
443 			roleService = KimApiServiceLocator.getRoleService();
444 		}
445 		return roleService;
446 	}
447 
448 	/**
449 	 * @return the responsibilityService
450 	 */
451 	public ResponsibilityService getResponsibilityService() {
452 		if ( responsibilityService == null ) {
453 			responsibilityService = KimApiServiceLocator.getResponsibilityService();
454 		}
455 		return responsibilityService;
456 	}
457 
458 	/**
459 	 * @return the documentTypeService
460 	 */
461 	public DocumentTypeService getDocumentTypeService() {
462 		if ( documentTypeService == null ) {
463 			documentTypeService = KEWServiceLocator.getDocumentTypeService();
464 		}
465 		return documentTypeService;
466 	}
467 
468 	public DataDictionaryService getDataDictionaryService() {
469 		if(dataDictionaryService == null){
470 			dataDictionaryService = KRADServiceLocatorWeb.getDataDictionaryService();
471 		}
472 		return dataDictionaryService;
473 	}
474 
475 	public RouteNodeService getRouteNodeService() {
476 		if ( routeNodeService == null ) {
477 			routeNodeService = KEWServiceLocator.getRouteNodeService();
478 		}
479 		return routeNodeService;
480 	}
481 
482 	public DocumentHelperService getDocumentHelperService() {
483 		if(documentHelperService == null){
484 			documentHelperService = KNSServiceLocator.getDocumentHelperService();
485 		}
486 		return documentHelperService;
487 	}
488 
489 	public MaintenanceDocumentDictionaryService getMaintenanceDocumentDictionaryService() {
490 		if(maintenanceDocumentDictionaryService == null){
491 			maintenanceDocumentDictionaryService = KNSServiceLocator.getMaintenanceDocumentDictionaryService();
492 		}
493 		return maintenanceDocumentDictionaryService;
494 	}
495 	
496 }