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