KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > entityext > permission > EntityPermissionChecker


1 /*
2  * $Id: EntityPermissionChecker.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2003-2005 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 package org.ofbiz.entityext.permission;
26
27 import java.sql.Timestamp JavaDoc;
28 import java.util.ArrayList JavaDoc;
29 import java.util.Arrays JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.HashSet JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.List JavaDoc;
34 import java.util.ListIterator JavaDoc;
35 import java.util.Map JavaDoc;
36
37 import javax.servlet.http.HttpServletRequest JavaDoc;
38 import javax.servlet.http.HttpSession JavaDoc;
39
40 import org.ofbiz.base.util.Debug;
41 import org.ofbiz.base.util.StringUtil;
42 import org.ofbiz.base.util.UtilDateTime;
43 import org.ofbiz.base.util.UtilMisc;
44 import org.ofbiz.base.util.UtilValidate;
45 import org.ofbiz.base.util.UtilXml;
46 import org.ofbiz.base.util.string.FlexibleStringExpander;
47 import org.ofbiz.entity.GenericDelegator;
48 import org.ofbiz.entity.GenericEntityException;
49 import org.ofbiz.entity.GenericValue;
50 import org.ofbiz.entity.condition.EntityCondition;
51 import org.ofbiz.entity.condition.EntityConditionList;
52 import org.ofbiz.entity.condition.EntityExpr;
53 import org.ofbiz.entity.condition.EntityOperator;
54 import org.ofbiz.entity.model.ModelEntity;
55 import org.ofbiz.entity.util.EntityUtil;
56 import org.ofbiz.security.Security;
57 import org.ofbiz.service.ServiceUtil;
58 import org.w3c.dom.Element JavaDoc;
59
60
61 /**
62  * EntityPermissionChecker Class
63  *
64  * @author <a HREF="mailto:byersa@automationgroups.com">Al Byers</a>
65  * @version $Rev: 5462 $
66  * @since 3.1
67  *
68  * Services for granting operation permissions on Content entities in a data-driven manner.
69  */

