KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jaspersoft > jasperserver > api > metadata > user > service > impl > ObjectPermissionServiceImpl


1 /*
2  * Copyright (C) 2006 JasperSoft http://www.jaspersoft.com
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed WITHOUT ANY WARRANTY; and without the
10  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11  * See the GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, see http://www.gnu.org/licenses/gpl.txt
15  * or write to:
16  *
17  * Free Software Foundation, Inc.,
18  * 59 Temple Place - Suite 330,
19  * Boston, MA USA 02111-1307
20  */

21
22 package com.jaspersoft.jasperserver.api.metadata.user.service.impl;
23
24 import java.util.ArrayList JavaDoc;
25 import java.util.Collection JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.Map JavaDoc;
30
31 import org.acegisecurity.Authentication;
32 import org.acegisecurity.acl.AclEntry;
33 import org.acegisecurity.acl.AclProvider;
34 import org.acegisecurity.acl.basic.AclObjectIdentity;
35 import org.acegisecurity.acl.basic.BasicAclDao;
36 import org.acegisecurity.acl.basic.BasicAclEntry;
37 import org.acegisecurity.acl.basic.BasicAclEntryCache;
38 import org.acegisecurity.acl.basic.EffectiveAclsResolver;
39 import org.acegisecurity.acl.basic.GrantedAuthorityEffectiveAclsResolver;
40 import org.acegisecurity.acl.basic.SimpleAclEntry;
41 import org.acegisecurity.acl.basic.cache.NullAclEntryCache;
42 import org.apache.commons.lang.builder.EqualsBuilder;
43 import org.apache.commons.lang.builder.HashCodeBuilder;
44 import org.apache.commons.lang.builder.ToStringBuilder;
45 import org.apache.commons.logging.Log;
46 import org.apache.commons.logging.LogFactory;
47 import org.hibernate.Hibernate;
48 import org.hibernate.HibernateException;
49 import org.hibernate.Query;
50 import org.hibernate.Session;
51 import org.springframework.beans.BeansException;
52 import org.springframework.beans.factory.InitializingBean;
53 import org.springframework.context.ApplicationContext;
54 import org.springframework.context.ApplicationContextAware;
55 import org.springframework.orm.hibernate3.HibernateCallback;
56
57 import com.jaspersoft.jasperserver.api.JSException;
58 import com.jaspersoft.jasperserver.api.common.domain.ExecutionContext;
59 import com.jaspersoft.jasperserver.api.metadata.common.domain.Folder;
60 import com.jaspersoft.jasperserver.api.metadata.common.domain.InternalURI;
61 import com.jaspersoft.jasperserver.api.metadata.common.domain.Resource;
62 import com.jaspersoft.jasperserver.api.metadata.common.domain.impl.IdedObject;
63 import com.jaspersoft.jasperserver.api.metadata.common.service.RepositoryEventListener;
64 import com.jaspersoft.jasperserver.api.metadata.common.service.ResourceFactory;
65 import com.jaspersoft.jasperserver.api.metadata.common.service.impl.HibernateDaoImpl;
66 import com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryService;
67 import com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.PersistentObjectResolver;
68 import com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.ReferenceResolver;
69 import com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.persistent.RepoResource;
70 import com.jaspersoft.jasperserver.api.metadata.user.domain.ObjectPermission;
71 import com.jaspersoft.jasperserver.api.metadata.user.domain.Role;
72 import com.jaspersoft.jasperserver.api.metadata.user.domain.User;
73 import com.jaspersoft.jasperserver.api.metadata.user.domain.impl.hibernate.RepoObjectPermission;
74 import com.jaspersoft.jasperserver.api.metadata.user.domain.impl.hibernate.RepoUser;
75 import com.jaspersoft.jasperserver.api.metadata.user.service.ObjectPermissionService;
76 import com.jaspersoft.jasperserver.api.metadata.user.service.UserAuthorityService;
77
78 /**
79  *
80  * @author swood
81  *
82  */

