]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
b3904c0aa8f87b2cdd2c856c6a1d8f7a5baa66d7
[tmp/jakarta-migration.git] /
1 /*
2  * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
3  *
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the GNU Lesser General Public License
6  * (LGPL) version 2.1 which accompanies this distribution, and is available at
7  * http://www.gnu.org/licenses/lgpl.html
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * Contributors:
15  *     bstefanescu, jcarsique
16  *
17  * $Id$
18  */
19
20 package org.collectionspace.services.nuxeo.client.java;
21
22 import java.util.Collection;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.Map.Entry;
26 import java.security.Principal;
27
28 import org.collectionspace.services.common.context.ServiceContext;
29 import org.collectionspace.services.common.repository.RepositoryInstanceWrapperAdvice;
30 import org.collectionspace.services.config.tenant.RepositoryDomainType;
31 import org.nuxeo.ecm.core.api.repository.Repository;
32 import org.nuxeo.ecm.core.api.CoreInstance;
33 import org.nuxeo.ecm.core.api.CoreSession;
34 import org.nuxeo.ecm.core.api.NuxeoPrincipal;
35 import org.nuxeo.ecm.core.api.SystemPrincipal;
36 import org.nuxeo.ecm.core.api.repository.RepositoryManager;
37 import org.nuxeo.runtime.api.Framework;
38 import org.nuxeo.runtime.jtajca.NuxeoContainer;
39 import org.nuxeo.runtime.transaction.TransactionHelper;
40
41 import javax.transaction.TransactionManager;
42 import javax.transaction.UserTransaction;
43
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.aop.framework.ProxyFactory;
47
48 /**
49  * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
50  *
51  */
52 public final class NuxeoClientEmbedded {
53
54         private Logger logger = LoggerFactory.getLogger(NuxeoClientEmbedded.class);
55         
56     private final HashMap<String, CoreSessionInterface> repositoryInstances;
57
58     private RepositoryManager repositoryMgr;
59
60     private static final NuxeoClientEmbedded instance = new NuxeoClientEmbedded();
61
62         private static final int MAX_CREATE_TRANSACTION_ATTEMPTS = 5;
63         
64     /**
65      * Constructs a new NuxeoClient. NOTE: Using {@link #getInstance()} instead
66      * of this constructor is recommended.
67      */
68     private NuxeoClientEmbedded() {
69         repositoryInstances = new HashMap<String, CoreSessionInterface>();
70     }
71     
72     public static NuxeoClientEmbedded getInstance() {
73         return instance;
74     }
75
76     public synchronized void tryDisconnect() throws Exception {
77         doDisconnect();
78     }
79
80     private void doDisconnect() throws Exception {
81         // close the open Nuxeo repository sessions if any
82         Iterator<Entry<String, CoreSessionInterface>> it = repositoryInstances.entrySet().iterator();
83         while (it.hasNext()) {
84             Entry<String, CoreSessionInterface> repo = it.next();
85             try {
86                 repo.getValue().close();
87             } catch (Exception e) {
88                 logger.debug("Error while trying to close " + repo, e);
89             }
90             it.remove();
91         }
92
93         repositoryMgr = null;
94     }
95
96     public RepositoryManager getRepositoryManager() throws Exception {
97         if (repositoryMgr == null) {
98             repositoryMgr = Framework.getService(RepositoryManager.class);
99         }
100         return repositoryMgr;
101     }
102
103     /**
104      * Gets the repositories available on the connected server.
105      *
106      * @return the repositories
107      */
108     public Repository[] getRepositories() throws Exception {
109         Collection<Repository> repos = getRepositoryManager().getRepositories();
110         return repos.toArray(new Repository[repos.size()]);
111     }
112
113     public Repository getDefaultRepository() throws Exception {
114         return getRepositoryManager().getDefaultRepository();
115     }
116
117     public Repository getRepository(String name) throws Exception {
118         return getRepositoryManager().getRepository(name);
119     }
120
121     /*
122      * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period
123      */
124     public CoreSessionInterface openRepository(RepositoryDomainType repoDomain) throws Exception {
125         return openRepository(repoDomain.getRepositoryName(), ServiceContext.DEFAULT_TX_TIMEOUT);
126     }
127     
128     /*
129      * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period
130      */
131     public CoreSessionInterface openRepository(String repoName) throws Exception {
132         return openRepository(repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
133     }
134     
135     private boolean startTransaction() {
136         boolean startedTransaction = false;
137         int attempts = 0;
138         
139         if (TransactionHelper.isTransactionActive() == false) {
140                 while (startedTransaction == false && attempts <= MAX_CREATE_TRANSACTION_ATTEMPTS) {                    
141                         try {
142                                 startedTransaction = TransactionHelper.startTransaction();
143                         } catch (Exception e) {
144                                 String traceMsg = String.format("Could not start a new transaction on thread '%d'", Thread.currentThread().getId());
145                                 logger.trace(traceMsg);
146                                 boolean txState = TransactionHelper.isTransactionActive();
147                                 txState = TransactionHelper.isNoTransaction();
148                                 txState = TransactionHelper.isTransactionActiveOrMarkedRollback();
149                                 txState = TransactionHelper.isTransactionMarkedRollback();
150                         }
151                         
152                 if (startedTransaction == false) {
153                         long currentThreadId = Thread.currentThread().getId();
154                                 boolean txState = TransactionHelper.isTransactionActive();
155                                 txState = TransactionHelper.isNoTransaction();
156                                 txState = TransactionHelper.isTransactionActiveOrMarkedRollback();
157                                 txState = TransactionHelper.isTransactionMarkedRollback();
158                                 
159                                 if (TransactionHelper.isTransactionActiveOrMarkedRollback() == true) {
160                                         try {
161                                                 TransactionHelper.commitOrRollbackTransaction();
162                                         } catch (Exception e) {
163                                                 logger.error("Could not commit or rollback transaction.", e);
164                                         }
165                                 }
166                 }
167                         attempts++;
168                 }
169         } else {
170                 logger.warn("A request to start a new transaction was made, but a transaction is already open.");
171                 startedTransaction = true;
172         }
173                 
174                 if (startedTransaction == false) {
175                         String errMsg = String.format("Attempted %d time(s) to start a new transaction, but failed.", attempts);
176                 logger.error(errMsg);
177         }
178
179                 return startedTransaction;
180     }
181
182     public CoreSessionInterface openRepository(String repoName, int timeoutSeconds) throws Exception {
183         CoreSessionInterface result = null;
184         
185         //
186         // If the called passed in a custom timeout setting, use it to configure Nuxeo's transaction manager.
187         //
188         if (timeoutSeconds > 0) {
189                 TransactionManager transactionMgr = TransactionHelper.lookupTransactionManager();
190             TransactionManager tm = NuxeoContainer.getTransactionManager();
191             if (logger.isDebugEnabled()) {
192                 if (tm != transactionMgr) {
193                         logger.debug("TransactionHelper's manager is different than NuxeoContainer's.");
194                 }
195             }
196                 
197                 transactionMgr.setTransactionTimeout(timeoutSeconds); // For the current thread only
198                 if (logger.isInfoEnabled()) {
199                         logger.info(String.format("Changing current request's transaction timeout period to %d seconds",
200                                         timeoutSeconds));
201                 }
202         }
203         
204         //
205         // Start a new Nuxeo transaction
206         //
207         boolean startedTransaction = false;
208         if (TransactionHelper.isTransactionActive() == false) {
209                 startedTransaction = startTransaction();
210                 if (startedTransaction == false) {
211                         String errMsg = String.format("Could not start a Nuxeo transaction with the TransactionHelper class on thread '%d'.",
212                                         Thread.currentThread().getId());
213                         logger.error(errMsg);
214                         throw new Exception(errMsg);
215                 }
216         } else {
217                 logger.warn("A request to start a new transaction was made, but a transaction is already open.");
218         }
219         
220         //
221         // From the repository name that the caller passed in, get an instance of Nuxeo's Repository class.
222         // The Repository class is just a metadata description of the repository.
223         //
224         Repository repository;
225         if (repoName != null) {
226                 repository = getRepositoryManager().getRepository(repoName);
227         } else {
228                 repository = getRepositoryManager().getDefaultRepository();
229                 logger.warn(String.format("Using default repository '%s' because no name was specified.", repository.getName()));
230         }
231         
232         //
233         // Using the Repository class, get a Spring AOP proxied instance.  We use Spring AOP to "wrap" all calls to the
234         // Nuxeo repository so we can check for network related failures and perform a series of retries.
235         //
236         if (repository != null) {
237             result = getCoreSessionWrapper(repository);
238                 logger.trace(String.format("A new transaction was started on thread '%d' : %s.",
239                                 Thread.currentThread().getId(), startedTransaction ? "true" : "false"));
240                 logger.trace(String.format("Added a new repository instance to our repo list.  Current count is now: %d",
241                                 repositoryInstances.size()));
242         } else {
243                 //
244                 // If we couldn't open a repo session, we need to close the transaction we started.
245                 //
246                 if (startedTransaction == true) {
247                         TransactionHelper.commitOrRollbackTransaction();
248                 }
249                 String errMsg = String.format("Could not open a session to the Nuxeo repository='%s'", repoName);
250                 logger.error(errMsg);
251                 throw new Exception(errMsg);
252         }       
253         
254         return result;
255     }
256     
257     //
258     // Returns a proxied interface to a Nuxeo repository instance.  Our proxy uses Spring AOP to
259     // wrap each call to the Nuxeo repo with code that catches network related errors/exceptions and
260     // re-attempts the calls to see if it recovers.
261     //
262     private CoreSessionInterface getAOPProxy(CoreSession repositoryInstance) {
263         CoreSessionInterface result = null;
264         
265         try {
266                         ProxyFactory factory = new ProxyFactory(new CoreSessionWrapper(repositoryInstance));
267                         factory.addAdvice(new RepositoryInstanceWrapperAdvice());
268                         factory.setExposeProxy(true);
269                         result = (CoreSessionInterface)factory.getProxy();
270         } catch (Exception e) {
271                 logger.error("Could not create AOP proxy for: " + CoreSessionWrapper.class.getName(), e);
272         }
273         
274         return result;
275     }
276     
277         private Principal getSystemPrincipal() {
278                 NuxeoPrincipal principal = new SystemPrincipal(null);
279                 return principal;
280         }
281
282     /*
283      * From the Repository object (a description of the repository), get repository instance wrapper.  Our wrapper
284      * will using the Spring AOP mechanism to intercept all calls to the repository.  We will wrap all the calls to the
285      * Nuxeo repository and check for network related failures.  We will retry all calls to the Nuxeo repo that fail because
286      * of network erros.
287      */
288     private CoreSessionInterface getCoreSessionWrapper(Repository repository) throws Exception {
289         CoreSessionInterface result = null;
290                 
291         CoreSession coreSession  = CoreInstance.openCoreSession(repository.getName(), getSystemPrincipal());  // A Nuxeo repo instance handler proxy
292         
293         if (coreSession != null) {
294                 result = this.getAOPProxy(coreSession);  // This is our AOP proxy
295                 if (result != null) {
296                         String key = result.getSessionId();
297                         repositoryInstances.put(key, result);
298                 } else {
299                         String errMsg = String.format("Could not instantiate a Spring AOP proxy for class '%s'.",
300                                         CoreSessionWrapper.class.getName());
301                         logger.error(errMsg);
302                         throw new Exception(errMsg);
303                 }
304         } else {
305                 String errMsg = String.format("Could not create a new repository instance for '%s' repository.", repository.getName());
306                 logger.error(errMsg);
307                 throw new Exception(errMsg);
308         }
309         
310         return result;
311     }
312
313     public void releaseRepository(CoreSessionInterface repoSession) throws Exception {
314         String key = repoSession.getSessionId();
315         String name = repoSession.getRepositoryName();
316
317         //
318         // The caller should have already called the .save() method, but just in
319         // case they didn't, let's try calling it again.
320         //
321         try {
322                 repoSession.save();
323         } catch (Exception e) {
324                 String errMsg = String.format("Possible data loss.  Could not save and/or close the Nuxeo repository name = '%s'.", name);
325                 logger.trace(errMsg, e);
326                 throw e;
327         } finally {
328                 repoSession.close();
329                 CoreSessionInterface wasRemoved = repositoryInstances.remove(key);
330             if (logger.isTraceEnabled()) {
331                 if (wasRemoved != null) {
332                         logger.trace("Removed a repository instance from our repo list.  Current count is now: "
333                                         + repositoryInstances.size());
334                 } else {
335                         logger.trace("Could not remove a repository instance from our repo list.  Current count is now: "
336                                         + repositoryInstances.size());
337                 }
338             }            
339             //
340             // Last but not least, try to commit the current Nuxeo-related transaction.
341             //
342             if (TransactionHelper.isTransactionActiveOrMarkedRollback() == true) {
343                 TransactionHelper.commitOrRollbackTransaction();
344                 logger.trace(String.format("Transaction closed on thread '%d'", Thread.currentThread().getId()));
345             } else {
346                 String warnMsg = String.format("Closed a Nuxeo repository session on thread '%d' without closing the containing transaction.",
347                                 Thread.currentThread().getId());
348                 logger.warn(warnMsg);
349             }
350         }
351     }    
352 }