]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
0547e446b75549fc4de0706c39272755e7ec13d0
[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.repository.RepositoryInstanceWrapperAdvice;
29 import org.collectionspace.services.config.tenant.RepositoryDomainType;
30
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.transaction.TransactionHelper;
39
40 import javax.transaction.TransactionManager;
41
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.aop.framework.ProxyFactory;
45
46 /**
47  * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
48  *
49  */
50 public final class NuxeoClientEmbedded {
51
52         private Logger logger = LoggerFactory.getLogger(NuxeoClientEmbedded.class);
53         
54     private final HashMap<String, CoreSessionInterface> repositoryInstances;
55
56     private RepositoryManager repositoryMgr;
57
58     private static final NuxeoClientEmbedded instance = new NuxeoClientEmbedded();
59         
60     /**
61      * Constructs a new NuxeoClient. NOTE: Using {@link #getInstance()} instead
62      * of this constructor is recommended.
63      */
64     private NuxeoClientEmbedded() {
65         repositoryInstances = new HashMap<String, CoreSessionInterface>();
66     }
67     
68     public static NuxeoClientEmbedded getInstance() {
69         return instance;
70     }
71
72     public synchronized void tryDisconnect() throws Exception {
73         doDisconnect();
74     }
75
76     private void doDisconnect() throws Exception {
77         // close the open Nuxeo repository sessions if any
78         Iterator<Entry<String, CoreSessionInterface>> it = repositoryInstances.entrySet().iterator();
79         while (it.hasNext()) {
80             Entry<String, CoreSessionInterface> repo = it.next();
81             try {
82                 repo.getValue().close();
83             } catch (Exception e) {
84                 logger.debug("Error while trying to close " + repo, e);
85             }
86             it.remove();
87         }
88
89         repositoryMgr = null;
90     }
91
92     public RepositoryManager getRepositoryManager() throws Exception {
93         if (repositoryMgr == null) {
94             repositoryMgr = Framework.getService(RepositoryManager.class);
95         }
96         return repositoryMgr;
97     }
98
99     /**
100      * Gets the repositories available on the connected server.
101      *
102      * @return the repositories
103      */
104     public Repository[] getRepositories() throws Exception {
105         Collection<Repository> repos = getRepositoryManager().getRepositories();
106         return repos.toArray(new Repository[repos.size()]);
107     }
108
109     public Repository getDefaultRepository() throws Exception {
110         return getRepositoryManager().getDefaultRepository();
111     }
112
113     public Repository getRepository(String name) throws Exception {
114         return getRepositoryManager().getRepository(name);
115     }
116
117     /*
118      * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period
119      */
120     public CoreSessionInterface openRepository(RepositoryDomainType repoDomain) throws Exception {
121         return openRepository(repoDomain.getRepositoryName(), -1);
122     }
123     
124     /*
125      * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period
126      */
127     public CoreSessionInterface openRepository(String repoName) throws Exception {
128         return openRepository(repoName, -1);
129     }    
130
131     public CoreSessionInterface openRepository(String repoName, int timeoutSeconds) throws Exception {
132         CoreSessionInterface result = null;
133         
134         //
135         // If the called passed in a custom timeout setting, use it to configure Nuxeo's transaction manager.
136         //
137         if (timeoutSeconds > 0) {
138                 TransactionManager transactionMgr = TransactionHelper.lookupTransactionManager();
139                 transactionMgr.setTransactionTimeout(timeoutSeconds);
140                 if (logger.isInfoEnabled()) {
141                         logger.info(String.format("Changing current request's transaction timeout period to %d seconds",
142                                         timeoutSeconds));
143                 }
144         }
145         
146         //
147         // Start a new Nuxeo transaction
148         //
149         boolean startedTransaction = false;
150         if (TransactionHelper.isTransactionActive() == false) {
151                 startedTransaction = TransactionHelper.startTransaction();
152                 if (startedTransaction == false) {
153                         String errMsg = "Could not start a Nuxeo transaction with the TransactionHelper class.";
154                         logger.error(errMsg);
155                         throw new Exception(errMsg);
156                 }
157         } else {
158                 logger.warn("A request to start a new transaction was made, but a transaction is already open.");
159         }
160         
161         //
162         // From the repository name that the caller passed in, get an instance of Nuxeo's Repository class.
163         // The Repository class is just a metadata description of the repository.
164         //
165         Repository repository;
166         if (repoName != null) {
167                 repository = getRepositoryManager().getRepository(repoName);
168         } else {
169                 repository = getRepositoryManager().getDefaultRepository();
170                 logger.warn(String.format("Using default repository '%s' because no name was specified.", repository.getName()));
171         }
172         
173         //
174         // Using the Repository class, get a Spring AOP proxied instance.  We use Spring AOP to "wrap" all calls to the
175         // Nuxeo repository so we can check for network related failures and perform a series of retries.
176         //
177         if (repository != null) {
178             result = getCoreSessionWrapper(repository);
179                 logger.trace(String.format("A new transaction was started on thread '%d' : %s.",
180                                 Thread.currentThread().getId(), startedTransaction ? "true" : "false"));
181                 logger.trace(String.format("Added a new repository instance to our repo list.  Current count is now: %d",
182                                 repositoryInstances.size()));
183         } else {
184                 String errMsg = String.format("Could not open a session to the Nuxeo repository='%s'", repoName);
185                 logger.error(errMsg);
186                 throw new Exception(errMsg);
187         }       
188         
189         
190         return result;
191     }
192     
193     //
194     // Returns a proxied interface to a Nuxeo repository instance.  Our proxy uses Spring AOP to
195     // wrap each call to the Nuxeo repo with code that catches network related errors/exceptions and
196     // re-attempts the calls to see if it recovers.
197     //
198     private CoreSessionInterface getAOPProxy(CoreSession repositoryInstance) {
199         CoreSessionInterface result = null;
200         
201         try {
202                         ProxyFactory factory = new ProxyFactory(new CoreSessionWrapper(repositoryInstance));
203                         factory.addAdvice(new RepositoryInstanceWrapperAdvice());
204                         factory.setExposeProxy(true);
205                         result = (CoreSessionInterface)factory.getProxy();
206         } catch (Exception e) {
207                 logger.error("Could not create AOP proxy for: " + CoreSessionWrapper.class.getName(), e);
208         }
209         
210         return result;
211     }
212     
213         private Principal getSystemPrincipal() {
214                 NuxeoPrincipal principal = new SystemPrincipal(null);
215                 return principal;
216         }
217
218     /*
219      * From the Repository object (a description of the repository), get repository instance wrapper.  Our wrapper
220      * will using the Spring AOP mechanism to intercept all calls to the repository.  We will wrap all the calls to the
221      * Nuxeo repository and check for network related failures.  We will retry all calls to the Nuxeo repo that fail because
222      * of network erros.
223      */
224     private CoreSessionInterface getCoreSessionWrapper(Repository repository) throws Exception {
225         CoreSessionInterface result = null;
226                 
227         CoreSession coreSession  = CoreInstance.openCoreSession(repository.getName(), getSystemPrincipal());  // A Nuxeo repo instance handler proxy
228         
229         if (coreSession != null) {
230                 result = this.getAOPProxy(coreSession);  // This is our AOP proxy
231                 if (result != null) {
232                         String key = result.getSessionId();
233                         repositoryInstances.put(key, result);
234                 } else {
235                         String errMsg = String.format("Could not instantiate a Spring AOP proxy for class '%s'.",
236                                         CoreSessionWrapper.class.getName());
237                         logger.error(errMsg);
238                         throw new Exception(errMsg);
239                 }
240         } else {
241                 String errMsg = String.format("Could not create a new repository instance for '%s' repository.", repository.getName());
242                 logger.error(errMsg);
243                 throw new Exception(errMsg);
244         }
245         
246         return result;
247     }
248
249     public void releaseRepository(CoreSessionInterface repoSession) throws Exception {
250         String key = repoSession.getSessionId();
251         String name = repoSession.getRepositoryName();
252
253         try {
254                 repoSession.save();
255                 repoSession.close();
256         } catch (Exception e) {
257                 String errMsg = String.format("Possible data loss.  Could not save and/or close the Nuxeo repository name = '%s'.",
258                                 name);
259                 logger.error(errMsg, e);
260                 throw e;
261         } finally {
262                 CoreSessionInterface wasRemoved = repositoryInstances.remove(key);
263             if (logger.isTraceEnabled()) {
264                 if (wasRemoved != null) {
265                         logger.trace("Removed a repository instance from our repo list.  Current count is now: "
266                                         + repositoryInstances.size());
267                 } else {
268                         logger.trace("Could not remove a repository instance from our repo list.  Current count is now: "
269                                         + repositoryInstances.size());
270                 }
271             }
272             if (TransactionHelper.isTransactionActiveOrMarkedRollback() == true) {
273                 TransactionHelper.commitOrRollbackTransaction();
274                 logger.trace(String.format("Transaction closed on thread '%d'", Thread.currentThread().getId()));
275             }
276         }
277     }    
278 }