2 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
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
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.
15 * bstefanescu, jcarsique
20 package org.collectionspace.services.nuxeo.client.java;
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;
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;
41 import javax.transaction.TransactionManager;
42 import javax.transaction.UserTransaction;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.aop.framework.ProxyFactory;
49 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
52 public final class NuxeoClientEmbedded {
54 private Logger logger = LoggerFactory.getLogger(NuxeoClientEmbedded.class);
56 private final HashMap<String, CoreSessionInterface> repositoryInstances;
58 private RepositoryManager repositoryMgr;
60 private static final NuxeoClientEmbedded instance = new NuxeoClientEmbedded();
62 private static final int MAX_CREATE_TRANSACTION_ATTEMPTS = 5;
65 * Constructs a new NuxeoClient. NOTE: Using {@link #getInstance()} instead
66 * of this constructor is recommended.
68 private NuxeoClientEmbedded() {
69 repositoryInstances = new HashMap<String, CoreSessionInterface>();
72 public static NuxeoClientEmbedded getInstance() {
76 public synchronized void tryDisconnect() throws Exception {
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();
86 repo.getValue().close();
87 } catch (Exception e) {
88 logger.debug("Error while trying to close " + repo, e);
96 public RepositoryManager getRepositoryManager() throws Exception {
97 if (repositoryMgr == null) {
98 repositoryMgr = Framework.getService(RepositoryManager.class);
100 return repositoryMgr;
104 * Gets the repositories available on the connected server.
106 * @return the repositories
108 public Repository[] getRepositories() throws Exception {
109 Collection<Repository> repos = getRepositoryManager().getRepositories();
110 return repos.toArray(new Repository[repos.size()]);
113 public Repository getDefaultRepository() throws Exception {
114 return getRepositoryManager().getDefaultRepository();
117 public Repository getRepository(String name) throws Exception {
118 return getRepositoryManager().getRepository(name);
122 * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period
124 public CoreSessionInterface openRepository(RepositoryDomainType repoDomain) throws Exception {
125 return openRepository(repoDomain.getRepositoryName(), ServiceContext.DEFAULT_TX_TIMEOUT);
129 * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period
131 public CoreSessionInterface openRepository(String repoName) throws Exception {
132 return openRepository(repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
135 private boolean startTransaction() {
136 boolean startedTransaction = false;
139 if (TransactionHelper.isTransactionActive() == false) {
140 while (startedTransaction == false && attempts <= MAX_CREATE_TRANSACTION_ATTEMPTS) {
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();
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();
159 if (TransactionHelper.isTransactionActiveOrMarkedRollback() == true) {
161 TransactionHelper.commitOrRollbackTransaction();
162 } catch (Exception e) {
163 logger.error("Could not commit or rollback transaction.", e);
170 logger.warn("A request to start a new transaction was made, but a transaction is already open.");
171 startedTransaction = true;
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);
179 return startedTransaction;
182 public CoreSessionInterface openRepository(String repoName, int timeoutSeconds) throws Exception {
183 CoreSessionInterface result = null;
186 // If the called passed in a custom timeout setting, use it to configure Nuxeo's transaction manager.
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.");
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",
205 // Start a new Nuxeo transaction
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);
217 logger.warn("A request to start a new transaction was made, but a transaction is already open.");
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.
224 Repository repository;
225 if (repoName != null) {
226 repository = getRepositoryManager().getRepository(repoName);
228 repository = getRepositoryManager().getDefaultRepository();
229 logger.warn(String.format("Using default repository '%s' because no name was specified.", repository.getName()));
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.
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()));
246 if (repository == null || result == null) {
248 // If we couldn't open a repo session, we need to close the transaction we started.
250 if (startedTransaction == true) {
251 TransactionHelper.commitOrRollbackTransaction();
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);
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.
266 private CoreSessionInterface getAOPProxy(CoreSession repositoryInstance) {
267 CoreSessionInterface result = null;
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);
281 private Principal getSystemPrincipal() {
282 NuxeoPrincipal principal = new SystemPrincipal(null);
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
292 private CoreSessionInterface getCoreSessionWrapper(Repository repository) {
293 CoreSessionInterface result = null;
295 CoreSession coreSession = null;
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);
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);
310 // Since we couldn't get an AOP proxy, we need to close the core session.
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);
322 public void releaseRepository(CoreSessionInterface repoSession) throws Exception {
323 String key = repoSession.getSessionId();
324 String name = repoSession.getRepositoryName();
327 // The caller should have already called the .save() method, but just in
328 // case they didn't, let's try calling it again.
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);
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());
344 logger.trace("Could not remove a repository instance from our repo list. Current count is now: "
345 + repositoryInstances.size());
349 // Last but not least, try to commit the current Nuxeo-related transaction.
351 if (TransactionHelper.isTransactionActiveOrMarkedRollback() == true) {
352 TransactionHelper.commitOrRollbackTransaction();
353 logger.trace(String.format("Transaction closed on thread '%d'", Thread.currentThread().getId()));
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);