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