View Javadoc

1   /**
2    * Copyright 2005-2012 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());
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                 if (lastProcessedNode != null) {
264                     for ( RouteNode nextNode : lastProcessedNode.getNextNodes() ) {
265                         lastProcessedNode = flattenRouteNodes(nextNode, nodes);
266                     }
267                 }
268             } else if ( node.getNodeType().contains( "JoinNode" ) ) {
269                 lastProcessedNode = node; // skip, handled by the split node
270             } else {
271                 // normal node, add to list and process all children
272                 nodes.put(node.getRouteNodeName(), node);
273                 for ( RouteNode nextNode : node.getNextNodes() ) {
274                     lastProcessedNode = flattenRouteNodes(nextNode, nodes);
275                 }
276             }
277         }
278 		return lastProcessedNode;
279 	}
280 	
281 	@SuppressWarnings("unchecked")
282 	public void populateRoutingResponsibilities( DocumentConfigurationViewForm form ) {
283 		// pull all the responsibilities
284 		// merge the data and attach to route levels
285 		// pull the route levels and store on form
286 		//List<RouteNode> routeNodes = getRouteNodeService().getFlattenedNodes(form.getDocumentType(), true);
287         Map<String,List<Role>> respToRoleMap = new HashMap<String, List<Role>>();
288         List<ProcessDefinitionBo> processes = (List<ProcessDefinitionBo>)form.getDocumentType().getProcesses();
289         if (!(processes.isEmpty())) {
290             RouteNode rootNode = processes.get(0).getInitialRouteNode();
291             LinkedHashMap<String, RouteNode> routeNodeMap = new LinkedHashMap<String, RouteNode>();
292             flattenRouteNodes(rootNode, routeNodeMap);
293 		
294             form.setRouteNodes( new ArrayList<RouteNode>( routeNodeMap.values() ) );
295             // pull all the responsibilities and store into a map for use by the JSP
296 		
297             // FILTER TO THE "Review" template only
298             // pull responsibility roles
299             DocumentType docType = form.getDocumentType();
300             Set<Responsibility> responsibilities = new HashSet<Responsibility>();
301             Map<String,List<ResponsibilityForDisplay>> nodeToRespMap = new LinkedHashMap<String, List<ResponsibilityForDisplay>>();
302             while ( docType != null) {
303                 QueryByCriteria.Builder builder = QueryByCriteria.Builder.create();
304                 Predicate p = and(
305                         equal("template.namespaceCode", KRADConstants.KUALI_RICE_WORKFLOW_NAMESPACE),
306                         equal("template.name", KewApiConstants.DEFAULT_RESPONSIBILITY_TEMPLATE_NAME),
307                         equal("active", "Y"),
308                         equal("attributes[documentTypeName]", docType.getName())
309                 );
310                 builder.setPredicates(p);
311                 List<Responsibility> resps = getResponsibilityService().findResponsibilities(builder.build()).getResults();
312 			
313                 for ( Responsibility r : resps ) {
314                     String routeNodeName = r.getAttributes().get(KimConstants.AttributeConstants.ROUTE_NODE_NAME);
315                     if ( StringUtils.isNotBlank(routeNodeName) ) {
316                         if ( !nodeToRespMap.containsKey( routeNodeName ) ) {
317                             nodeToRespMap.put(routeNodeName, new ArrayList<ResponsibilityForDisplay>() );
318                             nodeToRespMap.get(routeNodeName).add( new ResponsibilityForDisplay( r, false ) );
319                         } else {
320                             // check if the responsibility in the existing list is for the current document
321                             // if so, OK to add.  Otherwise, a lower level document has overridden this
322                             // responsibility (since we are walking up the hierarchy
323                             if ( nodeToRespMap.get(routeNodeName).get(0).getDetails().get( KimConstants.AttributeConstants.DOCUMENT_TYPE_NAME ).equals(docType.getName() ) ) {
324                                 nodeToRespMap.get(routeNodeName).add( new ResponsibilityForDisplay( r, false ) );
325                             } else { // doc type name did not match, mark as overridden
326                                 nodeToRespMap.get(routeNodeName).add( new ResponsibilityForDisplay( r, true ) );
327                             }
328                         }
329                         responsibilities.add(r);
330                     }
331                 }
332                 docType = docType.getParentDocType();			
333             }
334             form.setResponsibilityMap( nodeToRespMap );
335 		
336 		    for (Responsibility responsibility : responsibilities ) {
337 		        List<String> roleIds = getResponsibilityService().getRoleIdsForResponsibility(responsibility.getId());
338 		        respToRoleMap.put( responsibility.getId(), getRoleService().getRoles(roleIds) );
339 		    }
340         }
341 		form.setResponsibilityRoles( respToRoleMap );
342 	}
343 
344 	@Override
345 	public ActionForward toggleTab(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
346 		// Repopulating the form is necessary when toggling tab states on the server side.
347 		ActionForward actionForward = super.toggleTab(mapping, form, request, response);
348 		populateForm( (DocumentConfigurationViewForm)form );
349 		return actionForward;
350 	}
351 
352 	/**
353 	 * Internal delegate class to wrap a responsibility and add an overridden flag.
354 	 */
355 	public static class ResponsibilityForDisplay {
356 
357 		private Responsibility resp;
358 		private boolean overridden = false;
359 		
360 		public ResponsibilityForDisplay( Responsibility resp, boolean overridden ) {
361 			this.resp = resp;
362 			this.overridden = overridden;
363 		}
364 		
365 		/**
366 		 * @return the resp
367 		 */
368 		Responsibility getResp() {
369 			return this.resp;
370 		}
371 		
372 		public boolean isOverridden() {
373 			return this.overridden;
374 		}
375 
376 		public void setOverridden(boolean overridden) {
377 			this.overridden = overridden;
378 		}
379 
380 		public Map<String, String> getDetails() {
381 			return new HashMap<String, String>(this.resp.getAttributes());
382 		}
383 
384 		public String getName() {
385 			return this.resp.getName();
386 		}
387 
388 		public String getNamespaceCode() {
389 			return this.resp.getNamespaceCode();
390 		}
391 
392 		public String getResponsibilityId() {
393 			return this.resp.getId();
394 		}
395 	}
396 
397 	public static class PermissionForDisplay {
398 		private PermissionBo perm;
399 		private boolean overridden = false;
400 		
401 		public PermissionForDisplay( PermissionBo perm, boolean overridden ) {
402 			this.perm = perm;
403 			this.overridden = overridden;
404 		}
405 		public boolean isOverridden() {
406 			return this.overridden;
407 		}
408 
409 		public void setOverridden(boolean overridden) {
410 			this.overridden = overridden;
411 		}
412 		public Map<String, String> getDetails() {
413 			return this.perm.getDetails();
414 		}
415 		public String getName() {
416 			return this.perm.getName();
417 		}
418 		public String getNamespaceCode() {
419 			return this.perm.getNamespaceCode();
420 		}
421         public String getId() {
422             return this.perm.getId();
423         }
424 		public PermissionTemplateBo getTemplate() {
425 			return this.perm.getTemplate();
426 		}
427 		
428 	}
429 	
430 	/**
431 	 * @return the permissionService
432 	 */
433 	public PermissionService getPermissionService() {
434 		if ( permissionService == null ) {
435 			permissionService = KimApiServiceLocator.getPermissionService();
436 		}
437 		return permissionService;
438 	}
439 
440 	/**
441 	 * @return the roleService
442 	 */
443 	public RoleService getRoleService() {
444 		if ( roleService == null ) {
445 			roleService = KimApiServiceLocator.getRoleService();
446 		}
447 		return roleService;
448 	}
449 
450 	/**
451 	 * @return the responsibilityService
452 	 */
453 	public ResponsibilityService getResponsibilityService() {
454 		if ( responsibilityService == null ) {
455 			responsibilityService = KimApiServiceLocator.getResponsibilityService();
456 		}
457 		return responsibilityService;
458 	}
459 
460 	/**
461 	 * @return the documentTypeService
462 	 */
463 	public DocumentTypeService getDocumentTypeService() {
464 		if ( documentTypeService == null ) {
465 			documentTypeService = KEWServiceLocator.getDocumentTypeService();
466 		}
467 		return documentTypeService;
468 	}
469 
470 	public DataDictionaryService getDataDictionaryService() {
471 		if(dataDictionaryService == null){
472 			dataDictionaryService = KRADServiceLocatorWeb.getDataDictionaryService();
473 		}
474 		return dataDictionaryService;
475 	}
476 
477 	public RouteNodeService getRouteNodeService() {
478 		if ( routeNodeService == null ) {
479 			routeNodeService = KEWServiceLocator.getRouteNodeService();
480 		}
481 		return routeNodeService;
482 	}
483 
484 	public DocumentHelperService getDocumentHelperService() {
485 		if(documentHelperService == null){
486 			documentHelperService = KNSServiceLocator.getDocumentHelperService();
487 		}
488 		return documentHelperService;
489 	}
490 
491 	public MaintenanceDocumentDictionaryService getMaintenanceDocumentDictionaryService() {
492 		if(maintenanceDocumentDictionaryService == null){
493 			maintenanceDocumentDictionaryService = KNSServiceLocator.getMaintenanceDocumentDictionaryService();
494 		}
495 		return maintenanceDocumentDictionaryService;
496 	}
497 	
498 }