]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
d10ab1caf3ae8d509ac06cdfa83902319bcfc5de
[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.common.context;
25
26 import java.lang.reflect.Constructor;
27
28 import javax.ws.rs.core.UriInfo;
29
30 import org.collectionspace.services.common.CollectionSpaceResource;
31 import org.collectionspace.services.common.ResourceMap;
32 import org.collectionspace.services.common.ServiceMain;
33 import org.collectionspace.services.common.config.ConfigUtils;
34 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
35 import org.collectionspace.services.common.document.TransactionException;
36 import org.collectionspace.services.common.security.UnauthorizedException;
37 import org.collectionspace.services.common.storage.StorageClient;
38 import org.collectionspace.services.common.storage.TransactionContext;
39 import org.collectionspace.services.common.storage.jpa.JPATransactionContext;
40 import org.collectionspace.services.config.service.ServiceBindingType;
41 import org.collectionspace.services.config.tenant.TenantBindingType;
42
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * RemoteServiceContextImpl
48  *
49  * $LastChangedRevision: $
50  * $LastChangedDate: $
51  */
52 public class RemoteServiceContextImpl<IT, OT>
53         extends AbstractServiceContextImpl<IT, OT>
54         implements RemoteServiceContext<IT, OT> {
55
56     /** The logger. */
57     final Logger logger = LoggerFactory.getLogger(RemoteServiceContextImpl.class);
58     //input stores original content as received over the wire
59     /** The input. */
60     private IT input;    
61     /** The output. */
62     private OT output;
63     /** The target of the HTTP request **/
64     
65     //
66     // Reference count for things like JPA connections
67     //
68     private int transactionConnectionRefCount = 0;
69     
70     //
71     // RESTEasy context
72     //
73     JaxRsContext jaxRsContext;    
74     ResourceMap resourceMap = null;
75     
76     @Override
77     public void setJaxRsContext(JaxRsContext theJaxRsContext) {
78         this.jaxRsContext = theJaxRsContext;
79     }
80     
81     @Override
82     public JaxRsContext getJaxRsContext() {
83         return this.jaxRsContext;
84     }
85
86     /**
87      * Instantiates a new remote service context impl.
88      * 
89      * @param serviceName the service name
90      * 
91      * @throws UnauthorizedException the unauthorized exception
92      */
93     protected RemoteServiceContextImpl(String serviceName, UriInfo uriInfo) throws UnauthorizedException {
94         super(serviceName, uriInfo);
95     }
96
97     /**
98      * Instantiates a new remote service context impl. (This is "package" protected for the Factory class)
99      * 
100      * @param serviceName the service name
101      * 
102      * @throws UnauthorizedException the unauthorized exception
103      */
104     protected RemoteServiceContextImpl(String serviceName, IT theInput, UriInfo uriInfo) throws UnauthorizedException {
105         this(serviceName, uriInfo);
106         this.input = theInput;        
107     }
108
109     /**
110      * Instantiates a new remote service context impl. (This is "package" protected for the Factory class)
111      * 
112      * @param serviceName the service name
113      * @param theInput the the input
114      * @param queryParams the query params
115      * 
116      * @throws UnauthorizedException the unauthorized exception
117      */
118     protected RemoteServiceContextImpl(String serviceName,
119                 IT theInput,
120                 ResourceMap resourceMap,
121                 UriInfo uriInfo) throws UnauthorizedException {
122         this(serviceName, theInput, uriInfo);
123         this.setResourceMap(resourceMap);
124         this.setUriInfo(uriInfo);
125         if (uriInfo != null) {
126                 this.setQueryParams(uriInfo.getQueryParameters());
127         }
128     }
129
130     /*
131      * Returns the name of the service's acting repository.  Gets this from the tenant and service bindings files
132      */
133     @Override
134         public String getRepositoryName() throws Exception {
135         String result = null;
136         
137         TenantBindingConfigReaderImpl tenantBindingConfigReader = ServiceMain.getInstance().getTenantBindingConfigReader();
138         String tenantId = this.getTenantId();
139         TenantBindingType tenantBindingType = tenantBindingConfigReader.getTenantBinding(tenantId);
140         ServiceBindingType serviceBindingType = this.getServiceBinding();
141         String servicesRepoDomainName = serviceBindingType.getRepositoryDomain();
142         if (servicesRepoDomainName != null && servicesRepoDomainName.trim().isEmpty() == false) {
143                 result = ConfigUtils.getRepositoryName(tenantBindingType, servicesRepoDomainName);
144         } else {
145                 String errMsg = String.format("The '%s' service for tenant ID=%s did not declare a repository domain in its service bindings.", 
146                                 serviceBindingType.getName(), tenantId);
147                 throw new Exception(errMsg);
148         }
149         
150         return result;
151     }
152     
153     /* (non-Javadoc)
154      * @see org.collectionspace.services.common.context.AbstractServiceContextImpl#getInput()
155      */
156     @Override
157     public IT getInput() {
158         return input;
159     }
160
161     /* (non-Javadoc)
162      * @see org.collectionspace.services.common.context.AbstractServiceContextImpl#setInput(java.lang.Object)
163      */
164     @Override
165     public void setInput(IT input) {
166         //for security reasons, do not allow to set input again (from handlers)
167         if (this.input != null) {
168             String msg = "Resetting or changing an context's input is not allowed.";
169             logger.error(msg);
170             throw new IllegalStateException(msg);
171         }
172         this.input = input;
173     }
174
175     /* (non-Javadoc)
176      * @see org.collectionspace.services.common.context.AbstractServiceContextImpl#getOutput()
177      */
178     @Override
179     public OT getOutput() {
180         return output;
181     }
182
183     /* (non-Javadoc)
184      * @see org.collectionspace.services.common.context.AbstractServiceContextImpl#setOutput(java.lang.Object)
185      */
186     @Override
187     public void setOutput(OT output) {
188         this.output = output;
189     }
190
191     /**
192      * Return the JAX-RS resource for the current context.
193      * 
194      * @param ctx
195      * @return
196      * @throws Exception 
197      */
198     public CollectionSpaceResource<IT, OT> getResource(ServiceContext<?, ?> ctx) throws Exception {
199         CollectionSpaceResource<IT, OT> result = null;
200         
201         ResourceMap resourceMap = ctx.getResourceMap();
202         String resourceName = ctx.getClient().getServiceName();
203         result = (CollectionSpaceResource<IT, OT>) resourceMap.get(resourceName);
204         
205         return result;
206     }
207     
208     /**
209      * @return the map of service names to resource classes.
210      */
211     @Override
212     public ResourceMap getResourceMap() {
213         ResourceMap result = resourceMap;
214         
215         if (result == null) {
216                 result = ServiceMain.getInstance().getJaxRSResourceMap();
217         }
218         
219         return result;
220     }
221     
222     /**
223      * @param map the map of service names to resource instances.
224      */
225     @Override
226         public void setResourceMap(ResourceMap map) {
227         this.resourceMap = map;
228     }
229
230  
231     
232     /* (non-Javadoc)
233      * @see org.collectionspace.services.common.context.RemoteServiceContext#getLocalContext(java.lang.String)
234      */
235     @Override
236     public ServiceContext<IT, OT> getLocalContext(String localContextClassName) throws Exception {
237         ClassLoader cloader = Thread.currentThread().getContextClassLoader();
238         Class<?> ctxClass = cloader.loadClass(localContextClassName);
239         if (!ServiceContext.class.isAssignableFrom(ctxClass)) {
240             throw new IllegalArgumentException("getLocalContext requires "
241                     + " implementation of " + ServiceContext.class.getName());
242         }
243
244         Constructor<?> ctor = ctxClass.getConstructor(java.lang.String.class);
245         ServiceContext<IT, OT> ctx = (ServiceContext<IT, OT>) ctor.newInstance(getServiceName());
246         return ctx;
247     }
248
249         @Override
250         public CollectionSpaceResource<IT, OT> getResource() throws Exception {
251                 // TODO Auto-generated method stub
252                 throw new RuntimeException("Unimplemented method.");
253         }
254
255         @Override
256         public CollectionSpaceResource<IT, OT> getResource(String serviceName)
257                         throws Exception {
258                 // TODO Auto-generated method stub
259                 throw new RuntimeException("Unimplemented method.");
260         }
261         
262         //
263         // Transaction management methods
264         //
265         
266         @Override
267         public TransactionContext getCurrentTransactionContext() {
268                 return (TransactionContext) this.getProperty(StorageClient.SC_TRANSACTION_CONTEXT_KEY);
269         }
270
271         @Override
272         synchronized public void closeConnection() throws TransactionException {
273                 if (transactionConnectionRefCount == 0) {
274                         throw new TransactionException("Attempted to release a connection that doesn't exist or has already been released.");
275                 }
276
277                 if (isTransactionContextShared() == true) {
278                         //
279                         // If it's a shared connection, we can't close it.  Just reduce the refcount by 1
280                         //
281                         String warnMsg = "Attempted to release a shared storage connection.  Only the originator can release the connection";
282                         logger.warn(warnMsg);
283                         transactionConnectionRefCount--;
284                 } else {
285                         TransactionContext transactionCtx = getCurrentTransactionContext();
286                         if (transactionCtx != null) {
287                                 if (--transactionConnectionRefCount == 0) {
288                                         transactionCtx.close();
289                                 this.setProperty(StorageClient.SC_TRANSACTION_CONTEXT_KEY, null);
290                                 }
291                         } else {
292                                 throw new TransactionException("Attempted to release a non-existent storage connection.  Transaction context missing from service context.");
293                         }
294                 }
295         }
296
297         @Override
298         synchronized public TransactionContext openConnection() throws TransactionException {
299                 TransactionContext result = getCurrentTransactionContext();
300                 
301                 if (result == null) {
302                         result = new JPATransactionContext(this);
303                 this.setProperty(StorageClient.SC_TRANSACTION_CONTEXT_KEY, result);
304                 }
305                 transactionConnectionRefCount++;
306                 
307                 return result;
308         }
309
310         @Override
311         public void setTransactionContext(TransactionContext transactionCtx) throws TransactionException {
312                 TransactionContext currentTransactionCtx = this.getCurrentTransactionContext();
313                 if (currentTransactionCtx == null) {
314                         setProperty(StorageClient.SC_TRANSACTION_CONTEXT_KEY, transactionCtx);
315                 } else if (currentTransactionCtx != transactionCtx) {
316                         throw new TransactionException("Transaction context already set from service context.");
317                 }
318         }
319
320         /**
321          * Returns true if the TransactionContext is shared with another ServiceContext instance
322          * @throws TransactionException 
323          */
324         @Override
325         public boolean isTransactionContextShared() throws TransactionException {
326                 boolean result = true;
327                 
328                 TransactionContext transactionCtx = getCurrentTransactionContext();
329                 if (transactionCtx != null) {
330                         if (transactionCtx.getServiceContext() == this) {  // check to see if the service context used to create the connection is the same as the current service context
331                                 result = false;
332                         }
333                 } else {
334                         throw new TransactionException("Transaction context missing from service context.");
335                 }
336                 
337                 return result;
338         }
339
340         @Override
341         public boolean hasActiveConnection() {
342                 return getCurrentTransactionContext() != null;
343         }
344 }