]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
ffdf5398de82321a842b2acd0cb86dca8cb70c6a
[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.account.storage;
25
26 import java.util.Date;
27 import java.util.HashMap;
28
29 import org.collectionspace.services.account.AccountsCommon;
30 import org.collectionspace.services.account.storage.csidp.UserStorageClient;
31 import org.collectionspace.services.authentication.User;
32 import org.collectionspace.services.common.context.ServiceContext;
33 import org.collectionspace.services.common.document.BadRequestException;
34 import org.collectionspace.services.common.document.DocumentException;
35 import org.collectionspace.services.common.document.DocumentFilter;
36 import org.collectionspace.services.common.document.DocumentHandler;
37 import org.collectionspace.services.common.document.DocumentHandler.Action;
38 import org.collectionspace.services.common.document.DocumentNotFoundException;
39 import org.collectionspace.services.common.document.DocumentWrapper;
40 import org.collectionspace.services.common.document.DocumentWrapperImpl;
41 import org.collectionspace.services.common.document.JaxbUtils;
42 import org.collectionspace.services.common.storage.jpa.JPATransactionContext;
43 import org.collectionspace.services.common.storage.jpa.JpaStorageClientImpl;
44 import org.collectionspace.services.common.storage.jpa.JpaStorageUtils;
45
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 /**
50  * AccountStorageClient deals with both Account and CSIdP's
51  * state in persistent storage. The rationale behind creating this class is that
52  * this class manages pesistence for both account and CSIP's user. Transactions
53  * are used where possible to permorme the persistence operations atomically.
54  * @author 
55  */
56 @SuppressWarnings({ "rawtypes", "unchecked" })
57 public class AccountStorageClient extends JpaStorageClientImpl {
58
59     private final Logger logger = LoggerFactory.getLogger(AccountStorageClient.class);
60     private UserStorageClient userStorageClient = new UserStorageClient();
61
62     public AccountStorageClient() {
63     }
64
65         @Override
66     public String create(ServiceContext ctx,
67             DocumentHandler handler) throws BadRequestException,
68             DocumentException {
69         String result = null;
70         
71         AccountsCommon account = null;
72         JPATransactionContext jpaConnectionContext = (JPATransactionContext)ctx.openConnection();       
73         try {
74             account = (AccountsCommon) handler.getCommonPart();
75             handler.prepare(Action.CREATE);
76             DocumentWrapper<AccountsCommon> wrapDoc =
77                     new DocumentWrapperImpl<AccountsCommon>(account);
78             handler.handle(Action.CREATE, wrapDoc);
79             jpaConnectionContext.beginTransaction();
80             //
81             // If userid and password are given, add to default id provider
82             //
83             if (account.getUserId() != null && isForCSpaceIdentityProvider(account.getPassword())) {
84                 User user = userStorageClient.create(account.getUserId(), account.getPassword());
85                     jpaConnectionContext.persist(user);         
86             }
87
88             account.setCreatedAtItem(new Date());
89             jpaConnectionContext.persist(account);              
90
91             handler.complete(Action.CREATE, wrapDoc);
92             jpaConnectionContext.commitTransaction();
93
94             result = (String)JaxbUtils.getValue(account, "getCsid");
95         } catch (BadRequestException bre) {
96                 jpaConnectionContext.markForRollback();
97             throw bre;
98         } catch (Exception e) {
99             if (logger.isDebugEnabled()) {
100                 logger.debug("Caught exception ", e);
101             }
102             boolean uniqueConstraint = false;
103             if (userStorageClient.get(ctx, account.getUserId()) != null) {
104                 //might be unique constraint violation
105                 uniqueConstraint = true;
106             }
107             
108                 jpaConnectionContext.markForRollback();
109
110             if (uniqueConstraint) {
111                 String msg = "UserId exists. Non unique userId=" + account.getUserId();
112                 logger.error(msg);
113                 throw new BadRequestException(msg);
114             }
115             throw new DocumentException(e);
116         } finally {
117             ctx.closeConnection();
118         }
119         
120         return result;
121     }
122
123     @Override
124     public void get(ServiceContext ctx, String id, DocumentHandler handler)
125             throws DocumentNotFoundException, DocumentException {
126         DocumentFilter docFilter = handler.getDocumentFilter();
127         if (docFilter == null) {
128             docFilter = handler.createDocumentFilter();
129         }
130
131         JPATransactionContext jpaTransactionContext = (JPATransactionContext)ctx.openConnection();
132         try {
133             handler.prepare(Action.GET);
134             Object o = null;
135             String whereClause = " JOIN a.tenants as at where csid = :csid and at.tenantId = :tenantId";
136             HashMap<String, Object> params = new HashMap<String, Object>();
137             params.put("csid", id);
138             params.put("tenantId", ctx.getTenantId());
139
140             o = JpaStorageUtils.getEntity(jpaTransactionContext, 
141                     "org.collectionspace.services.account.AccountsCommon", whereClause, params);
142             if (null == o) {
143                 String msg = "could not find entity with id=" + id;
144                 throw new DocumentNotFoundException(msg);
145             }
146             DocumentWrapper<Object> wrapDoc = new DocumentWrapperImpl<Object>(o);
147             handler.handle(Action.GET, wrapDoc);
148             handler.complete(Action.GET, wrapDoc);
149         } catch (DocumentException de) {
150             throw de;
151         } catch (Exception e) {
152             if (logger.isDebugEnabled()) {
153                 logger.debug("Caught exception ", e);
154             }
155             throw new DocumentException(e);
156         } finally {
157                 ctx.closeConnection();
158         }
159         
160     }
161
162     @Override
163     public void update(ServiceContext ctx, String id, DocumentHandler handler)
164             throws BadRequestException, DocumentNotFoundException,
165             DocumentException {
166
167         JPATransactionContext jpaConnectionContext = (JPATransactionContext)ctx.openConnection();        
168         try {
169             jpaConnectionContext.beginTransaction();
170
171             handler.prepare(Action.UPDATE);
172             AccountsCommon accountReceived = (AccountsCommon) handler.getCommonPart();
173             AccountsCommon accountFound = getAccount(jpaConnectionContext, id);
174             checkAllowedUpdates(accountReceived, accountFound);
175             //if userid and password are given, add to default id provider
176             // Note that this ignores the immutable flag, as we allow
177             // password changes.
178             if (accountReceived.getUserId() != null && isForCSpaceIdentityProvider(accountReceived.getPassword())) {
179                 userStorageClient.update(jpaConnectionContext,
180                         accountReceived.getUserId(),
181                         accountReceived.getPassword());
182             }
183             DocumentWrapper<AccountsCommon> wrapDoc =
184                     new DocumentWrapperImpl<AccountsCommon>(accountFound);
185             handler.handle(Action.UPDATE, wrapDoc);
186             handler.complete(Action.UPDATE, wrapDoc);
187
188             jpaConnectionContext.commitTransaction();
189         } catch (BadRequestException bre) {
190                 jpaConnectionContext.markForRollback();
191             throw bre;
192         } catch (DocumentException de) {
193                 jpaConnectionContext.markForRollback();
194             throw de;
195         } catch (Exception e) {
196                 jpaConnectionContext.markForRollback();
197             throw new DocumentException(e);
198         } finally {
199             ctx.closeConnection();
200         }
201     }
202
203     @Override
204     public void delete(ServiceContext ctx, String id)
205             throws DocumentNotFoundException,
206             DocumentException {
207
208         if (logger.isDebugEnabled()) {
209             logger.debug("deleting entity with id=" + id);
210         }
211         
212         JPATransactionContext jpaConnectionContext = (JPATransactionContext)ctx.openConnection();        
213         try {
214             AccountsCommon accountFound = getAccount(jpaConnectionContext, id);
215             jpaConnectionContext.beginTransaction();
216             //if userid gives any indication about the id provider, it should
217             //be used to avoid  delete
218             userStorageClient.delete(jpaConnectionContext, accountFound.getUserId());
219             jpaConnectionContext.remove(accountFound);
220             jpaConnectionContext.commitTransaction();
221         } catch (DocumentException de) {
222                 jpaConnectionContext.markForRollback();
223             throw de;
224         } catch (Exception e) {
225             if (logger.isDebugEnabled()) {
226                 logger.debug("Caught exception ", e);
227             }
228             jpaConnectionContext.markForRollback();
229             throw new DocumentException(e);
230         } finally {
231             ctx.closeConnection();
232         }
233     }
234
235     private AccountsCommon getAccount(JPATransactionContext jpaConnectionContext, String id) throws DocumentNotFoundException {
236         AccountsCommon accountFound = (AccountsCommon) jpaConnectionContext.find(AccountsCommon.class, id);
237         if (accountFound == null) {
238             String msg = "could not find account with id=" + id;
239             logger.error(msg);
240             throw new DocumentNotFoundException(msg);
241         }
242         
243         return accountFound;
244     }
245
246     private boolean checkAllowedUpdates(AccountsCommon toAccount, AccountsCommon fromAccount) throws BadRequestException {
247         if (!fromAccount.getUserId().equals(toAccount.getUserId())) {
248             String msg = "userId=" + toAccount.getUserId() + " of existing account does not match "
249                     + "the userId=" + fromAccount.getUserId()
250                     + " with csid=" + fromAccount.getCsid();
251             logger.error(msg);
252             if (logger.isDebugEnabled()) {
253                 logger.debug(msg + " found userid=" + fromAccount.getUserId());
254             }
255             throw new BadRequestException(msg);
256         }
257         return true;
258     }
259
260     /**
261      * isForCSIdP deteremines if the create/update is also needed for CS IdP
262      * @param bpass
263      * @return
264      */
265     private boolean isForCSpaceIdentityProvider(byte[] bpass) {
266         return bpass != null && bpass.length > 0;
267     }
268 //    private UserTenant createTenantAssoc(AccountsCommon accountReceived) {
269 //        UserTenant userTenant = new UserTenant();
270 //        userTenant.setUserId(accountReceived.getUserId());
271 //        List<AccountsCommon.Tenant> atl = accountReceived.getTenant();
272 //        List<UserTenant.Tenant> utl =
273 //                new ArrayList<UserTenant.Tenant>();
274 //        for (AccountsCommon.Tenant at : atl) {
275 //            UserTenant.Tenant ut = new UserTenant.Tenant();
276 //            ut.setId(at.getId());
277 //            ut.setName(at.getName());
278 //            utl.add(ut);
279 //        }
280 //        userTenant.setTenant(utl);
281 //        return userTenant;
282 //    }
283 }