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