]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
82a0eae0e68898ff6d33a2a7fdbb5579a1835669
[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.naming.InitialContext;
9 import javax.naming.NamingException;
10 import javax.servlet.ServletContext;
11
12 import org.collectionspace.services.common.api.JEEServerDeployment;
13 import org.collectionspace.services.config.RepositoryClientConfigType;
14 import org.collectionspace.services.config.tenant.RepositoryDomainType;
15 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
16
17 import org.nuxeo.ecm.core.api.DocumentModel;
18 import org.nuxeo.ecm.core.api.DocumentModelList;
19 import org.nuxeo.ecm.core.api.repository.RepositoryManager;
20 import org.nuxeo.ecm.core.model.Repository;
21 import org.nuxeo.osgi.application.FrameworkBootstrap;
22 import org.nuxeo.runtime.api.Framework;
23 import org.nuxeo.ecm.core.storage.sql.ra.ConnectionFactoryImpl;
24 import org.nuxeo.ecm.core.storage.sql.ra.ManagedConnectionFactoryImpl;
25
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 public class NuxeoConnectorEmbedded {
30         /*
31     <host>127.0.0.1</host>
32     <port>62474</port> <!-- java -->
33  */
34         private Logger logger = LoggerFactory.getLogger(NuxeoConnectorEmbedded.class);
35
36         public final static String NUXEO_CLIENT_DIR = JEEServerDeployment.NUXEO_CLIENT_DIR;
37         public final static String NUXEO_SERVER_DIR = JEEServerDeployment.NUXEO_SERVER_DIR;
38         private final static String ERROR_CONNECTOR_NOT_INITIALIZED = "NuxeoConnector is not initialized!";
39                 
40         private final static String CSPACE_NUXEO_HOME = "CSPACE_NUXEO_HOME";
41         
42         private static final NuxeoConnectorEmbedded self = new NuxeoConnectorEmbedded();
43         private NuxeoClientEmbedded client;
44         private volatile boolean initialized = false; // use volatile for lazy
45                                                                                                         // initialization in
46                                                                                                         // singleton
47         public FrameworkBootstrap fb;
48         private ServletContext servletContext;
49         private RepositoryClientConfigType repositoryClientConfig;
50
51         private NuxeoConnectorEmbedded() {
52                 // empty constructor
53         }
54
55         public final static NuxeoConnectorEmbedded getInstance() {
56                 return self;
57         }
58         
59         private String getNuxeoServerPath(String serverRootPath) throws IOException {
60                 String result = null;
61                 //
62                 // Look for the CSPACE_NUXEO_HOME environment variable that might contain the fully qualified path of the
63                 // Nuxeo EP configuration directory.
64                 //
65                 String prop = System.getenv(CSPACE_NUXEO_HOME);
66                 if (prop != null && !prop.isEmpty()) {
67                         result = prop;
68                 } else {
69                         //
70                         // Could not find the 'CSPACE_NUXEO_HOME' environment variable, so using the default location instead.
71                         //
72                         result = serverRootPath + "/" + NUXEO_SERVER_DIR;
73                 }
74                 
75                 return result;
76         }
77         
78         private File getNuxeoServerDir(String serverRootPath) throws IOException {
79                 File result = null;
80                 String errMsg = null;
81                 
82                 String path = getNuxeoServerPath(serverRootPath);
83                 if (path != null) {
84                         File temp = new File(path);
85                         if (temp.exists() == true) {
86                                 result = temp;
87                         } else {
88                                 errMsg = "The Nuxeo EP configuration directory is missing or inaccessible at: '" + path + "'.";
89                         }
90                 }
91                 
92                 if (result == null) {
93                         if (errMsg == null) {
94                                 path = path != null ? path : "<empty>";
95                                 errMsg = "Unknown error trying to find Nuxeo configuration: '" +
96                                                 CSPACE_NUXEO_HOME + "' = " +
97                                                 path;
98                         }
99                         throw new IOException(errMsg);
100                 }
101                 
102                 return result;
103         }
104
105         //
106         // Start/boot the Nuxeo EP server instance
107         //
108         private void startNuxeoEP(String serverRootPath) throws Exception {
109                 File nuxeoHomeDir = getNuxeoServerDir(serverRootPath);
110
111                 if (logger.isInfoEnabled() == true) {
112                         logger.info("Starting Nuxeo EP server from configuration at: "
113                                         + nuxeoHomeDir.getCanonicalPath());
114                 }
115                 
116                 fb = new FrameworkBootstrap(NuxeoConnectorEmbedded.class.getClassLoader(),
117                                 nuxeoHomeDir);
118                 fb.initialize();
119                 fb.start();
120         }
121
122         /**
123          * release releases resources occupied by Nuxeo remoting client runtime
124          * 
125          * @throws java.lang.Exception
126          */
127         public void release() throws Exception {
128                 if (initialized == true) {
129                         try {
130                                 client.tryDisconnect();
131                         } catch (Exception e) {
132                                 logger.error("Failed to disconnect Nuxeo connection.", e);
133                                 throw e;
134                         }
135                 }
136         }
137
138         public void initialize(String serverRootPath,
139                         RepositoryClientConfigType repositoryClientConfig,
140                         ServletContext servletContext) throws Exception {
141                 if (initialized == false) {
142                         synchronized (this) {
143                                 if (initialized == false) {
144                                         this.servletContext = servletContext;
145                                         this.repositoryClientConfig = repositoryClientConfig;
146                                         startNuxeoEP(serverRootPath);
147                                         client = NuxeoClientEmbedded.getInstance();
148                                         initialized = true;
149                                 }
150                         }
151                 }
152         }
153         
154         /*
155          * This is a debug-only method.  Use to look at runtime values of Nuxeo internal
156          * data structures.
157          */
158         public String getDatabaseName(String repoName) {
159                 String result = null;
160
161 // TODO: Remove after CSPACE-6375 issue is resolved.
162 //              try {
163 //                      List<RepositoryDescriptor> repositoryDescriptorList = this.getRepositoryDescriptor(repoName);
164 //              } catch (Exception e1) {
165 //                      // TODO Auto-generated catch block
166 //                      e1.printStackTrace();
167 //              }
168                 
169                 Repository repository = null;
170                 try {
171                         repository = this.lookupRepository(repoName);
172                 } catch (Exception e) {
173                         // TODO Auto-generated catch block
174                         e.printStackTrace();
175                 }
176                 
177                 ConnectionFactoryImpl connectionFactory = (ConnectionFactoryImpl)repository;
178                 ManagedConnectionFactoryImpl managedConnectionFactory = connectionFactory.getManagedConnectionFactory();
179                 String property = managedConnectionFactory.getProperty();
180                 
181                 return result;
182         }
183
184         /**
185          * releaseRepositorySession releases given repository session
186          * 
187          * @param repoSession
188          * @throws java.lang.Exception
189          */
190         public void releaseRepositorySession(CoreSessionInterface repoSession)
191                         throws Exception {
192                 if (repoSession != null) {
193                         getClient().releaseRepository(repoSession);
194
195                         if (logger.isDebugEnabled()) {
196                                 logger.debug("releaseRepositorySession() released repository session");
197                         }
198                 }
199         }
200
201         /**
202          * getRepositorySession get session to default repository
203          * 
204          * @return RepositoryInstance
205          * @throws java.lang.Exception
206          */
207         public CoreSessionInterface getRepositorySession(RepositoryDomainType repoDomain) throws Exception {
208                 CoreSessionInterface repoSession = getClient().openRepository(repoDomain);
209                 
210                 if (logger.isDebugEnabled() && repoSession != null) {
211                         logger.debug("getRepositorySession() opened repository session");
212                         String repoName = repoDomain.getRepositoryName();
213                         String databaseName = this.getDatabaseName(repoName); // For debugging purposes only
214                 }
215                 
216                 return repoSession;
217         }
218
219     public Repository lookupRepository(String name) throws Exception {
220         Repository repo;
221                 RepositoryManager repositoryManager = Framework.getService(RepositoryManager.class);
222
223         try {
224             // needed by glassfish
225             repo = (Repository) new InitialContext().lookup("NXRepository/" + name);
226         } catch (NamingException e) {
227             try {
228                 // needed by jboss
229                 repo = (Repository) new InitialContext().lookup("java:NXRepository/"
230                         + name);
231             } catch (NamingException ee) {
232                 repo = (Repository) repositoryManager.getRepository(
233                         name);
234             }
235         }
236         
237         if (repo == null) {
238             throw new IllegalArgumentException("Repository not found: " + name);
239         }
240         
241         return repo;
242     }
243     
244 // TODO: Remove after CSPACE-6375 issue is resolved.
245 //    public List<RepositoryDescriptor> getRepositoryDescriptor(String name) throws Exception {
246 //      RepositoryDescriptor repo = null;
247 //              RepositoryManager repositoryManager = Framework.getService(RepositoryManager.class);
248 //        Iterable<RepositoryDescriptor> descriptorsList = repositoryManager.getDescriptors();
249 //        for (RepositoryDescriptor descriptor : descriptorsList) {
250 //              String homeDir = descriptor.getHomeDirectory();
251 //              String config = descriptor.getConfigurationFile();
252 //              RepositoryFactory factor = descriptor.getFactory();
253 //        }
254 //
255 //        return repo;
256 //    }
257         
258         /**
259          * getClient get Nuxeo client for accessing Nuxeo services remotely using
260          * Nuxeo Java (EJB) Remote APIS
261          * 
262          * @return NuxeoClient
263          * @throws java.lang.Exception
264          */
265         public NuxeoClientEmbedded getClient() throws Exception {
266                 if (initialized == true) {
267                         return client;
268                 }
269                 //
270                 // Nuxeo connection was not initialized
271                 //
272                 logger.error(ERROR_CONNECTOR_NOT_INITIALIZED);
273                 throw new IllegalStateException(ERROR_CONNECTOR_NOT_INITIALIZED);
274         }
275         
276         void releaseClient() throws Exception {
277                 if (initialized == true) {
278                         // Do nothing.
279                 } else {
280                         //
281                         // Nuxeo connection was not initialized
282                         //
283                         logger.error(ERROR_CONNECTOR_NOT_INITIALIZED);
284                         throw new IllegalStateException(ERROR_CONNECTOR_NOT_INITIALIZED);
285                 }
286         }
287
288         /**
289          * retrieveWorkspaceIds retrieves all workspace ids from default repository
290          * 
291          * @param repoDomain
292          *            a repository domain for a given tenant - see the tenant bindings XML file for details
293          * @return
294          * @throws java.lang.Exception
295          */
296         public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain)
297                         throws Exception {
298                 CoreSessionInterface repoSession = null;
299                 Hashtable<String, String> workspaceIds = new Hashtable<String, String>();
300                 try {
301                         repoSession = getRepositorySession(repoDomain);
302                         DocumentModel rootDoc = repoSession.getRootDocument();
303                         DocumentModelList rootChildrenList = repoSession.getChildren(rootDoc.getRef());
304                         Iterator<DocumentModel> diter = rootChildrenList.iterator();
305                         while (diter.hasNext()) {
306                                 DocumentModel domain = diter.next();
307                                 String domainPath = "/" + repoDomain.getStorageName();
308                                 if (!domain.getPathAsString().equalsIgnoreCase(domainPath)) {
309                                         continue; // If it's not our domain folder/directory then skip it
310                                 }
311                                 if (logger.isDebugEnabled()) {
312                                         logger.debug("domain=" + domain.toString());
313                                 }
314                                 DocumentModelList domainChildrenList = repoSession.getChildren(domain.getRef());
315                                 Iterator<DocumentModel> witer = domainChildrenList.iterator();
316                                 while (witer.hasNext()) {
317                                         DocumentModel childNode = witer.next();
318                                         if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) { 
319                                                 DocumentModelList workspaceList = repoSession
320                                                                 .getChildren(childNode.getRef());
321                                                 Iterator<DocumentModel> wsiter = workspaceList
322                                                                 .iterator();
323                                                 while (wsiter.hasNext()) {
324                                                         DocumentModel workspace = wsiter.next();
325                                                         if (logger.isDebugEnabled()) {
326                                                                 logger.debug("workspace name="
327                                                                                 + workspace.getName() + " id="
328                                                                                 + workspace.getId());
329                                                         }
330                                                         workspaceIds.put(workspace.getName().toLowerCase(),
331                                                                         workspace.getId());
332                                                 }
333                                         }
334                                 }
335                         }
336                 } catch (Exception e) {
337                         if (logger.isDebugEnabled()) {
338                                 logger.debug("retrieveWorkspaceIds() caught exception ", e);
339                         }
340                         throw e;
341                 } finally {
342                         if (repoSession != null) {
343                                 releaseRepositorySession(repoSession);
344                         }
345                 }
346                 
347                 return workspaceIds;
348         }       
349 }