1 package org.collectionspace.services.nuxeo.client.java;
4 import java.io.IOException;
5 import java.util.Hashtable;
6 import java.util.Iterator;
8 import javax.servlet.ServletContext;
10 import org.apache.catalina.util.ServerInfo;
11 import org.collectionspace.services.common.api.JEEServerDeployment;
12 import org.collectionspace.services.config.RepositoryClientConfigType;
13 import org.collectionspace.services.config.tenant.RepositoryDomainType;
14 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
15 import org.nuxeo.ecm.core.api.CoreInstance;
16 import org.nuxeo.ecm.core.api.CoreSession;
17 import org.nuxeo.ecm.core.api.DocumentModel;
18 import org.nuxeo.ecm.core.api.DocumentModelList;
19 import org.nuxeo.ecm.core.api.SystemPrincipal;
20 import org.nuxeo.ecm.core.api.repository.Repository;
21 import org.nuxeo.ecm.core.api.repository.RepositoryManager;
22 import org.nuxeo.osgi.application.MutableClassLoaderDelegate;
23 import org.nuxeo.runtime.api.Framework;
24 import org.nuxeo.runtime.transaction.TransactionHelper;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
28 public class NuxeoConnectorEmbedded {
30 <host>127.0.0.1</host>
31 <port>62474</port> <!-- java -->
33 private Logger logger = LoggerFactory.getLogger(NuxeoConnectorEmbedded.class);
35 public final static String NUXEO_CLIENT_DIR = JEEServerDeployment.NUXEO_CLIENT_DIR;
36 public final static String NUXEO_SERVER_DIR = JEEServerDeployment.NUXEO_SERVER_DIR;
37 private final static String ERROR_CONNECTOR_NOT_INITIALIZED = "NuxeoConnector is not initialized!";
39 private final static String CSPACE_NUXEO_HOME = "CSPACE_NUXEO_HOME";
41 private static final NuxeoConnectorEmbedded self = new NuxeoConnectorEmbedded();
42 private NuxeoClientEmbedded client;
43 private volatile boolean initialized = false; // use volatile for lazy
46 public NuxeoFrameworkBootstrap fb;
47 private ServletContext servletContext;
48 private RepositoryClientConfigType repositoryClientConfig;
50 private NuxeoConnectorEmbedded() {
54 public final static NuxeoConnectorEmbedded getInstance() {
58 private String getNuxeoServerPath(String serverRootPath) throws IOException {
61 // Look for the CSPACE_NUXEO_HOME environment variable that might contain the fully qualified path of the
62 // Nuxeo EP configuration directory.
64 String prop = System.getenv(CSPACE_NUXEO_HOME);
65 if (prop != null && !prop.isEmpty()) {
69 // Could not find the 'CSPACE_NUXEO_HOME' environment variable, so using the default location instead.
71 result = serverRootPath + "/" + NUXEO_SERVER_DIR;
77 private File getNuxeoServerDir(String serverRootPath) throws IOException {
81 String path = getNuxeoServerPath(serverRootPath);
83 File temp = new File(path);
84 if (temp.exists() == true) {
87 errMsg = "The Nuxeo EP configuration directory is missing or inaccessible at: '" + path + "'.";
93 path = path != null ? path : "<empty>";
94 errMsg = "Unknown error trying to find Nuxeo configuration: '" +
95 CSPACE_NUXEO_HOME + "' = " +
98 throw new IOException(errMsg);
105 // Start/boot the Nuxeo EP server instance
107 private void startNuxeoEP(String serverRootPath) throws Exception {
108 File nuxeoHomeDir = getNuxeoServerDir(serverRootPath);
110 if (logger.isInfoEnabled() == true) {
111 logger.info("Starting Nuxeo EP server from configuration at: "
112 + nuxeoHomeDir.getCanonicalPath());
115 ClassLoader cl = NuxeoConnectorEmbedded.class.getClassLoader();
117 fb = new NuxeoFrameworkBootstrap(cl, nuxeoHomeDir);
118 fb.setHostName("Tomcat");
119 fb.setHostVersion(ServerInfo.getServerNumber());
122 fb.start(new MutableClassLoaderDelegate(cl));
124 // Test to see if we can connect to the default repository
125 boolean transactionStarted = false;
127 if (!TransactionHelper.isTransactionActiveOrMarkedRollback()) {
128 transactionStarted = TransactionHelper.startTransaction();
131 CoreSession coreSession = null;
134 Repository defaultRepo = Framework.getService(RepositoryManager.class).getDefaultRepository();
135 coreSession = CoreInstance.openCoreSession(defaultRepo.getName(), new SystemPrincipal(null));
136 } catch (Throwable t) {
137 logger.error(t.getMessage());
138 throw new RuntimeException("Could not start the Nuxeo EP Framework", t);
140 if (coreSession != null) {
141 CoreInstance.closeCoreSession(coreSession);
144 if (transactionStarted) {
145 TransactionHelper.commitOrRollbackTransaction();
151 * release releases resources occupied by Nuxeo remoting client runtime
153 * @throws java.lang.Exception
155 public void release() throws Exception {
156 if (initialized == true) {
158 client.tryDisconnect();
159 } catch (Exception e) {
160 logger.error("Failed to disconnect Nuxeo connection.", e);
166 public void initialize(String serverRootPath,
167 RepositoryClientConfigType repositoryClientConfig,
168 ServletContext servletContext) throws Exception {
169 if (initialized == false) {
170 synchronized (this) {
171 if (initialized == false) {
172 this.servletContext = servletContext;
173 this.repositoryClientConfig = repositoryClientConfig;
174 startNuxeoEP(serverRootPath);
175 client = NuxeoClientEmbedded.getInstance();
183 * releaseRepositorySession releases given repository session
186 * @throws java.lang.Exception
188 public void releaseRepositorySession(CoreSessionInterface repoSession)
190 if (repoSession != null) {
191 getClient().releaseRepository(repoSession);
193 if (logger.isDebugEnabled()) {
194 logger.debug("releaseRepositorySession() released repository session");
200 * getRepositorySession get session to default repository
202 * @return RepositoryInstance
203 * @throws java.lang.Exception
205 public CoreSessionInterface getRepositorySession(RepositoryDomainType repoDomain) throws Exception {
206 CoreSessionInterface repoSession = getClient().openRepository(repoDomain);
208 if (logger.isDebugEnabled() && repoSession != null) {
209 String repoName = repoDomain.getRepositoryName();
210 logger.debug("getRepositorySession() opened repository session on: %s repo",
211 repoName != null ? repoName : "unknown");
218 // TODO: Remove after CSPACE-6375 issue is resolved.
219 // public List<RepositoryDescriptor> getRepositoryDescriptor(String name) throws Exception {
220 // RepositoryDescriptor repo = null;
221 // RepositoryManager repositoryManager = Framework.getService(RepositoryManager.class);
222 // Iterable<RepositoryDescriptor> descriptorsList = repositoryManager.getDescriptors();
223 // for (RepositoryDescriptor descriptor : descriptorsList) {
224 // String homeDir = descriptor.getHomeDirectory();
225 // String config = descriptor.getConfigurationFile();
226 // RepositoryFactory factor = descriptor.getFactory();
233 * getClient get Nuxeo client for accessing Nuxeo services remotely using
234 * Nuxeo Java (EJB) Remote APIS
236 * @return NuxeoClient
237 * @throws java.lang.Exception
239 public NuxeoClientEmbedded getClient() throws Exception {
240 if (initialized == true) {
244 // Nuxeo connection was not initialized
246 logger.error(ERROR_CONNECTOR_NOT_INITIALIZED);
247 throw new IllegalStateException(ERROR_CONNECTOR_NOT_INITIALIZED);
250 void releaseClient() throws Exception {
251 if (initialized == true) {
255 // Nuxeo connection was not initialized
257 logger.error(ERROR_CONNECTOR_NOT_INITIALIZED);
258 throw new IllegalStateException(ERROR_CONNECTOR_NOT_INITIALIZED);
263 * retrieveWorkspaceIds retrieves all workspace ids from default repository
266 * a repository domain for a given tenant - see the tenant bindings XML file for details
268 * @throws java.lang.Exception
270 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain)
272 CoreSessionInterface repoSession = null;
273 Hashtable<String, String> workspaceIds = new Hashtable<String, String>();
275 repoSession = getRepositorySession(repoDomain);
276 DocumentModel rootDoc = repoSession.getRootDocument();
277 DocumentModelList rootChildrenList = repoSession.getChildren(rootDoc.getRef());
278 Iterator<DocumentModel> diter = rootChildrenList.iterator();
279 while (diter.hasNext()) {
280 DocumentModel domain = diter.next();
281 String domainPath = "/" + repoDomain.getStorageName();
282 if (!domain.getPathAsString().equalsIgnoreCase(domainPath)) {
283 continue; // If it's not our domain folder/directory then skip it
285 if (logger.isDebugEnabled()) {
286 logger.debug("domain=" + domain.toString());
288 DocumentModelList domainChildrenList = repoSession.getChildren(domain.getRef());
289 Iterator<DocumentModel> witer = domainChildrenList.iterator();
290 while (witer.hasNext()) {
291 DocumentModel childNode = witer.next();
292 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
293 DocumentModelList workspaceList = repoSession
294 .getChildren(childNode.getRef());
295 Iterator<DocumentModel> wsiter = workspaceList
297 while (wsiter.hasNext()) {
298 DocumentModel workspace = wsiter.next();
299 if (logger.isDebugEnabled()) {
300 logger.debug("workspace name="
301 + workspace.getName() + " id="
302 + workspace.getId());
304 workspaceIds.put(workspace.getName().toLowerCase(),
310 } catch (Exception e) {
311 if (logger.isDebugEnabled()) {
312 logger.debug("retrieveWorkspaceIds() caught exception ", e);
316 if (repoSession != null) {
317 releaseRepositorySession(repoSession);