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