70 public class EntityPermissionChecker {
71
72     public static final String JavaDoc module = EntityPermissionChecker.class.getName();
73
74     protected FlexibleStringExpander entityIdExdr;
75     protected FlexibleStringExpander entityNameExdr;
76     protected boolean displayFailCond;
77     protected List JavaDoc targetOperationList;
78     protected PermissionConditionGetter permissionConditionGetter;
79     protected RelatedRoleGetter relatedRoleGetter;
80     protected AuxiliaryValueGetter auxiliaryValueGetter;
81     
82     public EntityPermissionChecker(Element JavaDoc element) {
83         this.entityNameExdr = new FlexibleStringExpander(element.getAttribute("entity-name"));
84         this.entityIdExdr = new FlexibleStringExpander(element.getAttribute("entity-id"));
85         this.displayFailCond = "true".equals(element.getAttribute("display-fail-cond"));
86         Element JavaDoc permissionConditionElement = UtilXml.firstChildElement(element, "permission-condition-getter");
87         if (permissionConditionElement == null) {
88             permissionConditionGetter = new StdPermissionConditionGetter();
89         } else {
90             permissionConditionGetter = new StdPermissionConditionGetter(permissionConditionElement);
91         }
92         Element JavaDoc auxiliaryValueElement = UtilXml.firstChildElement(element, "auxiliary-value-getter");
93         if (auxiliaryValueElement == null) {
94             auxiliaryValueGetter = new StdAuxiliaryValueGetter();
95         } else {
96             auxiliaryValueGetter = new StdAuxiliaryValueGetter(auxiliaryValueElement);
97         }
98         Element JavaDoc relatedRoleElement = UtilXml.firstChildElement(element, "related-role-getter");
99         if (relatedRoleElement == null) {
100             relatedRoleGetter = new StdRelatedRoleGetter();
101         } else {
102             relatedRoleGetter = new StdRelatedRoleGetter(relatedRoleElement);
103         }
104         String JavaDoc targetOperationString = new String JavaDoc(element.getAttribute("target-operation"));
105         if (UtilValidate.isNotEmpty(targetOperationString)) {
106             List JavaDoc operationsFromString = StringUtil.split(targetOperationString, "|");
107             if (targetOperationList == null) {
108                 targetOperationList = new ArrayList JavaDoc();
109             }
110             targetOperationList.addAll(operationsFromString);
111         }
112         permissionConditionGetter.setOperationList(targetOperationList);
113
114         return;
115     }
116
117     public boolean runPermissionCheck(Map JavaDoc context) {
118         
119         boolean passed = false;
120         String JavaDoc idString = entityIdExdr.expandString(context);
121         List JavaDoc entityIdList = null;
122         if (UtilValidate.isNotEmpty(idString)) {
123             entityIdList = StringUtil.split(idString, "|");
124         } else {
125             entityIdList = new ArrayList JavaDoc();
126         }
127         String JavaDoc entityName = entityNameExdr.expandString(context);
128         HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc)context.get("request");
129         GenericValue userLogin = null;
130         String JavaDoc userLoginId = null;
131         String JavaDoc partyId = null;
132         GenericDelegator delegator = null;
133         if (request != null) {
134             HttpSession JavaDoc session = request.getSession();
135             userLogin = (GenericValue)session.getAttribute("userLogin");
136             if (userLogin != null) {
137                 userLoginId = userLogin.getString("userLoginId");
138                 partyId = userLogin.getString("partyId");
139             }
140            delegator = (GenericDelegator)request.getAttribute("delegator");
141         }
142         
143         if (auxiliaryValueGetter != null) auxiliaryValueGetter.clearList();
144         if (relatedRoleGetter != null) relatedRoleGetter.clearList();
145         try {
146             permissionConditionGetter.init(delegator);
147             passed = checkPermissionMethod(delegator, partyId, entityName, entityIdList, auxiliaryValueGetter, relatedRoleGetter, permissionConditionGetter);
148             if (!passed && displayFailCond) {
149                  String JavaDoc errMsg = "Permission is denied. \nThese are the conditions of which one must be met:\n"
150                      + permissionConditionGetter.dumpAsText();
151                  List JavaDoc errorMessageList = (List JavaDoc)context.get("errorMessageList");
152                  errorMessageList.add(errMsg);
153             }
154         } catch(GenericEntityException e) {
155             throw new RuntimeException JavaDoc(e.getMessage());
156         }
157         return passed;
158     }
159
160     public static Map JavaDoc checkPermission(GenericValue content, String JavaDoc statusId, GenericValue userLogin, List JavaDoc passedPurposes, List JavaDoc targetOperations, List JavaDoc passedRoles, GenericDelegator delegator , Security security, String JavaDoc entityAction) {
161          String JavaDoc privilegeEnumId = null;
162          return checkPermission( content, statusId,
163                                   userLogin, passedPurposes,
164                                   targetOperations, passedRoles,
165                                   delegator, security, entityAction, privilegeEnumId, null);
166     }
167
168     public static Map JavaDoc checkPermission(GenericValue content, String JavaDoc statusId,
169                                   GenericValue userLogin, List JavaDoc passedPurposes,
170                                   List JavaDoc targetOperations, List JavaDoc passedRoles,
171                                   GenericDelegator delegator ,
172                                   Security security, String JavaDoc entityAction,
173                                   String JavaDoc privilegeEnumId, String JavaDoc quickCheckContentId) {
174          List JavaDoc statusList = null;
175          if (statusId != null) {
176              statusList = StringUtil.split(statusId, "|");
177          }
178          return checkPermission( content, statusList,
179                                   userLogin, passedPurposes,
180                                   targetOperations, passedRoles,
181                                   delegator, security, entityAction, privilegeEnumId, quickCheckContentId);
182     }
183
184     public static Map JavaDoc checkPermission(GenericValue content, List JavaDoc statusList,
185                                   GenericValue userLogin, List JavaDoc passedPurposes,
186                                   List JavaDoc targetOperations, List JavaDoc passedRoles,
187                                   GenericDelegator delegator ,
188                                   Security security, String JavaDoc entityAction,
189                                   String JavaDoc privilegeEnumId) {
190          return checkPermission( content, statusList,
191                                   userLogin, passedPurposes,
192                                   targetOperations, passedRoles,
193                                   delegator, security, entityAction, privilegeEnumId, null);
194     }
195  
196     public static Map JavaDoc checkPermission(GenericValue content, List JavaDoc statusList,
197                                   GenericValue userLogin, List JavaDoc passedPurposes,
198                                   List JavaDoc targetOperations, List JavaDoc passedRoles,
199                                   GenericDelegator delegator ,
200                                   Security security, String JavaDoc entityAction,
201                                   String JavaDoc privilegeEnumId, String JavaDoc quickCheckContentId) {
202
203         String JavaDoc contentId = null;
204         if (content != null)
205             contentId = content.getString("contentId");
206         List JavaDoc entityIds = new ArrayList JavaDoc();
207         if (content != null)
208             entityIds.add(content);
209         if (UtilValidate.isNotEmpty(quickCheckContentId)) {
210             List JavaDoc quickList = StringUtil.split(quickCheckContentId, "|");
211            if (UtilValidate.isNotEmpty(quickList))
212                    entityIds.addAll(quickList);
213         }
214         Map JavaDoc results = new HashMap JavaDoc();
215         boolean passed = false;
216         if (userLogin != null && entityAction != null) {
217             passed = security.hasEntityPermission("CONTENTMGR", entityAction, userLogin);
218         }
219         if (passed) {
220             results.put("permissionStatus", "granted");
221             return results;
222         }
223         try {
224             boolean check = checkPermissionMethod( delegator, userLogin, targetOperations, "Content", entityIds, passedPurposes, null, privilegeEnumId);
225             if (check)
226                 results.put("permissionStatus", "granted");
227             else
228                 results.put("permissionStatus", "rejected");
229         } catch (GenericEntityException e) {
230             ServiceUtil.returnError(e.getMessage());
231         }
232         return results;
233     }
234     
235     
236     public static boolean checkPermissionMethod(GenericDelegator delegator, GenericValue userLogin, List JavaDoc targetOperationList, String JavaDoc entityName, List JavaDoc entityIdList, List JavaDoc purposeList, List JavaDoc roleList, String JavaDoc privilegeEnumId) throws GenericEntityException {
237     
238         boolean passed = false;
239     
240         String JavaDoc lcEntityName = entityName.toLowerCase();
241         String JavaDoc userLoginId = null;
242         String JavaDoc partyId = null;
243         if (userLogin != null) {
244             userLoginId = userLogin.getString("userLoginId");
245             partyId = userLogin.getString("partyId");
246         }
247         boolean hasRoleOperation = false;
248         if (!(targetOperationList == null) && userLoginId != null) {
249             hasRoleOperation = checkHasRoleOperations(partyId, targetOperationList, delegator);
250         }
251         if( hasRoleOperation ) {
252             return true;
253         }
254         ModelEntity modelEntity = delegator.getModelEntity(entityName);
255         boolean hasStatusField = false;
256         if (modelEntity.getField("statusId") != null)
257             hasStatusField = true;
258     
259         boolean hasPrivilegeField = false;
260         if (modelEntity.getField("privilegeEnumId") != null)
261             hasPrivilegeField = true;
262     
263         List JavaDoc operationEntities = null;
264         ModelEntity modelOperationEntity = delegator.getModelEntity(entityName + "PurposeOperation");
265         if (modelOperationEntity == null) {
266             modelOperationEntity = delegator.getModelEntity(entityName + "Operation");
267         }
268         
269         if (modelOperationEntity == null) {
270             Debug.logError("No operation entity found for " + entityName, module);
271             throw new RuntimeException JavaDoc("No operation entity found for " + entityName);
272         }
273         
274         boolean hasPurposeOp = false;
275         if (modelOperationEntity.getField(lcEntityName + "PurposeTypeId") != null)
276             hasPurposeOp = true;
277         boolean hasStatusOp = false;
278         if (modelOperationEntity.getField("statusId") != null)
279             hasStatusOp = true;
280         boolean hasPrivilegeOp = false;
281         if (modelOperationEntity.getField("privilegeEnumId") != null)
282              hasPrivilegeOp = true;
283         
284         // Get all the condition operations that could apply, rather than having to go thru
285
// entire table each time.
286
//List condList = new ArrayList();
287
//Iterator iterType = targetOperationList.iterator();
288
//while (iterType.hasNext()) {
289
// String op = (String)iterType.next();
290
// condList.add(new EntityExpr(lcEntityName + "OperationId", EntityOperator.EQUALS, op));
291
//}
292
//EntityCondition opCond = new EntityConditionList(condList, EntityOperator.OR);
293

294         EntityCondition opCond = new EntityExpr(lcEntityName + "OperationId", EntityOperator.IN, targetOperationList);
295         
296         List JavaDoc targetOperationEntityList = delegator.findByConditionCache(modelOperationEntity.getEntityName(), opCond, null, null);
297         Map JavaDoc entities = new HashMap JavaDoc();
298         String JavaDoc pkFieldName = modelEntity.getFirstPkFieldName();
299     
300         //TODO: privilegeEnumId test
301
/*
302         if (hasPrivilegeOp && hasPrivilegeField) {
303             int privilegeEnumSeq = -1;
304             
305             if ( UtilValidate.isNotEmpty(privilegeEnumId)) {
306                 GenericValue privEnum = delegator.findByPrimaryKeyCache("Enumeration", UtilMisc.toMap("enumId", privilegeEnumId));
307                 if (privEnum != null) {
308                     String sequenceId = privEnum.getString("sequenceId");
309                     try {
310                         privilegeEnumSeq = Integer.parseInt(sequenceId);
311                     } catch(NumberFormatException e) {
312                         // just leave it at -1
313                     }
314                 }
315             }
316             boolean thisPassed = true;
317             Iterator iter = entityIdList.iterator();
318             while (iter.hasNext()) {
319                 GenericValue entity = getNextEntity(delegator, entityName, pkFieldName, iter.next(), entities);
320                 if (entity == null) continue;
321                    
322                 String entityId = entity.getString(pkFieldName);
323                 String targetPrivilegeEnumId = entity.getString("privilegeEnumId");
324                 if (UtilValidate.isNotEmpty(targetPrivilegeEnumId)) {
325                     int targetPrivilegeEnumSeq = -1;
326                     GenericValue privEnum = delegator.findByPrimaryKeyCache("Enumeration", UtilMisc.toMap("enumId", privilegeEnumId));
327                     if (privEnum != null) {
328                         String sequenceId = privEnum.getString("sequenceId");
329                         try {
330                             targetPrivilegeEnumSeq = Integer.parseInt(sequenceId);
331                         } catch(NumberFormatException e) {
332                             // just leave it at -1
333                         }
334                         if (targetPrivilegeEnumSeq > privilegeEnumSeq) {
335                             return false;
336                         }
337                     }
338                 }
339                 entities.put(entityId, entity);
340             }
341         }
342         */

343         
344         // check permission for each id in passed list until success.
345
// Note that "quickCheck" id come first in the list
346
// Check with no roles or purposes on the chance that the permission fields contain _NA_ s.
347
List JavaDoc alreadyCheckedIds = new ArrayList JavaDoc();
348         Map JavaDoc purposes = new HashMap JavaDoc();
349         Map JavaDoc roles = new HashMap JavaDoc();
350         Iterator JavaDoc iter = entityIdList.iterator();
351         //List purposeList = null;
352
//List roleList = null;
353
while (iter.hasNext()) {
354                GenericValue entity = getNextEntity(delegator, entityName, pkFieldName, iter.next(), entities);
355              if (entity == null) continue;
356                    
357             String JavaDoc statusId = null;
358             if (hasStatusOp && hasStatusField) {
359                 statusId = entity.getString("statusId");
360             }
361             
362             int privilegeEnumSeq = -1;
363             if (hasPrivilegeOp && hasPrivilegeField) {
364                 privilegeEnumId = entity.getString("privilegeEnumId");
365                 privilegeEnumSeq = getPrivilegeEnumSeq(delegator, privilegeEnumId);
366             }
367                
368             passed = hasMatch(entityName, targetOperationEntityList, roleList, hasPurposeOp, purposeList, hasStatusOp, statusId);
369             if (passed) {
370                 break;
371             }
372        }
373         
374         if (passed) {
375             return true;
376         }
377         
378         if (hasPurposeOp) {
379             // Check with just purposes next.
380
iter = entityIdList.iterator();
381             while (iter.hasNext()) {
382                 GenericValue entity = getNextEntity(delegator, entityName, pkFieldName, iter.next(), entities);
383                 if (entity == null) continue;
384                  
385                 String JavaDoc entityId = entity.getString(pkFieldName);
386                 purposeList = getRelatedPurposes(entity, null);
387                 String JavaDoc statusId = null;
388                 if (hasStatusOp && hasStatusField) {
389                     statusId = entity.getString("statusId");
390                 }
391                 
392                 if (purposeList.size() > 0) {
393                     passed = hasMatch(entityName, targetOperationEntityList, roleList, hasPurposeOp, purposeList, hasStatusOp, statusId);
394                 }
395                 if (passed){
396                     break;
397                 }
398                 purposes.put(entityId, purposeList);
399             }
400         }
401         
402         if (passed)
403             return true;
404         
405         if (userLogin == null)
406             return false;
407     
408         // Check with roles.
409
iter = entityIdList.iterator();
410         while (iter.hasNext()) {
411             GenericValue entity = getNextEntity(delegator, entityName, pkFieldName, iter.next(), entities);
412             if (entity == null) continue;
413             String JavaDoc entityId = entity.getString(pkFieldName);
414             List JavaDoc tmpPurposeList = (List JavaDoc)purposes.get(entityId);
415             if (purposeList != null ) {
416                 if (tmpPurposeList != null) {
417                     purposeList.addAll(tmpPurposeList);
418                 }
419             } else {
420                 purposeList = tmpPurposeList;
421             }
422                 
423             List JavaDoc tmpRoleList = getUserRoles(entity, userLogin, delegator);
424             if (roleList != null ) {
425                 if (tmpRoleList != null) {
426                     roleList.addAll(tmpRoleList);
427                 }
428             } else {
429                 roleList = tmpRoleList;
430             }
431     
432             String JavaDoc statusId = null;
433             if (hasStatusOp && hasStatusField) {
434                 statusId = entity.getString("statusId");
435             }
436                
437             passed = hasMatch(entityName, targetOperationEntityList, roleList, hasPurposeOp, purposeList, hasStatusOp, statusId);
438             if (passed) {
439                 break;
440             }
441             roles.put(entityId, roleList);
442         }
443         
444         if (passed)
445             return true;
446         
447         // Follow ownedEntityIds
448
if (modelEntity.getField("owner" + entityName + "Id") != null) {
449             iter = entityIdList.iterator();
450             while (iter.hasNext()) {
451                 GenericValue entity = getNextEntity(delegator, entityName, pkFieldName, iter.next(), entities);
452                 if (entity == null) continue;
453                 
454                 String JavaDoc entityId = entity.getString(pkFieldName);
455                 List JavaDoc ownedContentIdList = new ArrayList JavaDoc();
456                 getEntityOwners(delegator, entity, ownedContentIdList, "Content", "ownerContentId");
457     
458                 List JavaDoc ownedContentRoleIds = getUserRolesFromList(delegator, ownedContentIdList, partyId, "contentId", "partyId", "roleTypeId", "ContentRole");
459                 String JavaDoc statusId = null;
460                 if (hasStatusOp && hasStatusField) {
461                     statusId = entity.getString("statusId");
462                 }
463                    
464                 purposeList = (List JavaDoc)purposes.get(entityId);
465                 passed = hasMatch(entityName, targetOperationEntityList, ownedContentRoleIds, hasPurposeOp, purposeList, hasStatusOp, statusId);
466                 if (passed) break;
467                
468                 /*
469                    String ownedEntityId = entity.getString("owner" + entityName + "Id");
470                    GenericValue ownedEntity = delegator.findByPrimaryKeyCache(entityName,UtilMisc.toMap(pkFieldName, ownedEntityId));
471                    while (ownedEntity != null) {
472                        if (!alreadyCheckedIds.contains(ownedEntityId)) {
473                         // Decided to let the original purposes only be used in permission checking
474                         //
475                         //purposeList = (List)purposes.get(entityId);
476                         //purposeList = getRelatedPurposes(ownedEntity, purposeList);
477                         roleList = getUserRoles(ownedEntity, userLogin, delegator);
478             
479                         String statusId = null;
480                         if (hasStatusOp && hasStatusField) {
481                             statusId = entity.getString("statusId");
482                         }
483                            
484                         passed = hasMatch(entityName, targetOperationEntityList, roleList, hasPurposeOp, purposeList, hasStatusOp, statusId);
485                         if (passed)
486                             break;
487                         alreadyCheckedIds.add(ownedEntityId);
488                        //purposes.put(ownedEntityId, purposeList);
489                         //roles.put(ownedEntityId, roleList);
490                            ownedEntityId = ownedEntity.getString("owner" + entityName + "Id");
491                            ownedEntity = delegator.findByPrimaryKeyCache(entityName,UtilMisc.toMap(pkFieldName, ownedEntityId));
492                        } else {
493                           ownedEntity = null;
494                        }
495                    }
496                    if (passed)
497                        break;
498                        */

499             }
500         }
501         
502         
503         /* seems like repeat
504         // Check parents
505         iter = entityIdList.iterator();
506         while (iter.hasNext()) {
507             String entityId = (String)iter.next();
508                GenericValue entity = (GenericValue)entities.get(entityId);
509             purposeList = (List)purposes.get(entityId);
510             roleList = getUserRoles(entity, userLogin, delegator);
511     
512             String statusId = null;
513             if (hasStatusOp && hasStatusField) {
514                 statusId = entity.getString("statusId");
515             }
516             String targetPrivilegeEnumId = null;
517             if (hasPrivilegeOp && hasPrivilegeField) {
518                 targetPrivilegeEnumId = entity.getString("privilegeEnumId");
519             }
520                
521             passed = hasMatch(entityName, targetOperationEntityList, roleList, hasPurposeOp, purposeList, hasStatusOp, statusId);
522             if (passed)
523                 break;
524             alreadyCheckedIds.add(entityId);
525         }
526         */

527         
528         return passed;
529     }
530     public static boolean checkPermissionMethod(GenericDelegator delegator, String JavaDoc partyId, String JavaDoc entityName, List JavaDoc entityIdList, AuxiliaryValueGetter auxiliaryValueGetter, RelatedRoleGetter relatedRoleGetter, PermissionConditionGetter permissionConditionGetter) throws GenericEntityException {
531     
532         permissionConditionGetter.init(delegator);
533         if (Debug.verboseOn()) Debug.logVerbose(permissionConditionGetter.dumpAsText(), module);
534         boolean passed = false;
535     
536         String JavaDoc lcEntityName = entityName.toLowerCase();
537         String JavaDoc userLoginId = null;
538         boolean checkAncestors = false;
539         boolean hasRoleOperation = checkHasRoleOperations(partyId, permissionConditionGetter, delegator);
540         if( hasRoleOperation ) {
541             return true;
542         }
543         ModelEntity modelEntity = delegator.getModelEntity(entityName);
544         
545         if (relatedRoleGetter != null) {
546             if (UtilValidate.isNotEmpty(partyId)) {
547                 relatedRoleGetter.setList(UtilMisc.toList("LOGGEDIN"));
548             }
549         }
550         
551         // check permission for each id in passed list until success.
552
// Note that "quickCheck" id come first in the list
553
// Check with no roles or purposes on the chance that the permission fields contain _NA_ s.
554
String JavaDoc pkFieldName = modelEntity.getFirstPkFieldName();
555         if (Debug.infoOn()) {
556         String JavaDoc entityIdString = "ENTITIES: ";
557         for (int i=0; i < entityIdList.size(); i++) {
558             Object JavaDoc obj = entityIdList.get(i);
559             if (obj instanceof GenericValue) {
560                 String JavaDoc s = ((GenericValue)obj).getString(pkFieldName);
561                 entityIdString += s + " ";
562             } else {
563                 entityIdString += obj + " ";
564             }
565         }
566             //if (Debug.infoOn()) Debug.logInfo(entityIdString, module);
567
}
568         
569         List JavaDoc alreadyCheckedIds = new ArrayList JavaDoc();
570         Map JavaDoc entities = new HashMap JavaDoc();
571         Iterator JavaDoc iter = entityIdList.iterator();
572         //List purposeList = null;
573
//List roleList = null;
574
while (iter.hasNext()) {
575             GenericValue entity = getNextEntity(delegator, entityName, pkFieldName, iter.next(), entities);
576             if (entity == null) continue;
577             checkAncestors = false;
578             passed = hasMatch(entity, permissionConditionGetter, relatedRoleGetter, null, partyId, checkAncestors);
579             if (passed) {
580                 break;
581             }
582        }
583         
584         if (passed) {
585             return true;
586         }
587         
588         if (auxiliaryValueGetter != null) {
589             //if (Debug.infoOn()) Debug.logInfo(auxiliaryValueGetter.dumpAsText(), module);
590
// Check with just purposes next.
591
iter = entityIdList.iterator();
592             while (iter.hasNext()) {
593                 GenericValue entity = getNextEntity(delegator, entityName, pkFieldName, iter.next(), entities);
594                 if (entity == null) continue;
595                 checkAncestors = false;
596                 passed = hasMatch(entity, permissionConditionGetter, relatedRoleGetter, auxiliaryValueGetter, partyId, checkAncestors);
597                  
598                 if (passed){
599                     break;
600                 }
601             }
602         }
603         
604         if (passed) return true;
605         
606         // TODO: need to return some information here about why it failed
607
if (partyId == null) return false;
608     
609         // Check with roles.
610
if (relatedRoleGetter != null) {
611             iter = entityIdList.iterator();
612             while (iter.hasNext()) {
613                 GenericValue entity = getNextEntity(delegator, entityName, pkFieldName, iter.next(), entities);
614                 if (entity == null) continue;
615                 checkAncestors = false;
616                 passed = hasMatch(entity, permissionConditionGetter, relatedRoleGetter, auxiliaryValueGetter, partyId, checkAncestors);
617                  
618                 if (passed){
619                     break;
620                 }
621             }
622         }
623         
624         if (passed)
625             return true;
626         
627         if (relatedRoleGetter != null) {
628             iter = entityIdList.iterator();
629             while (iter.hasNext()) {
630                 GenericValue entity = getNextEntity(delegator, entityName, pkFieldName, iter.next(), entities);
631                 if (entity == null) continue;
632                 String JavaDoc entityId = entity.getString(pkFieldName);
633                 checkAncestors = true;
634                 passed = hasMatch(entity, permissionConditionGetter, relatedRoleGetter, auxiliaryValueGetter, partyId, checkAncestors);
635                  
636                 if (passed){
637                     break;
638                 }
639             }
640         }
641         
642         
643         return passed;
644     }
645     
646     
647     public static GenericValue getNextEntity(GenericDelegator delegator, String JavaDoc entityName, String JavaDoc pkFieldName, Object JavaDoc obj, Map JavaDoc entities) throws GenericEntityException {
648            
649         GenericValue entity = null;
650         if (obj instanceof String JavaDoc) {
651             String JavaDoc entityId = (String JavaDoc)obj;
652             if (entities != null)
653                entity = (GenericValue)entities.get(entityId);
654             
655             if (entity == null)
656                 entity = delegator.findByPrimaryKeyCache(entityName,UtilMisc.toMap(pkFieldName, entityId));
657         } else if (obj instanceof GenericValue) {
658             entity = (GenericValue)obj;
659         }
660         return entity;
661     }
662     
663     public static boolean checkHasRoleOperations(String JavaDoc partyId, PermissionConditionGetter permissionConditionGetter , GenericDelegator delegator) {
664     
665         List JavaDoc targetOperations = permissionConditionGetter.getOperationList();
666         return checkHasRoleOperations(partyId, targetOperations, delegator);
667     }
668     
669     public static boolean checkHasRoleOperations(String JavaDoc partyId, List JavaDoc targetOperations, GenericDelegator delegator) {
670     
671         //if (Debug.infoOn()) Debug.logInfo("targetOperations:" + targetOperations, module);
672
//if (Debug.infoOn()) Debug.logInfo("userLoginId:" + userLoginId, module);
673
if (targetOperations == null)
674             return false;
675     
676         if (partyId != null && targetOperations.contains("HAS_USER_ROLE"))
677             return true;
678     
679         boolean hasRoleOperation = false;
680         Iterator JavaDoc targOpIter = targetOperations.iterator();
681         boolean hasNeed = false;
682         List JavaDoc newHasRoleList = new ArrayList JavaDoc();
683         while (targOpIter.hasNext()) {
684             String JavaDoc roleOp = (String JavaDoc)targOpIter.next();
685             int idx1 = roleOp.indexOf("HAS_");
686             if (idx1 == 0) {
687                 String JavaDoc roleOp1 = roleOp.substring(4); // lop off "HAS_"
688
int idx2 = roleOp1.indexOf("_ROLE");
689                 if (idx2 == (roleOp1.length() - 5)) {
690                     String JavaDoc roleOp2 = roleOp1.substring(0, roleOp1.indexOf("_ROLE") - 1); // lop off "_ROLE"
691
//if (Debug.infoOn()) Debug.logInfo("roleOp2:" + roleOp2, module);
692
newHasRoleList.add(roleOp2);
693                     hasNeed = true;
694                 }
695             }
696         }
697     
698         if (hasNeed) {
699             GenericValue uLogin = null;
700             try {
701                 if (UtilValidate.isNotEmpty(partyId)) {
702                     List JavaDoc partyRoleList = delegator.findByAndCache("PartyRole", UtilMisc.toMap("partyId", partyId));
703                     Iterator JavaDoc partyRoleIter = partyRoleList.iterator();
704                     while (partyRoleIter.hasNext()) {
705                         GenericValue partyRole = (GenericValue)partyRoleIter.next();
706                         String JavaDoc roleTypeId = partyRole.getString("roleTypeId");
707                         targOpIter = newHasRoleList.iterator();
708                         while (targOpIter.hasNext()) {
709                             String JavaDoc thisRole = (String JavaDoc)targOpIter.next();
710                             if (roleTypeId.indexOf(thisRole) >= 0) {
711                                 hasRoleOperation = true;
712                                 break;
713                             }
714                         }
715                         if (hasRoleOperation)
716                             break;
717                     }
718                 }
719             } catch (GenericEntityException e) {
720                 Debug.logError(e, module);
721                 return hasRoleOperation;
722             }
723         }
724         return hasRoleOperation;
725     }
726     
727     public static boolean hasMatch(String JavaDoc entityName, List JavaDoc targetOperations, List JavaDoc roles, boolean hasPurposeOp, List JavaDoc purposes, boolean hasStatusOp, String JavaDoc targStatusId) {
728         boolean isMatch = false;
729         int targPrivilegeSeq = 0;
730     // if (UtilValidate.isNotEmpty(targPrivilegeEnumId) && !targPrivilegeEnumId.equals("_NA_") && !targPrivilegeEnumId.equals("_00_") ) {
731
// need to do a lookup here to find the seq value of targPrivilegeEnumId.
732
// The lookup could be a static store or it could be done on Enumeration entity.
733
// }
734
String JavaDoc lcEntityName = entityName.toLowerCase();
735         Iterator JavaDoc targetOpsIter = targetOperations.iterator();
736         while (targetOpsIter.hasNext() ) {
737             GenericValue targetOp = (GenericValue)targetOpsIter.next();
738             String JavaDoc testRoleTypeId = (String JavaDoc)targetOp.get("roleTypeId");
739             String JavaDoc testContentPurposeTypeId = null;
740             if (hasPurposeOp)
741                 testContentPurposeTypeId = (String JavaDoc)targetOp.get(lcEntityName + "PurposeTypeId");
742             String JavaDoc testStatusId = null;
743             if (hasStatusOp)
744                 testStatusId = (String JavaDoc)targetOp.get("statusId");
745             //String testPrivilegeEnumId = null;
746
//if (hasPrivilegeOp)
747
//testPrivilegeEnumId = (String)targetOp.get("privilegeEnumId");
748
//int testPrivilegeSeq = 0;
749

750             boolean purposesCond = ( !hasPurposeOp || (purposes != null && purposes.contains(testContentPurposeTypeId) ) || testContentPurposeTypeId.equals("_NA_") );
751             boolean statusCond = ( !hasStatusOp || testStatusId.equals("_NA_") || (targStatusId != null && targStatusId.equals(testStatusId) ) );
752             //boolean privilegeCond = ( !hasPrivilegeOp || testPrivilegeEnumId.equals("_NA_") || testPrivilegeSeq <= targPrivilegeSeq || testPrivilegeEnumId.equals(targPrivilegeEnumId) );
753
boolean roleCond = ( testRoleTypeId.equals("_NA_") || (roles != null && roles.contains(testRoleTypeId) ) );
754     
755     
756             if (purposesCond && statusCond && roleCond) {
757                 
758                     isMatch = true;
759                     break;
760             }
761         }
762         return isMatch;
763     }
764     
765     public static boolean hasMatch(GenericValue entity, PermissionConditionGetter permissionConditionGetter, RelatedRoleGetter relatedRoleGetter, AuxiliaryValueGetter auxiliaryValueGetter, String JavaDoc partyId, boolean checkAncestors) throws GenericEntityException {
766     
767         String JavaDoc entityName = entity.getEntityName();
768         ModelEntity modelEntity = entity.getModelEntity();
769         GenericDelegator delegator = entity.getDelegator();
770         String JavaDoc pkFieldName = modelEntity.getFirstPkFieldName();
771         String JavaDoc entityId = entity.getString(pkFieldName);
772         if (Debug.verboseOn()) Debug.logVerbose("\n\nIN hasMatch: entityId:" + entityId + " partyId:" + partyId + " checkAncestors:" + checkAncestors, module);
773         boolean isMatch = false;
774         permissionConditionGetter.restart();
775         List JavaDoc auxiliaryValueList = null;
776         if (auxiliaryValueGetter != null) {
777            auxiliaryValueGetter.init(delegator, entityId);
778            auxiliaryValueList = auxiliaryValueGetter.getList();
779             if (Debug.verboseOn()) Debug.logVerbose(auxiliaryValueGetter.dumpAsText(), module);
780         } else {
781             if (Debug.verboseOn()) Debug.logVerbose("NO AUX GETTER", module);
782         }
783         List JavaDoc roleValueList = null;
784         if (relatedRoleGetter != null) {
785             if (checkAncestors) {
786                 relatedRoleGetter.initWithAncestors(delegator, entity, partyId);
787             } else {
788                 relatedRoleGetter.init(delegator, entityId, partyId, entity);
789             }
790             roleValueList = relatedRoleGetter.getList();
791             if (Debug.verboseOn()) Debug.logVerbose(relatedRoleGetter.dumpAsText(), module);
792         } else {
793             if (Debug.verboseOn()) Debug.logVerbose("NO ROLE GETTER", module);
794         }
795         
796         String JavaDoc targStatusId = null;
797         if (modelEntity.getField("statusId") != null) {
798             targStatusId = entity.getString("statusId");
799         }
800             if (Debug.verboseOn()) Debug.logVerbose("STATUS:" + targStatusId, module);
801         
802         while (permissionConditionGetter.getNext() ) {
803             String JavaDoc roleConditionId = permissionConditionGetter.getRoleValue();
804             String JavaDoc auxiliaryConditionId = permissionConditionGetter.getAuxiliaryValue();
805             String JavaDoc statusConditionId = permissionConditionGetter.getStatusValue();
806     
807             boolean auxiliaryCond = ( auxiliaryConditionId == null || auxiliaryConditionId.equals("_NA_") || (auxiliaryValueList != null && auxiliaryValueList.contains(auxiliaryConditionId) ) );
808             boolean statusCond = ( statusConditionId == null || statusConditionId.equals("_NA_") || (targStatusId != null && targStatusId.equals(statusConditionId) ) );
809             boolean roleCond = ( roleConditionId == null || roleConditionId.equals("_NA_") || (roleValueList != null && roleValueList.contains(roleConditionId) ) );
810     
811             if (auxiliaryCond && statusCond && roleCond) {
812                 if (Debug.verboseOn()) Debug.logVerbose("MATCHED: role:" + roleConditionId + " status:" + statusConditionId + " aux:" + auxiliaryConditionId, module);
813                     isMatch = true;
814                     break;
815             }
816         }
817         return isMatch;
818     }
819     
820     /**
821      * getRelatedPurposes
822      */