83 public class ObjectPermissionServiceImpl extends HibernateDaoImpl implements
84                 BasicAclDao, AclProvider, AclService, ObjectPermissionService,
85                 RepositoryEventListener, ApplicationContextAware, PersistentObjectResolver, InitializingBean {
86
87     //
88

89     protected static final Log log = LogFactory.getLog(ObjectPermissionServiceImpl.class);
90     public static final String JavaDoc RECIPIENT_USED_FOR_INHERITANCE_MARKER = "___INHERITANCE_MARKER_ONLY___";
91
92     /**
93      * Marker added to the cache to indicate an AclObjectIdentity has no
94      * corresponding BasicAclEntry[]s
95      */

96     private static String JavaDoc RECIPIENT_FOR_CACHE_EMPTY = "RESERVED_RECIPIENT_NOBODY";
97
98     private HibernateRepositoryService repoService;
99     private UserAuthorityService userService;
100
101     private ResourceFactory objectFactory;
102     private ResourceFactory persistentClassFactory;
103
104     private BasicAclEntryCache basicAclEntryCache = new NullAclEntryCache();
105     private EffectiveAclsResolver effectiveAclsResolver = new GrantedAuthorityEffectiveAclsResolver();
106
107     private ApplicationContext appContext;
108     
109     /**
110      * @return Returns the repoService.
111      */

112     public HibernateRepositoryService getRepositoryService() {
113         return repoService;
114     }
115
116     /**
117      * @param repoService The repoService to set.
118      */

119     public void setRepositoryService(HibernateRepositoryService repoService) {
120         this.repoService = repoService;
121     }
122
123     /**
124      * @return Returns the userService.
125      */

126     public UserAuthorityService getUserAuthorityService() {
127         return userService;
128     }
129
130     /**
131      * @param userService The userService to set.
132      */

133     public void setUserAuthorityService(UserAuthorityService userService) {
134         this.userService = userService;
135     }
136
137     public ResourceFactory getObjectMappingFactory() {
138         return objectFactory;
139     }
140
141     public void setObjectMappingFactory(ResourceFactory objectFactory) {
142         this.objectFactory = objectFactory;
143     }
144
145     public ResourceFactory getPersistentClassFactory() {
146         return persistentClassFactory;
147     }
148
149     public void setPersistentClassFactory(ResourceFactory persistentClassFactory) {
150         this.persistentClassFactory = persistentClassFactory;
151     }
152
153     public void setBasicAclEntryCache(BasicAclEntryCache basicAclEntryCache) {
154         this.basicAclEntryCache = basicAclEntryCache;
155     }
156
157     public BasicAclEntryCache getBasicAclEntryCache() {
158         return basicAclEntryCache;
159     }
160
161     /**
162      * @return Returns the effectiveAclsResolver.
163      */

164     public EffectiveAclsResolver getEffectiveAclsResolver() {
165         return effectiveAclsResolver;
166     }
167
168     /**
169      * @param effectiveAclsResolver The effectiveAclsResolver to set.
170      */

171     public void setEffectiveAclsResolver(EffectiveAclsResolver effectiveAclsResolver) {
172         this.effectiveAclsResolver = effectiveAclsResolver;
173     }
174
175     /* (non-Javadoc)
176      * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
177      */

178     public void setApplicationContext(ApplicationContext arg0) throws BeansException {
179         // Not needed really?
180
appContext = arg0;
181     }
182
183     /**
184      * Returns the ACLs associated with the requested
185      * <code>AclObjectIdentity</code>.
186      *
187      * <P>
188      * The {@link BasicAclEntry}s returned by this method will have
189      * <code>String</code>-based recipients. This will not be a problem if you
190      * are using the <code>GrantedAuthorityEffectiveAclsResolver</code>, which
191      * is the default configured against <code>BasicAclProvider</code>.
192      * </p>
193      *
194      * @param aclObjectIdentity for which ACL information is required (cannot
195      * be <code>null</code>)
196      *
197      * @return the ACLs that apply (without any <code>null</code>s inside the
198      * array), or <code>null</code> if not found or if an incompatible
199      * <code>AclObjectIdentity</code> was requested
200      */

201     public BasicAclEntry[] getAcls(InternalURI targetURI) {
202         if (targetURI == null) {
203             logger.debug("getAcls(InternalURI targetURI): returning. null targetURI");
204             return null;
205         }
206         Map JavaDoc map = new HashMap JavaDoc();
207
208         // Look in cache by targetURI.getURI for BasicAclEntry[]
209

210         BasicAclEntry[] instanceAclEntries = lookup(targetURI.getURI());
211
212         // Exit if there is no ACL information or parent for this instance
213
if (instanceAclEntries == null) {
214             return null;
215         }
216
217         // Add the leaf objects to the Map, keyed on recipient
218
for (int i = 0; i < instanceAclEntries.length; i++) {
219             if (logger.isDebugEnabled()) {
220                 logger.debug("Explicit add: "
221                         + instanceAclEntries[i].toString());
222             }
223
224             map.put(instanceAclEntries[i].getRecipient(), instanceAclEntries[i]);
225         }
226
227         String JavaDoc parent = getParentURI(targetURI.getURI());
228
229         while (parent != null) {
230             BasicAclEntry[] parentAclEntries = lookup(parent);
231
232             if (logger.isDebugEnabled()) {
233                 logger.debug("Parent lookup: " + parent);
234             }
235
236             // Exit loop if parent couldn't be found (unexpected condition)
237
if (parentAclEntries == null) {
238                 if (logger.isDebugEnabled()) {
239                     logger.debug("Parent could not be found in ACL repository");
240                 }
241
242                 break;
243             }
244
245             // Now add each _NEW_ recipient to the list
246
for (int i = 0; i < parentAclEntries.length; i++) {
247                 if (!map.containsKey(parentAclEntries[i].getRecipient())) {
248                     if (logger.isDebugEnabled()) {
249                         logger.debug("Added parent to map: "
250                                 + parentAclEntries[i].toString()
251                                 + " for recipient: "
252                                 + parentAclEntries[i].getRecipient());
253                     }
254
255                     map.put(parentAclEntries[i].getRecipient(),
256                             parentAclEntries[i]);
257                 } else {
258                     if (logger.isDebugEnabled()) {
259                         logger.debug("Did NOT add parent to map: "
260                                 + parentAclEntries[i].toString()
261                                 + " for recipient: "
262                                 + parentAclEntries[i].getRecipient());
263                     }
264                 }
265             }
266
267             // Prepare for next iteration of while loop
268
parent = getParentURI(parent);
269         }
270
271         Collection JavaDoc collection = map.values();
272
273         return (BasicAclEntry[]) collection.toArray(new BasicAclEntry[]{});
274     }
275
276     public BasicAclEntry[] getAcls(AclObjectIdentity aclObjectIdentity) {
277         if (aclObjectIdentity == null || !(aclObjectIdentity instanceof InternalURI)) {
278             logger.debug("getAcls(AclObjectIdentity aclObjectIdentity): returning. invalid object for getAcls: " + aclObjectIdentity);
279             return null;
280         }
281
282         InternalURI targetURI = (InternalURI) aclObjectIdentity;
283
284         return getAcls(targetURI);
285     }
286
287     public BasicAclEntry[] getAcls(AclObjectIdentity aclObjectIdentity, Object JavaDoc recipient) {
288         if (aclObjectIdentity == null || !(aclObjectIdentity instanceof InternalURI)) {
289             logger.debug("getAcls(AclObjectIdentity aclObjectIdentity, Object recipient): returning. invalid object for getAcls: " + aclObjectIdentity);
290             return null;
291         }
292
293         InternalURI targetURI = (InternalURI) aclObjectIdentity;
294         return getAclsForRecipient(targetURI.getURI(), recipient);
295     }
296
297     private BasicAclEntry[] getAclsForRecipient(String JavaDoc targetURI, Object JavaDoc recipient) {
298         Map JavaDoc map = new HashMap JavaDoc();
299
300         while (targetURI != null) {
301             BasicAclEntry[] entries = lookup(targetURI);
302             if (entries != null) {
303
304                 // Add the leaf objects to the Map, keyed on recipient
305
for (int i = 0; i < entries.length; i++) {
306
307                     // Include if we are not filtering by recipients or we have matched the given
308
// recipient, and we have not seen this recipient before
309

310                     if ((recipient == null || recipient != entries[i].getRecipient())
311                             && !map.containsKey(entries[i].getRecipient())) {
312                         if (logger.isDebugEnabled()) {
313                             logger.debug("Added: "
314                                     + entries[i].toString());
315                         }
316
317                         map.put(entries[i].getRecipient(),
318                                 entries[i]);
319                     } else {
320                         if (logger.isDebugEnabled()) {
321                             logger.debug("Did NOT add: "
322                                     + entries[i].toString());
323                         }
324                     }
325                 }
326             }
327             targetURI = getParentURI(targetURI);
328         }
329
330         Collection JavaDoc collection = map.values();
331         return (BasicAclEntry[]) collection.toArray(new BasicAclEntry[]{});
332         //return new ArrayList(map.values());
333
}
334
335     /**
336      * Create AclEntrys from targetURI and list of ObjectPermissions
337      *
338      *
339      * @param targetURI
340      * @param permissions
341      * @return
342      */

343     private BasicAclEntry[] getAclsFromObjectPermissions(String JavaDoc targetURI, List JavaDoc permissions) {
344
345         if (permissions == null || permissions.size() == 0) {
346             log.debug("No explicit permissions found");
347             // return merely an inheritance marker (as we know about the object but it has no related ACLs)
348
return new BasicAclEntry[] {createBasicAclEntry(targetURI, null)};
349         } else {
350             if (log.isDebugEnabled()) {
351                 log.debug("Found " + permissions.size() + " explicit permissions");
352             }
353             // return the individual ACL instances
354
ObjectPermission[] aclHolders = (ObjectPermission[]) permissions.toArray(new ObjectPermission[] {});
355             List JavaDoc toReturnAcls = new ArrayList JavaDoc(aclHolders.length);
356
357             for (int i = 0; i < aclHolders.length; i++) {
358                 if (log.isDebugEnabled()) {
359                     log.debug(aclHolders[i]);
360                 }
361                 toReturnAcls.add(createBasicAclEntry(targetURI, aclHolders[i]));
362             }
363
364             return (BasicAclEntry[]) toReturnAcls.toArray(new BasicAclEntry[] {});
365         }
366     }
367     /**
368      * Constructs an individual <code>BasicAclEntry</code> from the passed
369      * <code>ObjectPermission</code> and <code>InternalURI</code>.
370      *
371      * <P>
372      * Guarantees to never return <code>null</code> (exceptions are thrown in
373      * the event of any issues).
374      * </p>
375      *
376      * @param propertiesInformation mandatory information about which instance
377      * to create, the object identity, and the parent object identity
378      * (<code>null</code> or empty <code>String</code>s prohibited for
379      * <code>aclClass</code> and <code>aclObjectIdentity</code>
380      * @param aclInformation optional information about the individual ACL
381      * record (if <code>null</code> only an "inheritence marker"
382      * instance is returned; if not <code>null</code>, it is prohibited
383      * to present <code>null</code> or an empty <code>String</code> for
384      * <code>recipient</code>)
385      *
386      * @return a fully populated instance suitable for use by external objects
387      *
388      * @throws IllegalArgumentException if the indicated ACL class could not be
389      * created
390      */

391     private BasicAclEntry createBasicAclEntry(
392             String JavaDoc targetURI, ObjectPermission aclInformation) {
393         BasicAclEntry entry;
394
395         try {
396             entry = (BasicAclEntry) SimpleAclEntry.class.newInstance();
397         } catch (InstantiationException JavaDoc ie) {
398             throw new IllegalArgumentException JavaDoc(ie.getMessage());
399         } catch (IllegalAccessException JavaDoc iae) {
400             throw new IllegalArgumentException JavaDoc(iae.getMessage());
401         }
402
403         entry.setAclObjectIdentity(new URIObjectIdentity(targetURI));
404         entry.setAclObjectParentIdentity(new URIObjectIdentity(getParentURI(targetURI)));
405
406         if (aclInformation == null) {
407             // this is an inheritance marker instance only
408
entry.setMask(0);
409             entry.setRecipient(RECIPIENT_USED_FOR_INHERITANCE_MARKER);
410         } else {
411             // this is an individual ACL entry
412
entry.setMask(aclInformation.getPermissionMask());
413             entry.setRecipient(aclInformation.getPermissionRecipient());
414         }
415
416         return entry;
417     }
418
419     /**
420      * Get the parent URI of the given URI, by slicing off the last part of the path
421      *
422      * @param currentURI
423      * @return
424      */

425     private String JavaDoc getParentURI(String JavaDoc currentURI) {
426         if (currentURI == null || currentURI.trim().length() == 0) {
427             return null;
428         } else {
429             
430             // Deal with URIs that come with "repo:" on the front
431

432             final String JavaDoc repoURIPrefix = Resource.URI_PROTOCOL + ":";
433             String JavaDoc workUri = currentURI.startsWith(repoURIPrefix)
434                                 ? currentURI.substring(repoURIPrefix.length()).trim()
435                                 : currentURI.trim();
436             
437             /*
438              * If we have a URI like "repo:/folder1/object", return "repo:/folder1".
439              *
440              * repo:/folder1 returns repo:/
441              *
442              * repo:/ returns null
443              */

444             int lastSeparator = workUri.lastIndexOf(Folder.SEPARATOR);
445             
446             // no separator
447
if (lastSeparator < 0) {
448                 return null;
449             } else if (lastSeparator == 0) {
450                 // if we are the root: no parent
451
if (workUri.length() == 1) {
452                     return null;
453                 } else {
454                     return repoURIPrefix + Folder.SEPARATOR;
455                 }
456             } else {
457                 return repoURIPrefix + workUri.substring(0, lastSeparator);
458             }
459         }
460     }
461
462     /**
463      * Find ObjectPermissions for the object
464      *
465      * (non-Javadoc)
466      * @see org.acegisecurity.acl.AclManager#getAcls(java.lang.Object)
467      */

468     public AclEntry[] getAcls(Object JavaDoc obj) {
469
470         List JavaDoc resultList = new ArrayList JavaDoc();
471
472         if (obj instanceof InternalURI) {
473             return getAcls((InternalURI) obj);
474         }
475
476         return (BasicAclEntry[]) resultList.toArray(new BasicAclEntry[] {});
477     }
478
479     /**
480      * Find ObjectPermissions for the object and Authentication (user)
481      *
482      * (non-Javadoc)
483      * @see org.acegisecurity.acl.AclManager#getAcls(java.lang.Object, org.acegisecurity.Authentication)
484      */

485     public AclEntry[] getAcls(Object JavaDoc obj, Authentication auth) {
486
487         String JavaDoc username = auth.getName();
488
489         User user = userService.getUser(null, username);
490
491         if (user == null || !(obj instanceof InternalURI)) {
492             return new BasicAclEntry[] {};
493         }
494         AclEntry[] allAcls = (AclEntry[]) this.getAcls(obj);
495
496         return this.effectiveAclsResolver.resolveEffectiveAcls(allAcls,
497             auth);
498     }
499
500     private BasicAclEntry[] lookup(String JavaDoc targetURI) {
501         URIObjectIdentity objIdent = new URIObjectIdentity(targetURI);
502         BasicAclEntry[] result = basicAclEntryCache.getEntriesFromCache(objIdent);
503
504         if (result != null) {
505             if (log.isDebugEnabled()) {
506                 log.debug("Found " + targetURI + " in cache");
507             }
508             if (result[0].getRecipient().equals(RECIPIENT_FOR_CACHE_EMPTY)) {
509                 return null;
510             } else {
511                 return result;
512             }
513         }
514
515         if (log.isDebugEnabled()) {
516             log.debug("Did not find " + targetURI + " in cache");
517         }
518
519         Resource res = getRepositoryService().getResource(null, targetURI);
520         if (res == null) {
521             res = getRepositoryService().getFolder(null, targetURI);
522             if (log.isDebugEnabled()) {
523                 log.debug("Did not find " + targetURI + " as resource");
524                 log.debug("Did " + ((res == null) ? "not" : "") + " find " + targetURI + " as folder");
525             }
526         } else {
527             if (log.isDebugEnabled()) {
528                 log.debug("Found " + targetURI + " as resource");
529             }
530         }
531
532         if (res != null) {
533             List JavaDoc permissions = getObjectPermissionsForObject(null, res);
534     
535             result = getAclsFromObjectPermissions(targetURI, permissions);
536         } else {
537             if (log.isDebugEnabled()) {
538                 log.debug("Resource not found for permissions lookup: " + targetURI);
539             }
540         }
541
542         if (result == null) {
543
544             if (log.isDebugEnabled()) {
545                 log.debug("Default entries for " + targetURI + " cached");
546             }
547             
548             SimpleAclEntry[] emptyAclEntries = {new SimpleAclEntry(RECIPIENT_FOR_CACHE_EMPTY,
549                     new URIObjectIdentity(targetURI), null, 0)};
550             basicAclEntryCache.putEntriesInCache(emptyAclEntries);
551
552             return null;
553         }
554
555         if (log.isDebugEnabled()) {
556             log.debug(result.length + " entries for " + targetURI + " cached");
557         }
558
559         basicAclEntryCache.putEntriesInCache(result);
560
561         return result;
562     }
563
564     /* (non-Javadoc)
565      * @see com.jaspersoft.jasperserver.api.metadata.common.service.RepositoryEventListener#onResourceDelete(java.lang.Class, java.lang.String)
566      */

567     public void onResourceDelete(Class JavaDoc resourceItf, String JavaDoc resourceURI) {
568         URIObjectIdentity objId = new URIObjectIdentity(resourceURI);
569         if (log.isDebugEnabled()) {
570             log.debug("Removing " + resourceURI + " from permissions and cache");
571         }
572         basicAclEntryCache.removeEntriesFromCache(objId);
573         
574         List JavaDoc permissionsToDelete = getRepoObjectPermissions(null, objId.getURI(), null);
575         
576         if (permissionsToDelete != null && !permissionsToDelete.isEmpty()) {
577             for (Iterator JavaDoc it = permissionsToDelete.iterator(); it.hasNext(); ) {
578                 RepoObjectPermission perm = (RepoObjectPermission) it.next();
579                 deleteObjectPermission(null, perm);
580             }
581         }
582     }
583  
584     /**
585      * A key for the cache
586      *
587      * @author swood
588      *
589      */

590     private class URIObjectIdentity implements AclObjectIdentity {
591         String JavaDoc uri;
592         public URIObjectIdentity(String JavaDoc uri) {
593             String JavaDoc fullUri = uri;
594             
595             // Catch things that do not have a protocol
596
if (uri != null && uri.startsWith(Folder.SEPARATOR)) {
597                 fullUri = "repo:" + uri;
598             }
599             this.uri = fullUri;
600         }
601         public String JavaDoc getURI() {
602             return uri;
603         }
604         
605         public String JavaDoc toString() {
606             return new ToStringBuilder(this)
607                 .append("uri", getURI())
608                 .toString();
609         }
610
611         public boolean equals(Object JavaDoc other) {
612             if ( !(other instanceof URIObjectIdentity) ) return false;
613             URIObjectIdentity castOther = (URIObjectIdentity) other;
614             return new EqualsBuilder()
615                 .append(this.getURI(), castOther.getURI())
616                 .isEquals();
617         }
618
619         public int hashCode() {
620             return new HashCodeBuilder()
621                 .append(getURI())
622                 .toHashCode();
623         }
624     }
625
626     /**
627      * We can authorize InternalURI
628      *
629      * (non-Javadoc)
630      * @see org.acegisecurity.acl.AclProvider#supports(java.lang.Object)
631      */

632     public boolean supports(Object JavaDoc obj) {
633         return obj instanceof InternalURI;
634     }
635
636     /* (non-Javadoc)
637      * @see com.jaspersoft.jasperserver.api.metadata.user.service.ObjectPermissionService#newObjectPermission(com.jaspersoft.jasperserver.api.common.domain.ExecutionContext)
638      */

639     public ObjectPermission newObjectPermission(ExecutionContext context) {
640         return (ObjectPermission) getObjectMappingFactory().newObject(ObjectPermission.class);
641     }
642
643     /* (non-Javadoc)
644      * @see com.jaspersoft.jasperserver.api.metadata.user.service.ObjectPermissionService#putObjectPermission(com.jaspersoft.jasperserver.api.common.domain.ExecutionContext, com.jaspersoft.jasperserver.api.metadata.user.domain.ObjectPermission)
645      */

646     public void putObjectPermission(ExecutionContext context, ObjectPermission objPermission) {
647         // Given the object and the recipient, find the permission
648
RepoObjectPermission existingPerm = getRepoObjectPermission(context, objPermission);
649         if (existingPerm == null) {
650             existingPerm = (RepoObjectPermission) getPersistentClassFactory().newObject(ObjectPermission.class);
651         }
652         existingPerm.copyFromClient(objPermission, this);
653         getHibernateTemplate().saveOrUpdate(existingPerm);
654         
655         URIObjectIdentity objId = new URIObjectIdentity(objPermission.getURI());
656         if (log.isDebugEnabled()) {
657             log.debug("Removing " + objId + " from permissions");
658         }
659         basicAclEntryCache.removeEntriesFromCache(objId);
660
661     }
662
663     public void deleteObjectPermission(ExecutionContext context, ObjectPermission objPermission) {
664         // Given the object and the recipient, find the permission
665
RepoObjectPermission existingPerm = getRepoObjectPermission(context, objPermission);
666         if (existingPerm == null) {
667             throw new JSException("No such object permission");
668         }
669         // and delete
670
getHibernateTemplate().delete(existingPerm);
671         URIObjectIdentity objId = new URIObjectIdentity(objPermission.getURI());
672         if (log.isDebugEnabled()) {
673             log.debug("Removing " + objId + " from permissions");
674         }
675         basicAclEntryCache.removeEntriesFromCache(objId);
676     }
677
678     public ObjectPermission getObjectPermission(ExecutionContext context, ObjectPermission objPermission) {
679         // Given the object and the recipient, find the permission
680
RepoObjectPermission existingPerm = getRepoObjectPermission(context, objPermission);
681         if (existingPerm == null) {
682             return null;
683         } else {
684             return (ObjectPermission) existingPerm.toClient(getObjectMappingFactory());
685         }
686     }
687 /*
688     private List getRepoObjectPermissions(ExecutionContext context, InternalURI targetURI, Object recipient) {
689         return getRepoObjectPermissions(context, targetURI.getURI(), recipient);
690     }
691 */

692     private List JavaDoc getRepoObjectPermissions(ExecutionContext context, final String JavaDoc uri, Object JavaDoc recipient) {
693         // Given the object and the recipient, find the permission
694
final IdedObject recipientObject = (IdedObject) getPersistentObject(recipient);
695
696         final String JavaDoc objPermissionClassName = getPersistentClassFactory().getImplementationClassName(ObjectPermission.class);
697
698         List JavaDoc objList = null;
699
700         if (uri == null && recipientObject == null) {
701             throw new JSException("No URI or recipient given");
702         }
703
704         if (uri != null && recipientObject != null) {
705             // Select on both identity and recipient
706
final String JavaDoc queryString = "from " + objPermissionClassName + " as objPermission " +
707             "where objPermission.URI = ? and " +
708             " objPermission.permissionRecipient.id = ? and objPermission.permissionRecipient.class = ?";
709
710             objList = getHibernateTemplate().executeFind(new HibernateCallback() {
711                 public Object JavaDoc doInHibernate(Session session) throws HibernateException {
712                     Query query = session.createQuery(queryString);
713                     query.setParameter(0, uri, Hibernate.STRING);
714                     query.setParameter(1, new Long JavaDoc(recipientObject.getId()), Hibernate.LONG);
715                     query.setParameter(2, recipientObject.getClass(), Hibernate.CLASS);
716                     return query.list();
717                 }
718             });
719         } else if (uri != null) {
720             // Select on identity
721
final String JavaDoc queryString = "from " + objPermissionClassName + " as objPermission " +
722             "where objPermission.URI = ?";
723
724             objList = getHibernateTemplate().executeFind(new HibernateCallback() {
725                 public Object JavaDoc doInHibernate(Session session) throws HibernateException {
726                     Query query = session.createQuery(queryString);
727                     query.setParameter(0, uri, Hibernate.STRING);
728                     return query.list();
729                 }
730             });
731         } else if (recipientObject != null) {
732             // Select on recipient
733
final String JavaDoc queryString = "from " + objPermissionClassName + " as objPermission " +
734             "where objPermission.permissionRecipient.id = ? and objPermission.permissionRecipient.class = ?";
735
736             objList = getHibernateTemplate().executeFind(new HibernateCallback() {
737                 public Object JavaDoc doInHibernate(Session session) throws HibernateException {
738                     Query query = session.createQuery(queryString);
739                     query.setParameter(0, new Long JavaDoc(recipientObject.getId()), Hibernate.LONG);
740                     query.setParameter(1, recipientObject.getClass(), Hibernate.CLASS);
741                     return query.list();
742                 }
743             });
744
745         }
746         return objList;
747     }
748
749     private List JavaDoc getRepoObjectPermissions(ExecutionContext context, ObjectPermission objPermission) {
750         // Given the object and parent, find the objectIdentity
751
return getRepoObjectPermissions(context, objPermission.getURI(), objPermission.getPermissionRecipient());
752     }
753
754     private RepoObjectPermission getRepoObjectPermission(ExecutionContext context, ObjectPermission objPermission) {
755         List JavaDoc objList = getRepoObjectPermissions(context, objPermission);
756         RepoObjectPermission objPerm = null;
757         if (objList == null || objList.isEmpty()) {
758             log.debug("ObjectPermission not found with object \"" +
759                     objPermission.getURI() + "\", recipient \"" + objPermission.getPermissionRecipient() + "\"");
760         } else {
761             if (log.isDebugEnabled()) {
762                 log.debug("ObjectPermission FOUND with object \"" +
763                         objPermission.getURI() + "\", recipient \"" + objPermission.getPermissionRecipient() + "\"");
764                 log.debug("Size: " + objList.size());
765             }
766             objPerm = (RepoObjectPermission) objList.get(0);
767         }
768         return objPerm;
769
770     }
771
772     /* (non-Javadoc)
773      * @see com.jaspersoft.jasperserver.api.metadata.user.service.ObjectPermissionService#getObjectPermissionsForObject(com.jaspersoft.jasperserver.api.common.domain.ExecutionContext, java.lang.Object)
774      */

775     public List JavaDoc getObjectPermissionsForObject(ExecutionContext context, Object JavaDoc targetObject) {
776         if (targetObject == null || !(targetObject instanceof InternalURI)) {
777             return new ArrayList JavaDoc();
778         }
779         InternalURI res = (InternalURI) targetObject;
780         List JavaDoc objList = getRepoObjectPermissions(context, res.getURI(), null);
781         return makeObjectPermissionClientList(res.getURI(), objList);
782     }
783
784     /* (non-Javadoc)
785      * @see com.jaspersoft.jasperserver.api.metadata.user.service.ObjectPermissionService#getObjectPermissionsForRecipient(com.jaspersoft.jasperserver.api.common.domain.ExecutionContext, java.lang.Object)
786      */

787     public List JavaDoc getObjectPermissionsForRecipient(ExecutionContext context, Object JavaDoc recipient) {
788         List JavaDoc objList = getRepoObjectPermissions(context, null, recipient);
789         return makeObjectPermissionClientList(null, objList);
790     }
791
792     /* (non-Javadoc)
793      * @see com.jaspersoft.jasperserver.api.metadata.user.service.ObjectPermissionService#getObjectPermissionsForObjectAndRecipient(com.jaspersoft.jasperserver.api.common.domain.ExecutionContext, java.lang.Object, java.lang.Object)
794      */

795     public List JavaDoc getObjectPermissionsForObjectAndRecipient(ExecutionContext context, Object JavaDoc targetObject, Object JavaDoc recipient) {
796         if (!(targetObject instanceof InternalURI)) {
797             return new ArrayList JavaDoc();
798         }
799         InternalURI res = (InternalURI) targetObject;
800         List JavaDoc objList = getRepoObjectPermissions(context, res.getURI(), recipient);
801         return makeObjectPermissionClientList(res.getURI(), objList);
802     }
803
804     private List JavaDoc makeObjectPermissionClientList(String JavaDoc uri, List JavaDoc objList) {
805         List JavaDoc resultList = new ArrayList JavaDoc(objList.size());
806 /*
807         if ((objList == null || objList.isEmpty()) && uri != null && uri.length() > 0) {
808             // Deal with default inheritance: return an object with a URI only
809             RepoObjectPermission repoPerm = new RepoObjectPermission();
810             repoPerm.setURI(uri);
811             if (objList == null) {
812                 objList = new ArrayList();
813             }
814             objList.add(repoPerm);
815         }
816 */

817         for (Iterator JavaDoc it = objList.iterator(); !objList.isEmpty() && it.hasNext();) {
818             RepoObjectPermission repoPerm = (RepoObjectPermission) it.next();
819             ObjectPermission clientPermission = (ObjectPermission) repoPerm.toClient(getObjectMappingFactory());
820             resultList.add(clientPermission);
821         }
822         return resultList;
823     }
824
825     /* (non-Javadoc)
826      * @see com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.PersistentObjectResolver#getPersistentObject(java.lang.Object)
827      */

828     public Object JavaDoc getPersistentObject(Object JavaDoc clientObject) {
829         // If already persisted, just return it
830
if (clientObject == null) {
831             return null;
832         } else if (clientObject instanceof IdedObject) {
833             return clientObject;
834         } else if (clientObject instanceof Role || clientObject instanceof User) {
835             return ((PersistentObjectResolver) userService).getPersistentObject(clientObject);
836         } else if (clientObject instanceof Resource) {
837             // TODO Hack! Make it an interface!
838
String JavaDoc uri = ((Resource) clientObject).getURIString();
839             return repoService.findByURI(RepoResource.class, uri, false);
840         } else if (clientObject instanceof ObjectPermission) {
841             return getRepoObjectPermission(null, (ObjectPermission) clientObject);
842         }
843         return null;
844     }
845
846     /* (non-Javadoc)
847      * @see com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.ReferenceResolver#getExternalReference(java.lang.String, java.lang.Class)
848      */

849     public RepoResource getExternalReference(String JavaDoc uri, Class JavaDoc persistentReferenceClass) {
850         return ((ReferenceResolver) repoService).getExternalReference(uri, persistentReferenceClass);
851     }
852
853     /* (non-Javadoc)
854      * @see com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.ReferenceResolver#getReference(com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.persistent.RepoResource, com.jaspersoft.jasperserver.api.metadata.common.domain.Resource, java.lang.Class)
855      */

856     public RepoResource getReference(RepoResource owner, Resource resource, Class JavaDoc persistentReferenceClass) {
857         return ((ReferenceResolver) repoService).getReference(owner, resource, persistentReferenceClass);
858     }
859
860 }
861
Popular Tags