e1b71d7dd177c8a940f8c9119630294871dcfb50
[utils] / security / impl / src / main / java / org / wamblee / security / authorization / jpa / JpaAuthorizationService.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.wamblee.security.authorization.jpa;
17
18 import javax.persistence.EntityManager;
19 import javax.persistence.NoResultException;
20 import javax.persistence.NonUniqueResultException;
21
22 import org.wamblee.persistence.JpaMergeSupport;
23 import org.wamblee.security.authorization.AbstractAuthorizationService;
24 import org.wamblee.security.authorization.AbstractAuthorizationRule;
25 import org.wamblee.security.authorization.AuthorizationRule;
26 import org.wamblee.security.authorization.AuthorizationService;
27 import org.wamblee.security.authorization.DefaultAuthorizationService;
28 import org.wamblee.security.authorization.Operation;
29 import org.wamblee.usermgt.UserAccessor;
30
31 /**
32  * Authorization service with persistent storage. This is a wrapper for
33  * {@link org.wamblee.security.authorization.DefaultAuthorizationService} which
34  * refreshes the state of the service at certain time intervals.
35  * 
36  * @author Erik Brakkee
37  */
38 public class JpaAuthorizationService implements AuthorizationService {
39
40     /**
41      * Authorization service to use.
42      */
43     private AuthorizationService service;
44
45     /**
46      * Hibernate template to use.
47      */
48     private EntityManager entityManager;
49
50     /**
51      * User accessor.
52      */
53     private UserAccessor userAccessor;
54
55     /**
56      * Name of the service.
57      */
58     private String name;
59
60     /**
61      * Refresh interval in milliseconds.
62      */
63     private final long refreshInterval;
64
65     /**
66      * Last refresh time.
67      */
68     private long lastRefreshTime;
69
70     /**
71      * Constructs the persistent service.
72      * 
73      * @param aName
74      *            Name of the service.
75      * @param aEntityManager
76      *            Entity manager.
77      * @param aAccessor
78      *            User accessor.
79      * @param aRefresh
80      *            Whether or not to refresh the state of the service at the
81      *            start of every operation.
82      */
83     public JpaAuthorizationService(String aName, EntityManager aEntityManager,
84         UserAccessor aAccessor, long aRefreshInterval) {
85         entityManager = aEntityManager;
86         refreshInterval = aRefreshInterval;
87         lastRefreshTime = System.currentTimeMillis();
88         userAccessor = aAccessor;
89         name = aName;
90     }
91     
92     @Override
93     public void setUserAccessor(UserAccessor aUserAccessor) {
94         userAccessor = aUserAccessor;   
95     }
96
97     /**
98      * Initialize service if needed.
99      * 
100      */
101     private void initialize() {
102         if (service == null) {
103             refreshByReload();
104         }
105     }
106
107     private void refreshByReload() {
108         try {
109             service = entityManager.createNamedQuery(
110                 AbstractAuthorizationService.QUERY_FIND_BY_NAME,
111                 AbstractAuthorizationService.class).setParameter(
112                     AbstractAuthorizationService.NAME_PARAM, name).getSingleResult();
113             service.setUserAccessor(userAccessor);
114         } catch (NonUniqueResultException e) {
115             throw new IllegalArgumentException(
116                 "Returned more than one service for name '" + name + "'");
117         } catch (NoResultException e) {
118             service = new DefaultAuthorizationService(userAccessor, name);
119             entityManager.persist(service);
120         }
121     }
122
123     /*
124      * (non-Javadoc)
125      * 
126      * @see
127      * org.wamblee.security.authorization.AuthorizationService#isAllowed(java
128      * .lang.Object, org.wamblee.security.authorization.Operation)
129      */
130     public boolean isAllowed(Object aResource, Operation aOperation) {
131         initialize();
132         refresh();
133
134         return service.isAllowed(aResource, aOperation);
135     }
136
137     /*
138      * (non-Javadoc)
139      * 
140      * @see org.wamblee.security.authorization.AuthorizationService#check(T,
141      * org.wamblee.security.authorization.Operation)
142      */
143     public <T> T check(T aResource, Operation aOperation) {
144         initialize();
145         refresh();
146
147         return service.check(aResource, aOperation);
148     }
149
150     /*
151      * (non-Javadoc)
152      * 
153      * @see org.wamblee.security.authorization.AuthorizationService#getRules()
154      */
155     public AuthorizationRule[] getRules() {
156         initialize();
157         refresh();
158
159         return service.getRules();
160     }
161
162     /*
163      * (non-Javadoc)
164      * 
165      * @see
166      * org.wamblee.security.authorization.AuthorizationService#appendRule(org
167      * .wamblee.security.authorization.AuthorizationRule)
168      */
169     public void appendRule(AuthorizationRule aRule) {
170         initialize();
171         refresh();
172         service.appendRule(aRule);
173         save();
174     }
175
176     /*
177      * (non-Javadoc)
178      * 
179      * @see
180      * org.wamblee.security.authorization.AuthorizationService#removeRule(int)
181      */
182     public void removeRule(int aIndex) {
183         initialize();
184         refresh();
185         service.removeRule(aIndex);
186         save();
187     }
188
189     /*
190      * (non-Javadoc)
191      * 
192      * @see
193      * org.wamblee.security.authorization.AuthorizationService#insertRuleAfter
194      * (int, org.wamblee.security.authorization.AuthorizationRule)
195      */
196     public void insertRuleAfter(int aIndex, AuthorizationRule aRule) {
197         initialize();
198         refresh();
199         service.insertRuleAfter(aIndex, aRule);
200         save();
201     }
202
203     /**
204      * Refreshes the state of the service through hibernate.
205      */
206     private synchronized void refresh() {
207         long time = System.currentTimeMillis();
208
209         if ((time - lastRefreshTime) > refreshInterval) {
210             refreshByReload();
211             lastRefreshTime = time;
212         }
213     }
214
215     /**
216      * Saves any changes to the service state if necessary.
217      */
218     private void save() {
219         AuthorizationService merged = entityManager.merge(service);
220         entityManager.flush();
221         JpaMergeSupport.merge(merged, service);
222     }
223 }