]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
9f15b782b8e101dff10ee83e406ca6ea79cfa41c
[tmp/jakarta-migration.git] /
1 package org.collectionspace.services.nuxeo.client.java;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.Hashtable;
6 import java.util.Iterator;
7
8 import javax.servlet.ServletContext;
9
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;
27
28 public class NuxeoConnectorEmbedded {
29         /*
30     <host>127.0.0.1</host>
31     <port>62474</port> <!-- java -->
32  */
33         private Logger logger = LoggerFactory.getLogger(NuxeoConnectorEmbedded.class);
34
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!";
38
39         private final static String CSPACE_NUXEO_HOME = "CSPACE_NUXEO_HOME";
40
41         private static final NuxeoConnectorEmbedded self = new NuxeoConnectorEmbedded();
42         private NuxeoClientEmbedded client;
43         private volatile boolean initialized = false; // use volatile for lazy
44                                                                                                         // initialization in
45                                                                                                         // singleton
46         public NuxeoFrameworkBootstrap fb;
47         private ServletContext servletContext;
48         private RepositoryClientConfigType repositoryClientConfig;
49
50         private NuxeoConnectorEmbedded() {
51                 // empty constructor
52         }
53
54         public final static NuxeoConnectorEmbedded getInstance() {
55                 return self;
56         }
57
58         private String getNuxeoServerPath(String serverRootPath) throws IOException {
59                 String result = null;
60                 //
61                 // Look for the CSPACE_NUXEO_HOME environment variable that might contain the fully qualified path of the
62                 // Nuxeo EP configuration directory.
63                 //
64                 String prop = System.getenv(CSPACE_NUXEO_HOME);
65                 if (prop != null && !prop.isEmpty()) {
66                         result = prop;
67                 } else {
68                         //
69                         // Could not find the 'CSPACE_NUXEO_HOME' environment variable, so using the default location instead.
70                         //
71                         result = serverRootPath + "/" + NUXEO_SERVER_DIR;
72                 }
73
74                 return result;
75         }
76
77         private File getNuxeoServerDir(String serverRootPath) throws IOException {
78                 File result = null;
79                 String errMsg = null;
80
81                 String path = getNuxeoServerPath(serverRootPath);
82                 if (path != null) {
83                         File temp = new File(path);
84                         if (temp.exists() == true) {
85                                 result = temp;
86                         } else {
87                                 errMsg = "The Nuxeo EP configuration directory is missing or inaccessible at: '" + path + "'.";
88                         }
89                 }
90
91                 if (result == null) {
92                         if (errMsg == null) {
93                                 path = path != null ? path : "<empty>";
94                                 errMsg = "Unknown error trying to find Nuxeo configuration: '" +
95                                                 CSPACE_NUXEO_HOME + "' = " +
96                                                 path;
97                         }
98                         throw new IOException(errMsg);
99                 }
100
101                 return result;
102         }
103
104         //
105         // Start/boot the Nuxeo EP server instance
106         //
107         private void startNuxeoEP(String serverRootPath) throws Exception {
108                 File nuxeoHomeDir = getNuxeoServerDir(serverRootPath);
109
110                 if (logger.isInfoEnabled() == true) {
111                         logger.info("Starting Nuxeo EP server from configuration at: "
112                                         + nuxeoHomeDir.getCanonicalPath());
113                 }
114
115                 ClassLoader cl = NuxeoConnectorEmbedded.class.getClassLoader();
116
117                 fb = new NuxeoFrameworkBootstrap(cl, nuxeoHomeDir);
118                 fb.setHostName("Tomcat");
119                 fb.setHostVersion(ServerInfo.getServerNumber());
120
121                 fb.initialize();
122                 fb.start(new MutableClassLoaderDelegate(cl));
123
124                 // Test to see if we can connect to the default repository
125                 boolean transactionStarted = false;
126
127                 if (!TransactionHelper.isTransactionActiveOrMarkedRollback()) {
128                                 transactionStarted = TransactionHelper.startTransaction();
129                 }
130
131                 CoreSession coreSession = null;
132
133                 try {
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);
139                 } finally {
140                         if (coreSession != null) {
141                                 CoreInstance.closeCoreSession(coreSession);
142                         }
143
144                         if (transactionStarted) {
145                                 TransactionHelper.commitOrRollbackTransaction();
146                         }
147                 }
148         }
149
150         /**
151          * release releases resources occupied by Nuxeo remoting client runtime
152          *
153          * @throws java.lang.Exception
154          */
155         public void release() throws Exception {
156                 if (initialized == true) {
157                         try {
158                                 client.tryDisconnect();
159                         } catch (Exception e) {
160                                 logger.error("Failed to disconnect Nuxeo connection.", e);
161                                 throw e;
162                         }
163                 }
164         }
165
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();
176                                         initialized = true;
177                                 }
178                         }
179                 }
180         }
181
182         /**
183          * releaseRepositorySession releases given repository session
184          *
185          * @param repoSession
186          * @throws java.lang.Exception
187          */
188         public void releaseRepositorySession(CoreSessionInterface repoSession)
189                         throws Exception {
190                 if (repoSession != null) {
191                         getClient().releaseRepository(repoSession);
192
193                         if (logger.isDebugEnabled()) {
194                                 logger.debug("releaseRepositorySession() released repository session");
195                         }
196                 }
197         }
198
199         /**
200          * getRepositorySession get session to default repository
201          *
202          * @return RepositoryInstance
203          * @throws java.lang.Exception
204          */
205         public CoreSessionInterface getRepositorySession(RepositoryDomainType repoDomain) throws Exception {
206                 CoreSessionInterface repoSession = getClient().openRepository(repoDomain);
207
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");
212                 }
213
214                 return repoSession;
215         }
216
217
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();
227 //        }
228 //
229 //        return repo;
230 //    }
231
232         /**
233          * getClient get Nuxeo client for accessing Nuxeo services remotely using
234          * Nuxeo Java (EJB) Remote APIS
235          *
236          * @return NuxeoClient
237          * @throws java.lang.Exception
238          */
239         public NuxeoClientEmbedded getClient() throws Exception {
240                 if (initialized == true) {
241                         return client;
242                 }
243                 //
244                 // Nuxeo connection was not initialized
245                 //
246                 logger.error(ERROR_CONNECTOR_NOT_INITIALIZED);
247                 throw new IllegalStateException(ERROR_CONNECTOR_NOT_INITIALIZED);
248         }
249
250         void releaseClient() throws Exception {
251                 if (initialized == true) {
252                         // Do nothing.
253                 } else {
254                         //
255                         // Nuxeo connection was not initialized
256                         //
257                         logger.error(ERROR_CONNECTOR_NOT_INITIALIZED);
258                         throw new IllegalStateException(ERROR_CONNECTOR_NOT_INITIALIZED);
259                 }
260         }
261
262         /**
263          * retrieveWorkspaceIds retrieves all workspace ids from default repository
264          *
265          * @param repoDomain
266          *            a repository domain for a given tenant - see the tenant bindings XML file for details
267          * @return
268          * @throws java.lang.Exception
269          */
270         public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain)
271                         throws Exception {
272                 CoreSessionInterface repoSession = null;
273                 Hashtable<String, String> workspaceIds = new Hashtable<String, String>();
274                 try {
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
284                                 }
285                                 if (logger.isDebugEnabled()) {
286                                         logger.debug("domain=" + domain.toString());
287                                 }
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
296                                                                 .iterator();
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());
303                                                         }
304                                                         workspaceIds.put(workspace.getName().toLowerCase(),
305                                                                         workspace.getId());
306                                                 }
307                                         }
308                                 }
309                         }
310                 } catch (Exception e) {
311                         if (logger.isDebugEnabled()) {
312                                 logger.debug("retrieveWorkspaceIds() caught exception ", e);
313                         }
314                         throw e;
315                 } finally {
316                         if (repoSession != null) {
317                                 releaseRepositorySession(repoSession);
318                         }
319                 }
320
321                 return workspaceIds;
322         }
323 }