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