823     public static List JavaDoc getRelatedPurposes(GenericValue entity, List JavaDoc passedPurposes) {
824     
825         if(entity == null) return passedPurposes;
826     
827         List JavaDoc purposeIds = null;
828         if (passedPurposes == null) {
829             purposeIds = new ArrayList JavaDoc( );
830         } else {
831             purposeIds = new ArrayList JavaDoc( passedPurposes );
832         }
833     
834         String JavaDoc entityName = entity.getEntityName();
835         String JavaDoc lcEntityName = entityName.toLowerCase();
836     
837         List JavaDoc purposes = null;
838         try {
839             purposes = entity.getRelatedCache(entityName + "Purpose");
840         } catch (GenericEntityException e) {
841             Debug.logError(e, "No associated purposes found. ", module);
842             return purposeIds;
843         }
844     
845         Iterator JavaDoc purposesIter = purposes.iterator();
846         while (purposesIter.hasNext() ) {
847             GenericValue val = (GenericValue)purposesIter.next();
848             purposeIds.add(val.get(lcEntityName + "PurposeTypeId"));
849         }
850         
851     
852         return purposeIds;
853     }
854     
855     
856     /**
857      * getUserRoles
858      * Queries for the ContentRoles associated with a Content entity
859      * and returns the ones that match the user.
860      * Follows group parties to see if the user is a member.
861      */

