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.repository.RepositoryInstanceWrapperAdvice;
29 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.transaction.TransactionHelper;
40 import javax.transaction.TransactionManager;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.aop.framework.ProxyFactory;
47 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
50 public final class NuxeoClientEmbedded {
52 private Logger logger = LoggerFactory.getLogger(NuxeoClientEmbedded.class);
54 private final HashMap<String, CoreSessionInterface> repositoryInstances;
56 private RepositoryManager repositoryMgr;
58 private static final NuxeoClientEmbedded instance = new NuxeoClientEmbedded();
61 * Constructs a new NuxeoClient. NOTE: Using {@link #getInstance()} instead
62 * of this constructor is recommended.
64 private NuxeoClientEmbedded() {
65 repositoryInstances = new HashMap<String, CoreSessionInterface>();
68 public static NuxeoClientEmbedded getInstance() {
72 public synchronized void tryDisconnect() throws Exception {
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();
82 repo.getValue().close();
83 } catch (Exception e) {
84 logger.debug("Error while trying to close " + repo, e);
92 public RepositoryManager getRepositoryManager() throws Exception {
93 if (repositoryMgr == null) {
94 repositoryMgr = Framework.getService(RepositoryManager.class);
100 * Gets the repositories available on the connected server.
102 * @return the repositories
104 public Repository[] getRepositories() throws Exception {
105 Collection<Repository> repos = getRepositoryManager().getRepositories();
106 return repos.toArray(new Repository[repos.size()]);
109 public Repository getDefaultRepository() throws Exception {
110 return getRepositoryManager().getDefaultRepository();
113 public Repository getRepository(String name) throws Exception {
114 return getRepositoryManager().getRepository(name);
118 * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period
120 public CoreSessionInterface openRepository(RepositoryDomainType repoDomain) throws Exception {
121 return openRepository(repoDomain.getRepositoryName(), -1);
125 * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period
127 public CoreSessionInterface openRepository(String repoName) throws Exception {
128 return openRepository(repoName, -1);
131 public CoreSessionInterface openRepository(String repoName, int timeoutSeconds) throws Exception {
132 CoreSessionInterface result = null;
135 // If the called passed in a custom timeout setting, use it to configure Nuxeo's transaction manager.
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",
147 // Start a new Nuxeo transaction
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);
158 logger.warn("A request to start a new transaction was made, but a transaction is already open.");
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.
165 Repository repository;
166 if (repoName != null) {
167 repository = getRepositoryManager().getRepository(repoName);
169 repository = getRepositoryManager().getDefaultRepository();
170 logger.warn(String.format("Using default repository '%s' because no name was specified.", repository.getName()));
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.
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()));
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);
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.
198 private CoreSessionInterface getAOPProxy(CoreSession repositoryInstance) {
199 CoreSessionInterface result = null;
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);
213 private Principal getSystemPrincipal() {
214 NuxeoPrincipal principal = new SystemPrincipal(null);
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
224 private CoreSessionInterface getCoreSessionWrapper(Repository repository) throws Exception {
225 CoreSessionInterface result = null;
227 CoreSession coreSession = CoreInstance.openCoreSession(repository.getName(), getSystemPrincipal()); // A Nuxeo repo instance handler proxy
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);
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);
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);
249 public void releaseRepository(CoreSessionInterface repoSession) throws Exception {
250 String key = repoSession.getSessionId();
251 String name = repoSession.getRepositoryName();
256 } catch (Exception e) {
257 String errMsg = String.format("Possible data loss. Could not save and/or close the Nuxeo repository name = '%s'.",
259 logger.error(errMsg, e);
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());
268 logger.trace("Could not remove a repository instance from our repo list. Current count is now: "
269 + repositoryInstances.size());
272 if (TransactionHelper.isTransactionActiveOrMarkedRollback() == true) {
273 TransactionHelper.commitOrRollbackTransaction();
274 logger.trace(String.format("Transaction closed on thread '%d'", Thread.currentThread().getId()));