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:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
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.
24 package org.collectionspace.services.account.storage;
26 import java.util.Date;
27 import java.util.HashMap;
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;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
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.
56 @SuppressWarnings({ "rawtypes", "unchecked" })
57 public class AccountStorageClient extends JpaStorageClientImpl {
59 private final Logger logger = LoggerFactory.getLogger(AccountStorageClient.class);
60 private UserStorageClient userStorageClient = new UserStorageClient();
62 public AccountStorageClient() {
66 public String create(ServiceContext ctx,
67 DocumentHandler handler) throws BadRequestException,
71 AccountsCommon account = null;
72 JPATransactionContext jpaConnectionContext = (JPATransactionContext)ctx.openConnection();
74 account = (AccountsCommon) handler.getCommonPart();
75 handler.prepare(Action.CREATE);
76 DocumentWrapper<AccountsCommon> wrapDoc = new DocumentWrapperImpl<AccountsCommon>(account);
77 handler.handle(Action.CREATE, wrapDoc);
78 jpaConnectionContext.beginTransaction();
80 // If userid and password are given, add to default ID provider -i.e., add it to the Spring Security account list
82 if (account.getUserId() != null && isForCSpaceIdentityProvider(account.getPassword())) {
83 User user = userStorageClient.create(account.getUserId(), account.getPassword());
84 jpaConnectionContext.persist(user);
87 // Now add the account to the CSpace list of accounts
89 account.setCreatedAtItem(new Date());
90 jpaConnectionContext.persist(account);
92 // Finish creating related resources -e.g., account-role relationships
94 handler.complete(Action.CREATE, wrapDoc);
95 jpaConnectionContext.commitTransaction();
97 result = (String)JaxbUtils.getValue(account, "getCsid");
98 } catch (BadRequestException bre) {
99 jpaConnectionContext.markForRollback();
101 } catch (Exception e) {
102 if (logger.isDebugEnabled()) {
103 logger.debug("Caught exception ", e);
105 boolean uniqueConstraint = false;
106 if (userStorageClient.get(ctx, account.getUserId()) != null) {
107 //might be unique constraint violation
108 uniqueConstraint = true;
111 jpaConnectionContext.markForRollback();
113 if (uniqueConstraint) {
114 String msg = "UserId exists. Non unique userId=" + account.getUserId();
116 throw new BadRequestException(msg);
118 throw new DocumentException(e);
120 ctx.closeConnection();
127 public void get(ServiceContext ctx, String id, DocumentHandler handler)
128 throws DocumentNotFoundException, DocumentException {
129 DocumentFilter docFilter = handler.getDocumentFilter();
130 if (docFilter == null) {
131 docFilter = handler.createDocumentFilter();
134 JPATransactionContext jpaTransactionContext = (JPATransactionContext)ctx.openConnection();
136 handler.prepare(Action.GET);
138 String whereClause = " JOIN a.tenants as at where csid = :csid and at.tenantId = :tenantId";
139 HashMap<String, Object> params = new HashMap<String, Object>();
140 params.put("csid", id);
141 params.put("tenantId", ctx.getTenantId());
143 o = JpaStorageUtils.getEntity(jpaTransactionContext,
144 "org.collectionspace.services.account.AccountsCommon", whereClause, params);
146 String msg = "could not find entity with id=" + id;
147 throw new DocumentNotFoundException(msg);
149 DocumentWrapper<Object> wrapDoc = new DocumentWrapperImpl<Object>(o);
150 handler.handle(Action.GET, wrapDoc);
151 handler.complete(Action.GET, wrapDoc);
152 } catch (DocumentException de) {
154 } catch (Exception e) {
155 if (logger.isDebugEnabled()) {
156 logger.debug("Caught exception ", e);
158 throw new DocumentException(e);
160 ctx.closeConnection();
166 public void update(ServiceContext ctx, String id, DocumentHandler handler)
167 throws BadRequestException, DocumentNotFoundException,
170 JPATransactionContext jpaConnectionContext = (JPATransactionContext)ctx.openConnection();
172 jpaConnectionContext.beginTransaction();
174 handler.prepare(Action.UPDATE);
175 AccountsCommon accountReceived = (AccountsCommon) handler.getCommonPart();
176 AccountsCommon accountFound = getAccount(jpaConnectionContext, id);
177 checkAllowedUpdates(accountReceived, accountFound);
178 //if userid and password are given, add to default id provider
179 // Note that this ignores the immutable flag, as we allow
181 if (accountReceived.getUserId() != null && isForCSpaceIdentityProvider(accountReceived.getPassword())) {
182 userStorageClient.update(jpaConnectionContext,
183 accountReceived.getUserId(),
184 accountReceived.getPassword());
186 DocumentWrapper<AccountsCommon> wrapDoc =
187 new DocumentWrapperImpl<AccountsCommon>(accountFound);
188 handler.handle(Action.UPDATE, wrapDoc);
189 handler.complete(Action.UPDATE, wrapDoc);
191 jpaConnectionContext.commitTransaction();
192 } catch (BadRequestException bre) {
193 jpaConnectionContext.markForRollback();
195 } catch (DocumentException de) {
196 jpaConnectionContext.markForRollback();
198 } catch (Exception e) {
199 jpaConnectionContext.markForRollback();
200 throw new DocumentException(e);
202 ctx.closeConnection();
207 public void delete(ServiceContext ctx, String id)
208 throws DocumentNotFoundException,
211 if (logger.isDebugEnabled()) {
212 logger.debug("deleting entity with id=" + id);
215 JPATransactionContext jpaConnectionContext = (JPATransactionContext)ctx.openConnection();
217 AccountsCommon accountFound = getAccount(jpaConnectionContext, id);
218 jpaConnectionContext.beginTransaction();
219 //if userid gives any indication about the id provider, it should
220 //be used to avoid delete
221 userStorageClient.delete(jpaConnectionContext, accountFound.getUserId());
222 jpaConnectionContext.remove(accountFound);
223 jpaConnectionContext.commitTransaction();
224 } catch (DocumentException de) {
225 jpaConnectionContext.markForRollback();
227 } catch (Exception e) {
228 if (logger.isDebugEnabled()) {
229 logger.debug("Caught exception ", e);
231 jpaConnectionContext.markForRollback();
232 throw new DocumentException(e);
234 ctx.closeConnection();
238 private AccountsCommon getAccount(JPATransactionContext jpaConnectionContext, String id) throws DocumentNotFoundException {
239 AccountsCommon accountFound = (AccountsCommon) jpaConnectionContext.find(AccountsCommon.class, id);
240 if (accountFound == null) {
241 String msg = "could not find account with id=" + id;
243 throw new DocumentNotFoundException(msg);
249 private boolean checkAllowedUpdates(AccountsCommon toAccount, AccountsCommon fromAccount) throws BadRequestException {
250 if (!fromAccount.getUserId().equals(toAccount.getUserId())) {
251 String msg = "userId=" + toAccount.getUserId() + " of existing account does not match "
252 + "the userId=" + fromAccount.getUserId()
253 + " with csid=" + fromAccount.getCsid();
255 if (logger.isDebugEnabled()) {
256 logger.debug(msg + " found userid=" + fromAccount.getUserId());
258 throw new BadRequestException(msg);
264 * isForCSIdP deteremines if the create/update is also needed for CS IdP
268 private boolean isForCSpaceIdentityProvider(byte[] bpass) {
269 return bpass != null && bpass.length > 0;
271 // private UserTenant createTenantAssoc(AccountsCommon accountReceived) {
272 // UserTenant userTenant = new UserTenant();
273 // userTenant.setUserId(accountReceived.getUserId());
274 // List<AccountsCommon.Tenant> atl = accountReceived.getTenant();
275 // List<UserTenant.Tenant> utl =
276 // new ArrayList<UserTenant.Tenant>();
277 // for (AccountsCommon.Tenant at : atl) {
278 // UserTenant.Tenant ut = new UserTenant.Tenant();
279 // ut.setId(at.getId());
280 // ut.setName(at.getName());
283 // userTenant.setTenant(utl);
284 // return userTenant;