862     public static List JavaDoc getUserRoles(GenericValue entity, GenericValue userLogin, GenericDelegator delegator) throws GenericEntityException {
863     
864         String JavaDoc entityName = entity.getEntityName();
865         List JavaDoc roles = new ArrayList JavaDoc();
866         if(entity == null) return roles;
867             // TODO: Need to use ContentManagementWorker.getAuthorContent first
868

869     
870         roles.remove("OWNER"); // always test with the owner of the current content
871
if ( entity.get("createdByUserLogin") != null && userLogin != null) {
872             String JavaDoc userLoginId = (String JavaDoc)userLogin.get("userLoginId");
873             String JavaDoc userLoginIdCB = (String JavaDoc)entity.get("createdByUserLogin");
874             //if (Debug.infoOn()) Debug.logInfo("userLoginId:" + userLoginId + ": userLoginIdCB:" + userLoginIdCB + ":", null);
875
if (userLoginIdCB.equals(userLoginId)) {
876                 roles.add("OWNER");
877                 //if (Debug.infoOn()) Debug.logInfo("in getUserRoles, passedRoles(0):" + passedRoles, null);
878
}
879         }
880         
881         String JavaDoc partyId = (String JavaDoc)userLogin.get("partyId");
882         List JavaDoc relatedRoles = null;
883         List JavaDoc tmpRelatedRoles = entity.getRelatedCache(entityName + "Role");
884         relatedRoles = EntityUtil.filterByDate(tmpRelatedRoles);
885         if(relatedRoles != null ) {
886             Iterator JavaDoc rolesIter = relatedRoles.iterator();
887             while (rolesIter.hasNext() ) {
888                 GenericValue contentRole = (GenericValue)rolesIter.next();
889                 String JavaDoc roleTypeId = (String JavaDoc)contentRole.get("roleTypeId");
890                 String JavaDoc targPartyId = (String JavaDoc)contentRole.get("partyId");
891                 if (targPartyId.equals(partyId)) {
892                     if (!roles.contains(roleTypeId))
893                         roles.add(roleTypeId);
894                     if (roleTypeId.equals("AUTHOR") && !roles.contains("OWNER"))
895                         roles.add("OWNER");
896                 } else { // Party may be of "PARTY_GROUP" type, in which case the userLogin may still possess this role
897
GenericValue party = null;
898                     String JavaDoc partyTypeId = null;
899                     try {
900                         party = contentRole.getRelatedOne("Party");
901                         partyTypeId = (String JavaDoc)party.get("partyTypeId");
902                         if ( partyTypeId != null && partyTypeId.equals("PARTY_GROUP") ) {
903                            HashMap JavaDoc map = new HashMap JavaDoc();
904                          
905                            // At some point from/thru date will need to be added
906
map.put("partyIdFrom", partyId);
907                            map.put("partyIdTo", targPartyId);
908                            if ( isGroupMember( map, delegator ) ) {
909                                if (!roles.contains(roleTypeId))
910                                    roles.add(roleTypeId);
911                            }
912                         }
913                     } catch (GenericEntityException e) {
914                         Debug.logError(e, "Error in finding related party. " + e.getMessage(), module);
915                     }
916                 }
917             }
918         }
919         return roles;
920     }
921     
922     
923     /**
924      * Tests to see if the user belongs to a group
925      */

