]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
5d192f2151551c513798e10ef7061bf74439bad0
[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             if (result != null) {
239                         logger.trace(String.format("A new transaction was started on thread '%d' : %s.",
240                                         Thread.currentThread().getId(), startedTransaction ? "true" : "false"));
241                         logger.trace(String.format("Added a new repository instance to our repo list.  Current count is now: %d",
242                                         repositoryInstances.size()));
243             }
244         }
245         
246         if (repository == null || result == null) {
247                 //
248                 // If we couldn't open a repo session, we need to close the transaction we started.
249                 //
250                 if (startedTransaction == true) {
251                         TransactionHelper.commitOrRollbackTransaction();
252                 }
253                 String errMsg = String.format("Could not open a session to the Nuxeo repository='%s'", repoName);
254                 logger.error(errMsg);
255                 throw new Exception(errMsg);
256         }       
257         
258         return result;
259     }
260     
261     //
262     // Returns a proxied interface to a Nuxeo repository instance.  Our proxy uses Spring AOP to
263     // wrap each call to the Nuxeo repo with code that catches network related errors/exceptions and
264     // re-attempts the calls to see if it recovers.
265     //
266     private CoreSessionInterface getAOPProxy(CoreSession repositoryInstance) {
267         CoreSessionInterface result = null;
268         
269         try {
270                         ProxyFactory factory = new ProxyFactory(new CoreSessionWrapper(repositoryInstance));
271                         factory.addAdvice(new RepositoryInstanceWrapperAdvice());
272                         factory.setExposeProxy(true);
273                         result = (CoreSessionInterface)factory.getProxy();
274         } catch (Exception e) {
275                 logger.error("Could not create AOP proxy for: " + CoreSessionWrapper.class.getName(), e);
276         }
277         
278         return result;
279     }
280     
281         private Principal getSystemPrincipal() {
282                 NuxeoPrincipal principal = new SystemPrincipal(null);
283                 return principal;
284         }
285
286     /*
287      * From the Repository object (a description of the repository), get repository instance wrapper.  Our wrapper
288      * will using the Spring AOP mechanism to intercept all calls to the repository.  We will wrap all the calls to the
289      * Nuxeo repository and check for network related failures.  We will retry all calls to the Nuxeo repo that fail because
290      * of network erros.
291      */
292     private CoreSessionInterface getCoreSessionWrapper(Repository repository) {
293         CoreSessionInterface result = null;
294                 
295         CoreSession coreSession = null;
296         try {
297                 coreSession = CoreInstance.openCoreSession(repository.getName(), getSystemPrincipal());  // A Nuxeo repo instance handler proxy
298         } catch (Exception e) {
299                 logger.warn(String.format("Could not open a session to the '%s' repository.  The current request to the CollectionSpace services API will fail.",
300                                 repository != null ? repository.getName() : "not specified"), e);
301         }
302         
303         if (coreSession != null) {
304                 result = this.getAOPProxy(coreSession);  // This is our AOP proxy
305                 if (result != null) {
306                         String key = result.getSessionId();
307                         repositoryInstances.put(key, result);
308                 } else {
309                         //
310                         // Since we couldn't get an AOP proxy, we need to close the core session.
311                         //
312                         CoreInstance.closeCoreSession(coreSession);
313                         String errMsg = String.format("Could not instantiate a Spring AOP proxy for class '%s'.",
314                                         CoreSessionWrapper.class.getName());
315                         logger.error(errMsg);
316                 }
317         }
318         
319         return result;
320     }
321
322     public void releaseRepository(CoreSessionInterface repoSession) throws Exception {
323         String key = repoSession.getSessionId();
324         String name = repoSession.getRepositoryName();
325
326         //
327         // The caller should have already called the .save() method, but just in
328         // case they didn't, let's try calling it again.
329         //
330         try {
331                 repoSession.save();
332         } catch (Exception e) {
333                 String errMsg = String.format("Possible data loss.  Could not save and/or close the Nuxeo repository name = '%s'.", name);
334                 logger.trace(errMsg, e);
335                 throw e;
336         } finally {
337                 repoSession.close();
338                 CoreSessionInterface wasRemoved = repositoryInstances.remove(key);
339             if (logger.isTraceEnabled()) {
340                 if (wasRemoved != null) {
341                         logger.trace("Removed a repository instance from our repo list.  Current count is now: "
342                                         + repositoryInstances.size());
343                 } else {
344                         logger.trace("Could not remove a repository instance from our repo list.  Current count is now: "
345                                         + repositoryInstances.size());
346                 }
347             }            
348             //
349             // Last but not least, try to commit the current Nuxeo-related transaction.
350             //
351             if (TransactionHelper.isTransactionActiveOrMarkedRollback() == true) {
352                 TransactionHelper.commitOrRollbackTransaction();
353                 logger.trace(String.format("Transaction closed on thread '%d'", Thread.currentThread().getId()));
354             } else {
355                 String warnMsg = String.format("Closed a Nuxeo repository session on thread '%d' without closing the containing transaction.",
356                                 Thread.currentThread().getId());
357                 logger.warn(warnMsg);
358             }
359         }
360     }    
361 }