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;
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;
39 import javax.transaction.TransactionManager;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.aop.framework.ProxyFactory;
46 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
49 public final class NuxeoClientEmbedded {
51 private Logger logger = LoggerFactory.getLogger(NuxeoClientEmbedded.class);
53 private LoginHandler loginHandler;
55 private final HashMap<String, RepositoryInstanceInterface> repositoryInstances;
57 private InvokerLocator locator;
59 private RepositoryManager repositoryMgr;
61 private static final NuxeoClientEmbedded instance = new NuxeoClientEmbedded();
64 * Constructs a new NuxeoClient. NOTE: Using {@link #getInstance()} instead
65 * of this constructor is recommended.
67 private NuxeoClientEmbedded() {
68 loginHandler = loginHandler == null ? new DefaultLoginHandler()
70 repositoryInstances = new HashMap<String, RepositoryInstanceInterface>();
73 public static NuxeoClientEmbedded getInstance() {
77 public synchronized void tryDisconnect() throws Exception {
78 if (locator == null) {
84 private void doDisconnect() throws Exception {
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();
91 repo.getValue().close();
92 } catch (Exception e) {
93 logger.debug("Error while trying to close " + repo, e);
101 public synchronized boolean isConnected() {
105 public InvokerLocator getLocator() {
109 public synchronized LoginHandler getLoginHandler() {
113 public synchronized void setLoginHandler(LoginHandler loginHandler) {
114 this.loginHandler = loginHandler;
117 public RepositoryManager getRepositoryManager() throws Exception {
118 if (repositoryMgr == null) {
119 repositoryMgr = Framework.getService(RepositoryManager.class);
121 return repositoryMgr;
125 * Gets the repositories available on the connected server.
127 * @return the repositories
129 public Repository[] getRepositories() throws Exception {
130 Collection<Repository> repos = getRepositoryManager().getRepositories();
131 return repos.toArray(new Repository[repos.size()]);
134 public Repository getDefaultRepository() throws Exception {
135 return getRepositoryManager().getDefaultRepository();
138 public Repository getRepository(String name) throws Exception {
139 return getRepositoryManager().getRepository(name);
143 * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period
145 public RepositoryInstanceInterface openRepository(RepositoryDomainType repoDomain) throws Exception {
146 return openRepository(repoDomain.getRepositoryName(), -1);
150 * Open a Nuxeo repo session using the passed in repoDomain and use the default tx timeout period
152 public RepositoryInstanceInterface openRepository(String repoName) throws Exception {
153 return openRepository(repoName, -1);
156 public RepositoryInstanceInterface openRepository(String repoName, int timeoutSeconds) throws Exception {
157 RepositoryInstanceInterface result = null;
160 // If the called passed in a custom timeout setting, use it to configure Nuxeo's transaction manager.
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",
172 // Start a new Nuxeo transaction
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);
183 logger.warn("A request to start a new transaction was made, but a transaction is already open.");
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.
190 Repository repository;
191 if (repoName != null) {
192 repository = getRepositoryManager().getRepository(repoName);
194 repository = getRepositoryManager().getDefaultRepository();
195 logger.warn(String.format("Using default repository '%s' because no name was specified.", repository.getName()));
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.
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()));
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);
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.
223 private RepositoryInstanceInterface getAOPProxy(RepositoryInstance repositoryInstance) {
224 RepositoryInstanceInterface result = null;
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);
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
244 private RepositoryInstanceInterface getRepositoryInstanceWrapper(Repository repository) throws Exception {
245 RepositoryInstanceInterface result = null;
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);
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);
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);
268 public void releaseRepository(RepositoryInstanceInterface repo) throws Exception {
269 String key = repo.getSessionId();
274 } catch (Exception e) {
275 logger.error("Possible data loss. Could not save and/or release the repository.", e);
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());
284 logger.trace("Could not remove a repository instance from our repo list. Current count is now: "
285 + repositoryInstances.size());
288 if (TransactionHelper.isTransactionActiveOrMarkedRollback() == true) {
289 TransactionHelper.commitOrRollbackTransaction();
290 logger.trace(String.format("Transaction closed on thread '%d'", Thread.currentThread().getId()));