926     public static boolean isGroupMember( Map JavaDoc partyRelationshipValues, GenericDelegator delegator ) {
927         boolean isMember = false;
928         String JavaDoc partyIdFrom = (String JavaDoc)partyRelationshipValues.get("partyIdFrom") ;
929         String JavaDoc partyIdTo = (String JavaDoc)partyRelationshipValues.get("partyIdTo") ;
930         String JavaDoc roleTypeIdFrom = "PERMISSION_GROUP_MBR";
931         String JavaDoc roleTypeIdTo = "PERMISSION_GROUP";
932         Timestamp JavaDoc fromDate = UtilDateTime.nowTimestamp();
933         Timestamp JavaDoc thruDate = UtilDateTime.getDayStart(UtilDateTime.nowTimestamp(), 1);
934     
935         if (partyRelationshipValues.get("roleTypeIdFrom") != null ) {
936             roleTypeIdFrom = (String JavaDoc)partyRelationshipValues.get("roleTypeIdFrom") ;
937         }
938         if (partyRelationshipValues.get("roleTypeIdTo") != null ) {
939             roleTypeIdTo = (String JavaDoc)partyRelationshipValues.get("roleTypeIdTo") ;
940         }
941         if (partyRelationshipValues.get("fromDate") != null ) {
942             fromDate = (Timestamp JavaDoc)partyRelationshipValues.get("fromDate") ;
943         }
944         if (partyRelationshipValues.get("thruDate") != null ) {
945             thruDate = (Timestamp JavaDoc)partyRelationshipValues.get("thruDate") ;
946         }
947     
948         EntityExpr partyFromExpr = new EntityExpr("partyIdFrom", EntityOperator.EQUALS, partyIdFrom);
949         EntityExpr partyToExpr = new EntityExpr("partyIdTo", EntityOperator.EQUALS, partyIdTo);
950        
951         EntityExpr relationExpr = new EntityExpr("partyRelationshipTypeId", EntityOperator.EQUALS,
952                                                        "CONTENT_PERMISSION");
953         //EntityExpr roleTypeIdFromExpr = new EntityExpr("roleTypeIdFrom", EntityOperator.EQUALS, "CONTENT_PERMISSION_GROUP_MEMBER");
954
//EntityExpr roleTypeIdToExpr = new EntityExpr("roleTypeIdTo", EntityOperator.EQUALS, "CONTENT_PERMISSION_GROUP");
955
EntityExpr fromExpr = new EntityExpr("fromDate", EntityOperator.LESS_THAN_EQUAL_TO,
956                                                        fromDate);
957         EntityCondition thruCond = new EntityConditionList(
958                         UtilMisc.toList(
959                             new EntityExpr("thruDate", EntityOperator.EQUALS, null),
960                             new EntityExpr("thruDate", EntityOperator.GREATER_THAN, thruDate) ),
961                         EntityOperator.OR);
962     
963         // This method is simplified to make it work, these conditions need to be added back in.
964
//List joinList = UtilMisc.toList(fromExpr, thruCond, partyFromExpr, partyToExpr, relationExpr);
965
List JavaDoc joinList = UtilMisc.toList( partyFromExpr, partyToExpr);
966         EntityCondition condition = new EntityConditionList(joinList, EntityOperator.AND);
967     
968         List JavaDoc partyRelationships = null;
969         try {
970             partyRelationships = delegator.findByCondition("PartyRelationship", condition, null, null);
971         } catch (GenericEntityException e) {
972             Debug.logError(e, "Problem finding PartyRelationships. ", module);
973             return false;
974         }
975         if (partyRelationships.size() > 0) {
976            isMember = true;
977         }
978     
979         return isMember;
980     }
981     
982     
983     public interface PermissionConditionGetter {
984         
985         public boolean getNext();
986         public String JavaDoc getRoleValue();
987         public String JavaDoc getOperationValue();
988         public String JavaDoc getStatusValue();
989         public int getPrivilegeValue() throws GenericEntityException;
990         public String JavaDoc getAuxiliaryValue();
991         public void init(GenericDelegator delegator) throws GenericEntityException;
992         public void restart();
993         public void setOperationList(String JavaDoc operationIdString);
994         public void setOperationList(List JavaDoc opList);
995         public List JavaDoc getOperationList();
996         public String JavaDoc dumpAsText();
997         public void clearList();
998     }
999     
1000    public static class StdPermissionConditionGetter implements PermissionConditionGetter {
1001    
1002        protected List JavaDoc entityList;
1003        protected List JavaDoc operationList;
1004        protected ListIterator JavaDoc iter;
1005        protected GenericValue currentValue;
1006        protected String JavaDoc operationFieldName;
1007        protected String JavaDoc roleFieldName;
1008        protected String JavaDoc statusFieldName;
1009        protected String JavaDoc privilegeFieldName;
1010        protected String JavaDoc auxiliaryFieldName;
1011        protected String JavaDoc entityName;
1012        
1013        public StdPermissionConditionGetter () {
1014            
1015            this.operationFieldName = "contentOperationId";
1016            this.roleFieldName = "roleTypeId";
1017            this.statusFieldName = "statusId";
1018            this.privilegeFieldName = "privilegeEnumId";
1019            this.auxiliaryFieldName = "contentPurposeTypeId";
1020            this.entityName = "ContentPurposeOperation";
1021        }
1022        
1023        public StdPermissionConditionGetter ( String JavaDoc entityName, String JavaDoc operationFieldName, String JavaDoc roleFieldName, String JavaDoc statusFieldName, String JavaDoc auxiliaryFieldName, String JavaDoc privilegeFieldName) {
1024            
1025            this.operationFieldName = operationFieldName;
1026            this.roleFieldName = roleFieldName ;
1027            this.statusFieldName = statusFieldName ;
1028            this.privilegeFieldName = privilegeFieldName ;
1029            this.auxiliaryFieldName = auxiliaryFieldName ;
1030            this.entityName = entityName;
1031        }
1032        
1033        public StdPermissionConditionGetter ( Element JavaDoc getterElement) {
1034            this.operationFieldName = getterElement.getAttribute("operation-field-name");
1035            this.roleFieldName = getterElement.getAttribute("role-field-name");
1036            this.statusFieldName = getterElement.getAttribute("status-field-name");
1037            this.privilegeFieldName = getterElement.getAttribute("privilege-field-name");
1038            this.auxiliaryFieldName = getterElement.getAttribute("auxiliary-field-name");
1039            this.entityName = getterElement.getAttribute("entity-name");
1040        }
1041        
1042        public boolean getNext() {
1043            boolean hasNext = false;
1044            if (iter != null && iter.hasNext()) {
1045                currentValue = (GenericValue)iter.next();
1046                hasNext = true;
1047            }
1048            return hasNext;
1049        }
1050        
1051        public String JavaDoc getRoleValue() {
1052            return this.currentValue.getString(this.roleFieldName);
1053        }
1054    
1055        public String JavaDoc getOperationValue() {
1056            return this.currentValue.getString(this.operationFieldName);
1057        }
1058        public String JavaDoc getStatusValue() {
1059            return this.currentValue.getString(this.statusFieldName);
1060            
1061        }
1062        public int getPrivilegeValue() throws GenericEntityException {
1063            int privilegeEnumSeq = -1;
1064            String JavaDoc privilegeEnumId = null;
1065            GenericDelegator delegator = currentValue.getDelegator();
1066            
1067            if (UtilValidate.isNotEmpty(privilegeFieldName)) {
1068                privilegeEnumId = currentValue.getString(this.privilegeFieldName);
1069            }
1070            if ( UtilValidate.isNotEmpty(privilegeEnumId)) {
1071                GenericValue privEnum = delegator.findByPrimaryKeyCache("Enumeration", UtilMisc.toMap("enumId", privilegeEnumId));
1072                if (privEnum != null) {
1073                    String JavaDoc sequenceId = privEnum.getString("sequenceId");
1074                    try {
1075                        privilegeEnumSeq = Integer.parseInt(sequenceId);
1076                    } catch(NumberFormatException JavaDoc e) {
1077                        // just leave it at -1
1078
}
1079                }
1080            }
1081            return privilegeEnumSeq;
1082            
1083        }
1084        
1085        public String JavaDoc getAuxiliaryValue() {
1086            return this.currentValue.getString(this.auxiliaryFieldName);
1087        }
1088        
1089        public void setOperationList(String JavaDoc operationIdString) {
1090            
1091            this.operationList = null;
1092            if (UtilValidate.isNotEmpty(operationIdString)) {
1093                this.operationList = StringUtil.split(operationIdString, "|");
1094            }
1095        }
1096        
1097        public void setOperationList(List JavaDoc operationList) {
1098            this.operationList = operationList;
1099        }
1100        
1101        public List JavaDoc getOperationList() {
1102            return this.operationList;
1103        }
1104        
1105        public void clearList() {
1106            this.entityList = new ArrayList JavaDoc();
1107        }
1108        
1109        public void init( GenericDelegator delegator) throws GenericEntityException {
1110            EntityCondition opCond = new EntityExpr(operationFieldName, EntityOperator.IN, this.operationList);
1111            this.entityList = delegator.findByConditionCache(this.entityName, opCond, null, null);
1112        }
1113        
1114        public void restart() {
1115            this.iter = null;
1116            if (this.entityList != null) {
1117                this.iter = this.entityList.listIterator();
1118            }
1119        }
1120    
1121        public String JavaDoc dumpAsText() {
1122             List JavaDoc fieldNames = UtilMisc.toList("roleFieldName", "auxiliaryFieldName", "statusFieldName");
1123             Map JavaDoc widths = UtilMisc.toMap("roleFieldName", new Integer JavaDoc(24), "auxiliaryFieldName", new Integer JavaDoc(24), "statusFieldName", new Integer JavaDoc(24));
1124             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
1125             Integer JavaDoc wid = null;
1126             
1127             buf.append("Dump for ");
1128             buf.append(this.entityName);
1129             buf.append(" ops:");
1130             buf.append(StringUtil.join(this.operationList, ","));
1131             buf.append("\n");
1132             Iterator JavaDoc itFields = fieldNames.iterator();
1133             while (itFields.hasNext()) {
1134                 String JavaDoc fld = (String JavaDoc)itFields.next();
1135                 wid = (Integer JavaDoc)widths.get(fld);
1136                 buf.append(fld);
1137                 for (int i=0; i < (wid.intValue() - fld.length()); i++) buf.append("^");
1138                 buf.append(" ");
1139             }
1140                     buf.append("\n");
1141             itFields = fieldNames.iterator();
1142             while (itFields.hasNext()) {
1143                 String JavaDoc fld = (String JavaDoc)itFields.next();
1144                 wid = (Integer JavaDoc)widths.get(fld);
1145                 for (int i=0; i < wid.intValue(); i++) buf.append("-");
1146                 buf.append(" ");
1147             }
1148                     buf.append("\n");
1149             if (entityList != null) {
1150                 Iterator JavaDoc it = this.entityList.iterator();
1151                 while (it.hasNext()) {
1152                     GenericValue contentPurposeOperation = (GenericValue)it.next();
1153                     /*
1154                     String contentOperationId = contentPurposeOperation.getString(this.operationFieldName);
1155                     if (UtilValidate.isEmpty(contentOperationId)) {
1156                         contentOperationId = "";
1157                     }
1158                     wid = (Integer)widths.get("operationFieldName");
1159                     buf.append(contentOperationId);
1160                     for (int i=0; i < (wid.intValue() - contentOperationId.length()); i++) buf.append("^");
1161                     buf.append(" ");
1162                     */

1163                     
1164                     String JavaDoc roleTypeId = contentPurposeOperation.getString(this.roleFieldName);
1165                     if (UtilValidate.isEmpty(roleTypeId)) {
1166                         roleTypeId = "";
1167                     }
1168                     wid = (Integer JavaDoc)widths.get("roleFieldName");
1169                     buf.append(roleTypeId);
1170                     for (int i=0; i < (wid.intValue() - roleTypeId.length()); i++) buf.append("^");
1171                     buf.append(" ");
1172                     
1173                     String JavaDoc auxiliaryFieldValue = contentPurposeOperation.getString(this.auxiliaryFieldName);
1174                     if (UtilValidate.isEmpty(auxiliaryFieldValue)) {
1175                         auxiliaryFieldValue = "";
1176                     }
1177                     wid = (Integer JavaDoc)widths.get("auxiliaryFieldName");
1178                     buf.append(auxiliaryFieldValue);
1179                     for (int i=0; i < (wid.intValue() - auxiliaryFieldValue.length()); i++) buf.append("^");
1180                     buf.append(" ");
1181                     
1182                     String JavaDoc statusId = contentPurposeOperation.getString(this.statusFieldName);
1183                     if (UtilValidate.isEmpty(statusId)) {
1184                         statusId = "";
1185                     }
1186                     buf.append(statusId);
1187                     /*
1188                     wid = (Integer)widths.get("statusFieldName");
1189                     for (int i=0; i < (wid.intValue() - statusId.length()); i++) buf.append(" ");
1190                     */

1191                     buf.append(" ");
1192                     
1193                     buf.append("\n");
1194                 }
1195             }
1196             return buf.toString();
1197        }
1198    }
1199    
1200    public interface AuxiliaryValueGetter {
1201        public void init(GenericDelegator delegator, String JavaDoc entityId) throws GenericEntityException;
1202        public List JavaDoc getList();
1203        public void clearList();
1204        public String JavaDoc dumpAsText();
1205    }
1206    
1207    public static class StdAuxiliaryValueGetter implements AuxiliaryValueGetter {
1208    
1209        protected List JavaDoc entityList = new ArrayList JavaDoc();
1210        protected String JavaDoc auxiliaryFieldName;
1211        protected String JavaDoc entityName;
1212        protected String JavaDoc entityIdName;
1213        
1214        public StdAuxiliaryValueGetter () {
1215            
1216            this.auxiliaryFieldName = "contentPurposeTypeId";
1217            this.entityName = "ContentPurpose";
1218            this.entityIdName = "contentId";
1219        }
1220        
1221        public StdAuxiliaryValueGetter ( String JavaDoc entityName, String JavaDoc auxiliaryFieldName, String JavaDoc entityIdName) {
1222            
1223            this.auxiliaryFieldName = auxiliaryFieldName ;
1224            this.entityName = entityName;
1225            this.entityIdName = entityIdName;
1226        }
1227        
1228        public StdAuxiliaryValueGetter ( Element JavaDoc getterElement) {
1229        
1230            this.auxiliaryFieldName = getterElement.getAttribute("auxiliary-field-name");
1231            this.entityName = getterElement.getAttribute("entity-name");
1232            this.entityIdName = getterElement.getAttribute("entity-id-name");
1233        }
1234        
1235        public List JavaDoc getList() {
1236            return entityList;
1237        }
1238        
1239        public void clearList() {
1240            this.entityList = new ArrayList JavaDoc();
1241        }
1242        
1243        public void setList(List JavaDoc lst) {
1244            this.entityList = lst;
1245        }
1246        
1247        public void init(GenericDelegator delegator, String JavaDoc entityId) throws GenericEntityException {
1248            
1249            if (this.entityList == null) {
1250               this.entityList = new ArrayList JavaDoc();
1251            }
1252            if (UtilValidate.isEmpty(this.entityName)) {
1253                return;
1254            }
1255            List JavaDoc values = delegator.findByAndCache(this.entityName, UtilMisc.toMap(this.entityIdName, entityId));
1256            Iterator JavaDoc iter = values.iterator();
1257            while (iter.hasNext()) {
1258                GenericValue entity = (GenericValue)iter.next();
1259                this.entityList.add(entity.getString(this.auxiliaryFieldName));
1260            }
1261        }
1262        
1263        public String JavaDoc dumpAsText() {
1264             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
1265             buf.append("AUXILIARY: ");
1266             if (entityList != null) {
1267                for (int i=0; i < entityList.size(); i++) {
1268                    String JavaDoc val = (String JavaDoc)entityList.get(i);
1269                    buf.append(val);
1270                    buf.append(" ");
1271                }
1272             }
1273             return buf.toString();
1274        }
1275    }
1276    
1277    public interface RelatedRoleGetter {
1278        public void init(GenericDelegator delegator, String JavaDoc entityId, String JavaDoc partyId, GenericValue entity) throws GenericEntityException;
1279        public void initWithAncestors(GenericDelegator delegator, GenericValue entity, String JavaDoc partyId) throws GenericEntityException;
1280        public List JavaDoc getList();
1281        public void clearList();
1282        public void setList(List JavaDoc lst);
1283        public String JavaDoc dumpAsText();
1284        public boolean isOwner(GenericValue entity, String JavaDoc targetPartyId);
1285    }
1286    
1287    public static class StdRelatedRoleGetter implements RelatedRoleGetter {
1288    
1289        protected List JavaDoc roleIdList = new ArrayList JavaDoc();
1290        protected String JavaDoc roleTypeFieldName;
1291        protected String JavaDoc partyFieldName;
1292        protected String JavaDoc entityName;
1293        protected String JavaDoc roleEntityIdName;
1294        protected String JavaDoc roleEntityName;
1295        protected String JavaDoc ownerEntityFieldName;
1296        
1297        public StdRelatedRoleGetter () {
1298            
1299            this.roleTypeFieldName = "roleTypeId";
1300            this.partyFieldName = "partyId";
1301            this.ownerEntityFieldName = "ownerContentId";
1302            this.entityName = "Content";
1303            this.roleEntityName = "ContentRole";
1304            this.roleEntityIdName = "contentId";
1305        }
1306        
1307        public StdRelatedRoleGetter ( String JavaDoc entityName, String JavaDoc roleTypeFieldName, String JavaDoc roleEntityIdName, String JavaDoc partyFieldName, String JavaDoc ownerEntityFieldName, String JavaDoc roleEntityName) {
1308            
1309            this.roleTypeFieldName = roleTypeFieldName ;
1310            this.partyFieldName = partyFieldName ;
1311            this.ownerEntityFieldName = ownerEntityFieldName ;
1312            this.entityName = entityName;
1313            this.roleEntityName = roleEntityName;
1314            this.roleEntityIdName = roleEntityIdName;
1315        }
1316        
1317        public StdRelatedRoleGetter ( Element JavaDoc getterElement) {
1318        
1319            this.roleTypeFieldName = getterElement.getAttribute("role-type-field-name");
1320            this.partyFieldName = getterElement.getAttribute("party-field-name");
1321            this.ownerEntityFieldName = getterElement.getAttribute("owner-entity-field-name");
1322            this.entityName = getterElement.getAttribute("entity-name");
1323            this.roleEntityName = getterElement.getAttribute("role-entity-name");
1324            this.roleEntityIdName = getterElement.getAttribute("entity-id-name");
1325        }
1326        
1327        public List JavaDoc getList() {
1328            return this.roleIdList;
1329        }
1330        
1331        public void clearList() {
1332            this.roleIdList = new ArrayList JavaDoc();
1333        }
1334        
1335        public void setList(List JavaDoc lst) {
1336            this.roleIdList = lst;
1337        }
1338        
1339        public void init(GenericDelegator delegator, String JavaDoc entityId, String JavaDoc partyId, GenericValue entity) throws GenericEntityException {
1340            
1341            List JavaDoc lst = getUserRolesFromList(delegator, UtilMisc.toList(entityId), partyId, this.roleEntityIdName,
1342                                               this.partyFieldName, this.roleTypeFieldName, this.roleEntityName);
1343            this.roleIdList.addAll(lst);
1344            if (isOwner(entity, partyId)) {
1345                this.roleIdList.add("OWNER");
1346            }
1347           return;
1348        }
1349        
1350        public void initWithAncestors(GenericDelegator delegator, GenericValue entity, String JavaDoc partyId) throws GenericEntityException {
1351            
1352           List JavaDoc ownedContentIdList = new ArrayList JavaDoc();
1353           getEntityOwners(delegator, entity, ownedContentIdList, this.entityName, this.ownerEntityFieldName);
1354           if (ownedContentIdList.size() > 0) {
1355               List JavaDoc lst = getUserRolesFromList(delegator, ownedContentIdList, partyId, this.roleEntityIdName, this.partyFieldName, this.roleTypeFieldName, this.roleEntityName);
1356               this.roleIdList.addAll(lst);
1357           }
1358           return;
1359        }
1360        
1361        public boolean isOwner( GenericValue entity, String JavaDoc targetPartyId) {
1362            boolean isOwner = false;
1363            if (entity == null || targetPartyId == null) {
1364                return false;
1365            }
1366            GenericDelegator delegator = entity.getDelegator();
1367            ModelEntity modelEntity = delegator.getModelEntity(entityName);
1368            if (modelEntity.getField("createdByUserLogin") == null) {
1369                return false;
1370            }
1371            if ( entity.get("createdByUserLogin") != null) {
1372                String JavaDoc userLoginIdCB = (String JavaDoc)entity.get("createdByUserLogin");
1373                try {
1374                    GenericValue userLogin = delegator.findByPrimaryKeyCache("UserLogin", UtilMisc.toMap("userLoginId", userLoginIdCB ));
1375                    if (userLogin != null) {
1376                        String JavaDoc partyIdCB = userLogin.getString("partyId");
1377                        if (partyIdCB != null) {
1378                            if (partyIdCB.equals(targetPartyId)) {
1379                                isOwner = true;
1380                            }
1381                        }
1382                    }
1383                } catch(GenericEntityException e) {
1384                    Debug.logInfo(e.getMessage() + " Returning false for 'isOwner'.", module);
1385                       
1386                }
1387            }
1388            return isOwner;
1389        }
1390        
1391        public String JavaDoc dumpAsText() {
1392             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
1393             buf.append("ROLES: ");
1394             if (roleIdList != null) {
1395                for (int i=0; i < roleIdList.size(); i++) {
1396                    String JavaDoc val = (String JavaDoc)roleIdList.get(i);
1397                    buf.append(val);
1398                    buf.append(" ");
1399                }
1400             }
1401             return buf.toString();
1402        }
1403    }
1404
1405    public static List JavaDoc getUserRolesFromList(GenericDelegator delegator, List JavaDoc idList, String JavaDoc partyId, String JavaDoc entityIdFieldName, String JavaDoc partyIdFieldName, String JavaDoc roleTypeIdFieldName, String JavaDoc entityName) throws GenericEntityException {
1406        
1407        EntityExpr expr = new EntityExpr(entityIdFieldName, EntityOperator.IN, idList);
1408        EntityExpr expr2 = new EntityExpr(partyIdFieldName, EntityOperator.EQUALS, partyId);
1409        EntityConditionList condList = new EntityConditionList(UtilMisc.toList(expr, expr2), EntityOperator.AND);
1410        List JavaDoc roleList = delegator.findByConditionCache(entityName, condList, null, null);
1411        List JavaDoc roleListFiltered = EntityUtil.filterByDate(roleList);
1412        HashSet JavaDoc distinctSet = new HashSet JavaDoc();
1413        Iterator JavaDoc iter = roleListFiltered.iterator();
1414        while (iter.hasNext()) {
1415            GenericValue contentRole = (GenericValue)iter.next();
1416            String JavaDoc roleTypeId = contentRole.getString(roleTypeIdFieldName);
1417            distinctSet.add(roleTypeId);
1418        }
1419        List JavaDoc distinctList = Arrays.asList(distinctSet.toArray());
1420        return distinctList;
1421    }
1422
1423    public static void getEntityOwners(GenericDelegator delegator, GenericValue entity, List JavaDoc contentOwnerList, String JavaDoc entityName, String JavaDoc ownerIdFieldName) throws GenericEntityException {
1424
1425        String JavaDoc ownerContentId = entity.getString(ownerIdFieldName);
1426        if (UtilValidate.isNotEmpty(ownerContentId)) {
1427            contentOwnerList.add(ownerContentId);
1428            ModelEntity modelEntity = delegator.getModelEntity(entityName);
1429            String JavaDoc pkFieldName = modelEntity.getFirstPkFieldName();
1430            GenericValue ownerContent = delegator.findByPrimaryKeyCache(entityName, UtilMisc.toMap(pkFieldName, ownerContentId));
1431            if (ownerContent != null) {
1432                getEntityOwners(delegator, ownerContent, contentOwnerList, entityName, ownerIdFieldName );
1433            }
1434        }
1435        return;
1436    }
1437
1438    public static int getPrivilegeEnumSeq(GenericDelegator delegator, String JavaDoc privilegeEnumId) throws GenericEntityException {
1439        int privilegeEnumSeq = -1;
1440        
1441        if ( UtilValidate.isNotEmpty(privilegeEnumId)) {
1442            GenericValue privEnum = delegator.findByPrimaryKeyCache("Enumeration", UtilMisc.toMap("enumId", privilegeEnumId));
1443            if (privEnum != null) {
1444                String JavaDoc sequenceId = privEnum.getString("sequenceId");
1445                try {
1446                    privilegeEnumSeq = Integer.parseInt(sequenceId);
1447                } catch(NumberFormatException JavaDoc e) {
1448                    // just leave it at -1
1449
}
1450            }
1451        }
1452        return privilegeEnumSeq;
1453    }
1454}
1455
Popular Tags