]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
f55daf08d69d5d6169f846b13731e89cdd0c9d3d
[tmp/jakarta-migration.git] /
1 /**
2  *  This document is a part of the source code and related artifacts
3  *  for CollectionSpace, an open source collections management system
4  *  for museums and related institutions:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
18  *  Unless required by applicable law or agreed to in writing, software
19  *  distributed under the License is distributed on an "AS IS" BASIS,
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  *  See the License for the specific language governing permissions and
22  *  limitations under the License.
23  */
24 package org.collectionspace.services.common.authorization_mgt;
25
26 import java.util.HashMap;
27 import java.util.List;
28
29 import javax.persistence.EntityManager;
30 import javax.persistence.EntityManagerFactory;
31
32 import org.collectionspace.services.common.document.DocumentNotFoundException;
33 import org.collectionspace.services.common.context.ServiceContext;
34 import org.collectionspace.services.common.context.ServiceContextProperties;
35 import org.collectionspace.services.common.storage.jpa.JpaRelationshipStorageClient;
36 import org.collectionspace.services.common.storage.jpa.JpaStorageUtils;
37
38 import org.collectionspace.services.authorization.perms.Permission;
39 import org.collectionspace.services.authorization.PermissionRole;
40 import org.collectionspace.services.authorization.PermissionRoleRel;
41 import org.collectionspace.services.authorization.PermissionValue;
42 import org.collectionspace.services.authorization.Role;
43 import org.collectionspace.services.authorization.RoleValue;
44 import org.collectionspace.services.authorization.SubjectType;
45
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 // TODO: Auto-generated Javadoc
50 /**
51  * The Class PermissionRoleUtil.
52  *
53  * @author
54  */
55 public class PermissionRoleUtil {
56
57     static final Logger logger = LoggerFactory.getLogger(PermissionRoleUtil.class);
58
59     /**
60      * Gets the relation subject.
61      *
62      * @param ctx the ctx
63      * @return the relation subject
64      */
65     static public SubjectType getRelationSubject(ServiceContext ctx) {
66         Object o = ctx.getProperty(ServiceContextProperties.SUBJECT);
67         if (o == null) {
68             throw new IllegalArgumentException(ServiceContextProperties.SUBJECT
69                     + " property is missing in context "
70                     + ctx.toString());
71         }
72         return (SubjectType) o;
73     }
74
75     /**
76      * Gets the relation subject.
77      *
78      * @param ctx the ctx
79      * @param pr the pr
80      * @return the relation subject
81      */
82     static public SubjectType getRelationSubject(ServiceContext ctx, PermissionRole pr) {
83         SubjectType subject = pr.getSubject();
84         if (subject == null) {
85             //it is not required to give subject as URI determines the subject
86             subject = getRelationSubject(ctx);
87         }
88         return subject;
89     }
90
91     /**
92      * buildPermissionRoleRel builds persistent relationship entities from given
93      * permissionrole.
94      *
95      * @param pr permissionrole
96      * @param subject the subject
97      * @param prrl persistent entities built are inserted into this list
98      * @param toDelete the to delete
99      */
100     static public void buildPermissionRoleRel(EntityManager em, 
101                 PermissionRole pr,
102                 SubjectType subject,
103                 List<PermissionRoleRel> prrl,
104                 boolean handleDelete) throws Exception {
105         if (subject.equals(SubjectType.ROLE)) {
106                 List<PermissionValue> permissionValues = pr.getPermission();
107                 if (permissionValues != null && permissionValues.size() > 0) {
108                     PermissionValue pv = permissionValues.get(0);
109                     for (RoleValue rv : pr.getRole()) {
110                         PermissionRoleRel prr = buildPermissonRoleRel(em, pv, rv, subject, handleDelete);
111                         prrl.add(prr);
112                     }
113                 }
114         } else if (subject.equals(SubjectType.PERMISSION)) {
115                 List<RoleValue> roleValues = pr.getRole();
116                 if (roleValues != null && roleValues.size() > 0) {
117                     RoleValue rv = roleValues.get(0);
118                     for (PermissionValue pv : pr.getPermission()) {
119                         PermissionRoleRel prr = buildPermissonRoleRel(em, pv, rv, subject, handleDelete);
120                         prrl.add(prr);
121                     }
122                 }
123         }
124     }
125     
126     static public void buildPermissionRoleRel( 
127                 PermissionRole pr,
128                 SubjectType subject,
129                 List<PermissionRoleRel> prrl,
130                 boolean handleDelete) throws Exception {
131         EntityManagerFactory emf = null;
132         EntityManager em = null;
133         try {
134             emf = JpaStorageUtils.getEntityManagerFactory(JpaStorageUtils.CS_PERSISTENCE_UNIT);
135             em = emf.createEntityManager();
136             em.getTransaction().begin();
137             
138             buildPermissionRoleRel(em, pr, subject, prrl, handleDelete);
139             
140             em.getTransaction().commit();
141                 em.close();            
142         } catch (Exception e) {
143             if (em != null && em.getTransaction().isActive()) {
144                 em.getTransaction().rollback();
145             }
146             if (logger.isDebugEnabled()) {
147                 logger.debug("Caught exception ", e);
148             }
149             throw e;
150         } finally {
151             if (em != null) {
152                 JpaStorageUtils.releaseEntityManagerFactory(emf);
153             }
154         }
155     }    
156
157     /**
158      * Builds a permisson role relationship for either 'create' or 'delete'
159      *
160      * @param pv the pv (currently using only the ID)
161      * @param rv the rv (currently using only the ID)
162      * @param handleDelete the handle delete
163      * @return the permission role rel
164      */
165     static private PermissionRoleRel buildPermissonRoleRel(EntityManager em, PermissionValue permissionValue,
166                 RoleValue roleValue,
167                 SubjectType subject,
168                 boolean handleDelete)
169                         throws DocumentNotFoundException {
170
171         PermissionRoleRel result = null;
172         
173         //
174         // Ensure we can find both the Permission and Role to relate.
175         // FIXME: REM - This is a workaround until the Import utility creates Perm/Role relationships
176         // correctly.  The import utility should create and store the permissions and roles BEFORE creating the relationships
177         //
178         PermissionValue pv = permissionValue;
179         
180         //
181         // This lookup is slow, do we really need it?
182         //
183         /*
184         try {
185                 Permission permission = (Permission)JpaStorageUtils.getEntity(em, pv.getPermissionId(), //FIXME: REM 4/5/2012 - To improve performance, we should use a passed in Permission instance
186                                 Permission.class);
187                 if (permission != null) {
188                         // If the permission already exists, then use it to fill our the relation record
189                         pv = JpaRelationshipStorageClient.createPermissionValue(permission);
190                 }
191         } catch (DocumentNotFoundException e) {
192                 // ignore this exception, pv is set to permissionValue;
193         }
194         */
195         
196         //
197         // Ensure we can find both the Permission and Role to relate.
198         // FIXME: REM - This is a workaround until the Import utility creates Perm/Role relationships
199         // correctly.  The import utility should create and store the permissions and roles BEFORE creating the relationships
200         //
201         RoleValue rv = roleValue;
202         
203         /*
204          * This lookup is slow, can we avoid it?
205         try {
206                 Role role = (Role)JpaStorageUtils.getEntity(em, rv.getRoleId(),
207                                 Role.class);
208                 if (role != null) {
209                         // If the role already exists, then use it to fill out the relation record
210                         rv = JpaRelationshipStorageClient.createRoleValue(role);
211                 }
212         } catch (DocumentNotFoundException e) {
213                 // ignore this exception, rv is set to roleValue
214         }
215          */
216         
217         result = new PermissionRoleRel();
218         result.setPermissionId(pv.getPermissionId());
219         result.setPermissionResource(pv.getResourceName());
220         result.setActionGroup(pv.getActionGroup());
221         result.setRoleId(rv.getRoleId());
222         result.setRoleName(rv.getRoleName());
223         //
224         // For 'delete' we need to set the hjid of the existing relstionship
225         //
226         String relationshipId = null;
227         if (subject.equals(SubjectType.ROLE) == true) {
228                 relationshipId = roleValue.getRoleRelationshipId();
229         } else if (subject.equals(SubjectType.PERMISSION) == true) {
230                 relationshipId = permissionValue.getPermRelationshipId();
231         }
232         if (relationshipId != null && handleDelete == true) {
233                 result.setHjid(Long.parseLong(relationshipId));  // set this so we can convince JPA to del the relation
234         }
235         
236         return result;
237     }
238
239     /**
240      * Checks if is invalid tenant.
241      *
242      * @param tenantId the tenant id
243      * @param msgBldr the msg bldr
244      * @return true, if is invalid tenant
245      */
246     static boolean isInvalidTenant(String tenantId, StringBuilder msgBldr) {
247         boolean invalid = false;
248
249         if (tenantId == null || tenantId.isEmpty()) {
250             invalid = true;
251             msgBldr.append("\n tenant : tenantId is missing");
252         }
253         String whereClause = "where id = :id";
254         HashMap<String, Object> params = new HashMap<String, Object>();
255         params.put("id", tenantId);
256
257         Object tenantFound = JpaStorageUtils.getEntity(
258                 "org.collectionspace.services.account.Tenant", whereClause, params);
259         if (tenantFound == null) {
260             invalid = true;
261             msgBldr.append("\n tenant : tenantId=" + tenantId
262                     + " not found");
263         }
264         return invalid;
265     }
266 }