]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
7aff76a86e1e1414d02ae0a193e8339620d77dc5
[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 2010 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 /*
25  * To change this template, choose Tools | Templates
26  * and open the template in the editor.
27  */
28 package org.collectionspace.services.common.authorization_mgt;
29
30 import java.util.Date;
31 import javax.persistence.EntityManager;
32 import javax.persistence.EntityManagerFactory;
33
34 import org.collectionspace.services.authorization.Role;
35 import org.collectionspace.services.authorization.PermissionRoleRel;
36 import org.collectionspace.services.authorization.perms.Permission;
37 import org.collectionspace.services.common.authorization_mgt.RoleStorageConstants;
38 import org.collectionspace.services.common.document.JaxbUtils;
39 import org.collectionspace.services.common.storage.jpa.JpaStorageUtils;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * AuthorizationStore stores persistent entities during import
45  * @author
46  */
47 public class AuthorizationStore {
48
49     private static final Logger logger = LoggerFactory.getLogger(AuthorizationStore.class);
50     private final static String PERSISTENCE_UNIT = "org.collectionspace.services.authorization";
51
52     static public Role getRoleByName(String roleName, String tenantId) {
53         Role theRole = null;
54         
55         try {
56                 theRole = (Role)JpaStorageUtils.getEnityByKey(Role.class.getName(),
57                                 RoleStorageConstants.ROLE_NAME, roleName, tenantId);
58         } catch (Throwable e) {
59                 if (logger.isTraceEnabled() == true) {
60                         logger.trace("Could not retrieve role with name =" + roleName, e);
61                 }
62         }
63         
64         return theRole;
65     }
66     
67     static public Role getRoleByName(EntityManager em, String roleName, String tenantId) {
68         Role theRole = null;
69         
70         try {
71                 theRole = (Role)JpaStorageUtils.getEnityByKey(em, Role.class.getName(),
72                                 RoleStorageConstants.ROLE_NAME, roleName, tenantId);
73         } catch (Throwable e) {
74                 if (logger.isTraceEnabled() == true) {
75                         logger.trace("Could not retrieve role with name =" + roleName, e);
76                 }
77         }
78         
79         return theRole;
80     }
81     
82     
83     static public PermissionRoleRel getPermRoleRel(EntityManager em, String permId, String roleId) {
84         PermissionRoleRel permRoleRel = null;
85         
86         try {
87                 permRoleRel = (PermissionRoleRel)JpaStorageUtils.getEntityByDualKeys(em, 
88                                 PermissionRoleRel.class.getName(),
89                                 RoleStorageConstants.PERM_ROLE_REL_PERM_ID, permId, 
90                                 RoleStorageConstants.PERM_ROLE_REL_ROLE_ID, roleId);
91         } catch (Throwable e) {
92                 if (logger.isTraceEnabled()) {
93                         logger.trace("Could not retrieve permissionRoleRel with permId =" + permId 
94                                         +" and roleId="+roleId, e);
95                 }
96         }
97         
98         return permRoleRel;
99     }
100     
101     
102     static public Permission getPermission(Permission permission) {
103         Permission result = null;
104         //
105         // We need to perform a DB lookup to see if this permission already exists.  If so,
106         // we should return the existing permission.
107         //
108         result = permission;
109         
110         return result;
111     }
112     
113     /**
114      * store the given entity
115      * @param entity
116      * @return csid of the entity
117      * @throws Exception
118      */
119     public String store(Object entity) throws Exception {
120         EntityManagerFactory emf = null;
121         EntityManager em = null;
122         try {
123             emf = JpaStorageUtils.getEntityManagerFactory(PERSISTENCE_UNIT);
124             em = emf.createEntityManager();
125             //FIXME: more efficient would be to participate in transaction already started
126             //by the caller
127             em.getTransaction().begin();
128             if (JaxbUtils.getValue(entity, "getCreatedAt") == null) {
129                 JaxbUtils.setValue(entity, "setCreatedAtItem", Date.class, new Date());
130             }
131             em.persist(entity);
132             em.getTransaction().commit();
133             String id = null;
134             try{
135                 id = (String) JaxbUtils.getValue(entity, "getCsid"); //NOTE: Not all entities have a CSID attribute
136             } catch(NoSuchMethodException nsme) {
137                 //do nothing ok, relationship does not have csid
138             }
139             return id;
140         } catch (Exception e) {
141             if (em != null && em.getTransaction().isActive()) {
142                 em.getTransaction().rollback();
143             }
144             if (logger.isDebugEnabled()) {
145                 logger.debug("Caught exception ", e);
146             }
147             throw e;
148         } finally {
149             if (em != null) {
150                 em.clear();
151                 em.close();
152                 JpaStorageUtils.releaseEntityManagerFactory(emf);
153             }
154         }
155     }
156     
157     private boolean exists(EntityManager em, Object entity) {
158         boolean result = false;
159         
160         try {
161                 if(entity instanceof Role) {
162                         // If find by name, exists
163                         Role roleEntity = (Role)entity;
164                         String roleName = roleEntity.getRoleName();
165                         String tenantId = roleEntity.getTenantId();
166                         if(getRoleByName(em, roleName, tenantId)!=null) {
167                                 result = true;
168                         logger.trace("Role {} already exists in tenant {}.", roleName, tenantId);
169                         } else {
170                         logger.trace("Role {} does not exist in tenant {}.", roleName, tenantId);
171                         }
172                 } else if(entity instanceof PermissionRoleRel) {
173                         // If find by name, exists
174                         PermissionRoleRel permRoleEntity = (PermissionRoleRel)entity;
175                         String roleId = permRoleEntity.getRoleId();
176                         String permId = permRoleEntity.getPermissionId();
177                         if(getPermRoleRel(em, permId, roleId)!=null) {
178                                 result = true;
179                         logger.trace("PermRoleRel for {}, {} already exists.", permId, roleId);
180                         } else {
181                         logger.trace("PermRoleRel for {}, {} does not exist.", permId, roleId);
182                         }
183                 } else {        // Default case; also best test for Permission
184                         String csid = (String)JaxbUtils.getValue(entity, "getCsid");
185                         Object existingEntity = em.find(entity.getClass(), csid);
186                         if (existingEntity != null) {
187                                 result = true;
188                         logger.trace("Entity with csid {} already exists.", csid);
189                         } else {
190                         logger.trace("Entity with csid {} does not exist.", csid);
191                         }
192                 }
193         } catch (Exception e) {
194                 //NOTE: Not all entities have a CSID attribute
195         }
196         
197         return result;
198     }
199     /*
200      * Use this method if you've already started a transaction with an EntityManager
201      */
202     public String store(EntityManager em, Object entity) throws Exception {
203         boolean entityExists = exists(em, entity);
204         /* 
205          * Logging moved to exists, for better detail
206         if (entityExists == true) {
207                 logger.trace("Entity to persist already exists.");
208         }
209          */
210         if (JaxbUtils.getValue(entity, "getCreatedAt") == null) {
211             JaxbUtils.setValue(entity, "setCreatedAtItem", Date.class, new Date());
212         }
213         
214         if (entityExists == true) {
215                 //em.merge(entity); FIXME: Leave commented out until we address CSPACE-5031
216                 // PLS: Question: why merge? what might be new to change, and is this really a good idea?
217                 // Shouldn't we define them once and leave them alone?
218         } else {
219                 em.persist(entity);
220         }
221         
222         // look for a CSID
223         String id = null;
224         try{
225             id = (String) JaxbUtils.getValue(entity, "getCsid"); //NOTE: Not all entities have a CSID attribute
226         } catch(NoSuchMethodException nsme) {
227             //do nothing ok, relationship does not have csid
228         }
229         return id;
230     }
231 }