]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
34ad399693274e735d6073d3a7474ef588591f7e
[tmp/jakarta-migration.git] /
1 /**
2  *  This document is a part of the source code and related artifacts
3  *  for CollectionSpace, an open source collections management system
4  *  for museums and related institutions:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17  */
18 package org.collectionspace.services.nuxeo.client.java;
19
20 import java.io.Serializable;
21 import java.util.Hashtable;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.UUID;
26
27 import javax.ws.rs.WebApplicationException;
28 import javax.ws.rs.core.MultivaluedMap;
29
30 import org.collectionspace.services.client.CollectionSpaceClient;
31 import org.collectionspace.services.client.IQueryManager;
32 import org.collectionspace.services.client.PoxPayloadIn;
33 import org.collectionspace.services.client.PoxPayloadOut;
34 import org.collectionspace.services.client.workflow.WorkflowClient;
35 import org.collectionspace.services.common.context.ServiceContext;
36 import org.collectionspace.services.common.query.QueryContext;
37 import org.collectionspace.services.common.repository.RepositoryClient;
38 import org.collectionspace.services.common.profile.Profiler;
39 import org.collectionspace.services.lifecycle.TransitionDef;
40 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
41
42 import org.collectionspace.services.common.document.BadRequestException;
43 import org.collectionspace.services.common.document.DocumentException;
44 import org.collectionspace.services.common.document.DocumentFilter;
45 import org.collectionspace.services.common.document.DocumentHandler;
46 import org.collectionspace.services.common.document.DocumentNotFoundException;
47 import org.collectionspace.services.common.document.DocumentHandler.Action;
48 import org.collectionspace.services.common.document.DocumentWrapper;
49 import org.collectionspace.services.common.document.DocumentWrapperImpl;
50
51 import org.nuxeo.common.utils.IdUtils;
52 import org.nuxeo.ecm.core.api.ClientException;
53 import org.nuxeo.ecm.core.api.DocumentModel;
54 import org.nuxeo.ecm.core.api.DocumentModelList;
55 import org.nuxeo.ecm.core.api.IterableQueryResult;
56 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
57 import org.nuxeo.ecm.core.api.DocumentRef;
58 import org.nuxeo.ecm.core.api.IdRef;
59 import org.nuxeo.ecm.core.api.PathRef;
60 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
61
62 //
63 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
64 //
65 import org.apache.chemistry.opencmis.commons.server.CallContext;
66 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
67 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
68 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoRepository;
69
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72
73 /**
74  * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo
75  * repository using Remote Java APIs. It uses @see DocumentHandler as IOHandler
76  * with the client.
77  * 
78  * $LastChangedRevision: $ $LastChangedDate: $
79  */
80 public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
81
82     /** The logger. */
83     private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class);
84 //    private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
85 //    private String foo = Profiler.createLogger();
86
87     public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
88     public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
89     
90     /**
91      * Instantiates a new repository java client impl.
92      */
93     public RepositoryJavaClientImpl() {
94         //Empty constructor
95         
96     }
97
98     public void assertWorkflowState(ServiceContext ctx,
99                 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
100         MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
101         if (queryParams != null) {
102                 //
103                 // Look for the workflow "delete" query param and see if we need to assert that the
104                 // docModel is in a non-deleted workflow state.
105                 //
106                 String currentState = docModel.getCurrentLifeCycleState();
107                 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
108                 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
109                 if (includeDeleted == false) {
110                         //
111                         // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
112                         //
113                         if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
114                                 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
115                                 logger.debug(msg);
116                                 throw new DocumentNotFoundException(msg);
117                         }
118                 }
119         }
120     }
121     
122     /**
123      * create document in the Nuxeo repository
124      *
125      * @param ctx service context under which this method is invoked
126      * @param handler
127      *            should be used by the caller to provide and transform the
128      *            document
129      * @return id in repository of the newly created document
130      * @throws DocumentException
131      */
132     @Override
133     public String create(ServiceContext ctx,
134             DocumentHandler handler) throws BadRequestException,
135             DocumentException {
136
137         String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
138         if (docType == null) {
139             throw new IllegalArgumentException(
140                     "RepositoryJavaClient.create: docType is missing");
141         }
142         
143         if (handler == null) {
144             throw new IllegalArgumentException(
145                     "RepositoryJavaClient.create: handler is missing");
146         }
147         String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
148         if (nuxeoWspaceId == null) {
149             throw new DocumentNotFoundException(
150                     "Unable to find workspace for service " + ctx.getServiceName()
151                     + " check if the workspace exists in the Nuxeo repository");
152         }
153         
154         RepositoryInstance repoSession = null;
155         try {
156             handler.prepare(Action.CREATE);
157             repoSession = getRepositorySession();
158             DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
159             DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
160             String wspacePath = wspaceDoc.getPathAsString();
161             //give our own ID so PathRef could be constructed later on
162             String id = IdUtils.generateId(UUID.randomUUID().toString());
163             // create document model
164             DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
165             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
166             DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
167             handler.handle(Action.CREATE, wrapDoc);
168             // create document with documentmodel
169             doc = repoSession.createDocument(doc);
170             repoSession.save();
171 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
172 // and assume the handler has the state it needs (doc fragments). 
173             handler.complete(Action.CREATE, wrapDoc);
174             return id;
175         } catch (BadRequestException bre) {
176             throw bre;
177         } catch (Exception e) {
178                 logger.error("Caught exception ", e);
179             throw new DocumentException(e);
180         } finally {
181             if (repoSession != null) {
182                 releaseRepositorySession(repoSession);
183             }
184         }
185
186     }
187
188     /**
189      * get document from the Nuxeo repository
190      * @param ctx service context under which this method is invoked
191      * @param id
192      *            of the document to retrieve
193      * @param handler
194      *            should be used by the caller to provide and transform the
195      *            document
196      * @throws DocumentException
197      */
198     @Override
199     public void get(ServiceContext ctx, String id, DocumentHandler handler)
200             throws DocumentNotFoundException, DocumentException {
201
202         if (handler == null) {
203             throw new IllegalArgumentException(
204                     "RepositoryJavaClient.get: handler is missing");
205         }
206         
207         RepositoryInstance repoSession = null;
208         try {
209             handler.prepare(Action.GET);
210             repoSession = getRepositorySession();
211             DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
212             DocumentModel docModel = null;
213             try {
214                 docModel = repoSession.getDocument(docRef);
215                 assertWorkflowState(ctx, docModel);
216             } catch (ClientException ce) {
217                 String msg = logException(ce, "Could not find document with CSID=" + id);
218                 throw new DocumentNotFoundException(msg, ce);
219             }
220             //
221             // Set repository session to handle the document
222             //
223             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
224             DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
225             handler.handle(Action.GET, wrapDoc);
226             handler.complete(Action.GET, wrapDoc);
227         } catch (IllegalArgumentException iae) {
228             throw iae;
229         } catch (DocumentException de) {
230             throw de;
231         } catch (Exception e) {
232             if (logger.isDebugEnabled()) {
233                 logger.debug("Caught exception ", e);
234             }
235             throw new DocumentException(e);
236         } finally {
237             if (repoSession != null) {
238                 releaseRepositorySession(repoSession);
239             }
240         }
241     }
242
243     /**
244      * get document from the Nuxeo repository, using the docFilter params.
245      * @param ctx service context under which this method is invoked
246      * @param handler
247      *            should be used by the caller to provide and transform the
248      *            document. Handler must have a docFilter set to return a single item.
249      * @throws DocumentException
250      */
251     @Override
252     public void get(ServiceContext ctx, DocumentHandler handler)
253             throws DocumentNotFoundException, DocumentException {
254         QueryContext queryContext = new QueryContext(ctx, handler);
255         RepositoryInstance repoSession = null;
256
257         try {
258             handler.prepare(Action.GET);
259             repoSession = getRepositorySession();
260
261             DocumentModelList docList = null;
262             // force limit to 1, and ignore totalSize
263             String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
264             docList = repoSession.query(query, null, 1, 0, false);
265             if (docList.size() != 1) {
266                 throw new DocumentNotFoundException("No document found matching filter params: " + query);
267             }
268             DocumentModel doc = docList.get(0);
269
270             if (logger.isDebugEnabled()) {
271                 logger.debug("Executed NXQL query: " + query);
272             }
273
274             //set reposession to handle the document
275             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
276             DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
277             handler.handle(Action.GET, wrapDoc);
278             handler.complete(Action.GET, wrapDoc);
279         } catch (IllegalArgumentException iae) {
280             throw iae;
281         } catch (DocumentException de) {
282             throw de;
283         } catch (Exception e) {
284             if (logger.isDebugEnabled()) {
285                 logger.debug("Caught exception ", e);
286             }
287             throw new DocumentException(e);
288         } finally {
289             if (repoSession != null) {
290                 releaseRepositorySession(repoSession);
291             }
292         }
293     }
294     
295     public DocumentWrapper<DocumentModel> getDoc(
296                 RepositoryInstance repoSession,
297             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
298             String csid) throws DocumentNotFoundException, DocumentException {
299         DocumentWrapper<DocumentModel> wrapDoc = null;
300
301         try {
302             DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
303             DocumentModel doc = null;
304             try {
305                 doc = repoSession.getDocument(docRef);
306             } catch (ClientException ce) {
307                 String msg = logException(ce, "Could not find document with CSID=" + csid);
308                 throw new DocumentNotFoundException(msg, ce);
309             }
310             wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
311         } catch (IllegalArgumentException iae) {
312             throw iae;
313         } catch (DocumentException de) {
314             throw de;
315         }
316
317         return wrapDoc;
318     }
319     
320     /**
321      * Get wrapped documentModel from the Nuxeo repository.  The search is restricted to the workspace
322      * of the current context.
323      * 
324      * @param ctx service context under which this method is invoked
325      * @param id
326      *            of the document to retrieve
327      * @throws DocumentException
328      */
329     @Override
330     public DocumentWrapper<DocumentModel> getDoc(
331             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
332             String csid) throws DocumentNotFoundException, DocumentException {
333         RepositoryInstance repoSession = null;
334         DocumentWrapper<DocumentModel> wrapDoc = null;
335
336         try {
337                 // Open a new repository session
338             repoSession = getRepositorySession();
339             wrapDoc = getDoc(repoSession, ctx, csid);
340         } catch (IllegalArgumentException iae) {
341             throw iae;
342         } catch (DocumentException de) {
343             throw de;
344         } catch (Exception e) {
345             if (logger.isDebugEnabled()) {
346                 logger.debug("Caught exception ", e);
347             }
348             throw new DocumentException(e);
349         } finally {
350             if (repoSession != null) {
351                 releaseRepositorySession(repoSession);
352             }
353         }
354         
355         if (logger.isWarnEnabled() == true) {
356                 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
357         }
358         return wrapDoc;
359     }
360
361     public DocumentWrapper<DocumentModel> findDoc(
362             RepositoryInstance repoSession,
363             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
364             String whereClause)
365             throws DocumentNotFoundException, DocumentException {
366         DocumentWrapper<DocumentModel> wrapDoc = null;
367
368         try {
369             QueryContext queryContext = new QueryContext(ctx, whereClause);
370             DocumentModelList docList = null;
371             // force limit to 1, and ignore totalSize
372             String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
373             docList = repoSession.query(query,
374                     null, //Filter
375                     1, //limit
376                     0, //offset
377                     false); //countTotal
378             if (docList.size() != 1) {
379                 if (logger.isDebugEnabled()) {
380                     logger.debug("findDoc: Query found: " + docList.size() + " items.");
381                     logger.debug(" Query: " + query);
382                 }
383                 throw new DocumentNotFoundException("No document found matching filter params: " + query);
384             }
385             DocumentModel doc = docList.get(0);
386             wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
387         } catch (IllegalArgumentException iae) {
388             throw iae;
389         } catch (DocumentException de) {
390             throw de;
391         } catch (Exception e) {
392             if (logger.isDebugEnabled()) {
393                 logger.debug("Caught exception ", e);
394             }
395             throw new DocumentException(e);
396         }
397         
398         return wrapDoc;
399     }
400     
401     /**
402      * find wrapped documentModel from the Nuxeo repository
403      * @param ctx service context under which this method is invoked
404      * @param whereClause where NXQL where clause to get the document
405      * @throws DocumentException
406      */
407     @Override
408     public DocumentWrapper<DocumentModel> findDoc(
409             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
410             String whereClause)
411                         throws DocumentNotFoundException, DocumentException {
412         RepositoryInstance repoSession = null;
413         DocumentWrapper<DocumentModel> wrapDoc = null;
414
415         try {
416             repoSession = getRepositorySession();
417             wrapDoc = findDoc(repoSession, ctx, whereClause);
418         } catch (Exception e) {
419                         throw new DocumentException("Unable to create a Nuxeo repository session.", e);
420                 } finally {
421             if (repoSession != null) {
422                 releaseRepositorySession(repoSession);
423             }
424         }
425         
426         if (logger.isWarnEnabled() == true) {
427                 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
428         }
429         
430         return wrapDoc;
431     }
432
433     /**
434      * find doc and return CSID from the Nuxeo repository
435      * @param ctx service context under which this method is invoked
436      * @param whereClause where NXQL where clause to get the document
437      * @throws DocumentException
438      */
439     @Override
440     public String findDocCSID(RepositoryInstance repoSession, 
441             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
442             throws DocumentNotFoundException, DocumentException {
443         String csid = null;
444         boolean releaseSession = false;
445         try {
446                 if(repoSession== null) {
447                         repoSession = this.getRepositorySession();
448                         releaseSession = true;
449                 }
450             DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
451             DocumentModel docModel = wrapDoc.getWrappedObject();
452             csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
453         } catch (DocumentNotFoundException dnfe) {
454             throw dnfe;
455         } catch (IllegalArgumentException iae) {
456             throw iae;
457         } catch (DocumentException de) {
458             throw de;
459         } catch (Exception e) {
460             if (logger.isDebugEnabled()) {
461                 logger.debug("Caught exception ", e);
462             }
463             throw new DocumentException(e);
464         } finally {
465                 if(releaseSession && (repoSession != null)) {
466                         this.releaseRepositorySession(repoSession);
467                 }
468         }
469         return csid;
470     }
471
472     public DocumentWrapper<DocumentModelList> findDocs(
473             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
474             RepositoryInstance repoSession,
475             List<String> docTypes,
476             String whereClause,
477             int pageSize, int pageNum, boolean computeTotal)
478                         throws DocumentNotFoundException, DocumentException {
479         DocumentWrapper<DocumentModelList> wrapDoc = null;
480
481         try {
482             if (docTypes == null || docTypes.size() < 1) {
483                 throw new DocumentNotFoundException(
484                         "The findDocs() method must specify at least one DocumentType.");
485             }
486             DocumentModelList docList = null;
487             QueryContext queryContext = new QueryContext(ctx, whereClause);
488             String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
489             if (logger.isDebugEnabled()) {
490                 logger.debug("findDocs() NXQL: "+query);
491             }
492             docList = repoSession.query(query, null, pageSize, pageNum, computeTotal);
493             wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
494         } catch (IllegalArgumentException iae) {
495             throw iae;
496         } catch (Exception e) {
497             if (logger.isDebugEnabled()) {
498                 logger.debug("Caught exception ", e);
499             }
500             throw new DocumentException(e);
501         }
502                 
503         return wrapDoc;
504     }
505     
506     /**
507      * Find a list of documentModels from the Nuxeo repository
508      * @param docTypes a list of DocType names to match
509      * @param  whereClause where the clause to qualify on
510      * @return
511      */
512     @Override
513     public DocumentWrapper<DocumentModelList> findDocs(
514             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
515             List<String> docTypes,
516             String whereClause,
517             int pageSize, int pageNum, boolean computeTotal)
518             throws DocumentNotFoundException, DocumentException {
519         RepositoryInstance repoSession = null;
520         DocumentWrapper<DocumentModelList> wrapDoc = null;
521
522         try {
523             repoSession = getRepositorySession();
524             wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause,
525                         pageSize, pageNum, computeTotal);
526         } catch (IllegalArgumentException iae) {
527             throw iae;
528         } catch (Exception e) {
529             if (logger.isDebugEnabled()) {
530                 logger.debug("Caught exception ", e);
531             }
532             throw new DocumentException(e);
533         } finally {
534             if (repoSession != null) {
535                 releaseRepositorySession(repoSession);
536             }
537         }
538         
539         if (logger.isWarnEnabled() == true) {
540                 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
541         }
542         
543         return wrapDoc;
544     }
545
546     /* (non-Javadoc)
547      * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
548      */
549     @Override
550     public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
551             throws DocumentNotFoundException, DocumentException {
552         if (handler == null) {
553             throw new IllegalArgumentException(
554                     "RepositoryJavaClient.getAll: handler is missing");
555         }
556
557         RepositoryInstance repoSession = null;
558         try {
559             handler.prepare(Action.GET_ALL);
560             repoSession = getRepositorySession();
561             DocumentModelList docModelList = new DocumentModelListImpl();
562             //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
563             for (String csid : csidList) {
564                 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
565                 DocumentModel docModel = repoSession.getDocument(docRef);
566                 docModelList.add(docModel);
567             }
568
569             //set reposession to handle the document
570             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
571             DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
572             handler.handle(Action.GET_ALL, wrapDoc);
573             handler.complete(Action.GET_ALL, wrapDoc);
574         } catch (DocumentException de) {
575             throw de;
576         } catch (Exception e) {
577             if (logger.isDebugEnabled()) {
578                 logger.debug("Caught exception ", e);
579             }
580             throw new DocumentException(e);
581         } finally {
582             if (repoSession != null) {
583                 releaseRepositorySession(repoSession);
584             }
585         }
586     }
587
588     /**
589      * getAll get all documents for an entity entity service from the Nuxeo
590      * repository
591      *
592      * @param ctx service context under which this method is invoked
593      * @param handler
594      *            should be used by the caller to provide and transform the
595      *            document
596      * @throws DocumentException
597      */
598     @Override
599     public void getAll(ServiceContext ctx, DocumentHandler handler)
600             throws DocumentNotFoundException, DocumentException {
601         if (handler == null) {
602             throw new IllegalArgumentException(
603                     "RepositoryJavaClient.getAll: handler is missing");
604         }
605         String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
606         if (nuxeoWspaceId == null) {
607             throw new DocumentNotFoundException(
608                     "Unable to find workspace for service "
609                     + ctx.getServiceName()
610                     + " check if the workspace exists in the Nuxeo repository.");
611         }
612         
613         RepositoryInstance repoSession = null;
614         try {
615             handler.prepare(Action.GET_ALL);
616             repoSession = getRepositorySession();
617             DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
618             DocumentModelList docList = repoSession.getChildren(wsDocRef);
619             //set reposession to handle the document
620             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
621             DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
622             handler.handle(Action.GET_ALL, wrapDoc);
623             handler.complete(Action.GET_ALL, wrapDoc);
624         } catch (DocumentException de) {
625             throw de;
626         } catch (Exception e) {
627             if (logger.isDebugEnabled()) {
628                 logger.debug("Caught exception ", e);
629             }
630             throw new DocumentException(e);
631         } finally {
632             if (repoSession != null) {
633                 releaseRepositorySession(repoSession);
634             }
635         }
636     }
637     
638     private boolean isClauseEmpty(String theString) {
639         boolean result = true;
640         if (theString != null && !theString.isEmpty()) {
641                 result = false;
642         }
643         return result;
644     }
645     
646     public DocumentWrapper<DocumentModel> getDocFromCsid(
647                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
648                 RepositoryInstance repoSession,
649                 String csid)
650             throws Exception {
651         DocumentWrapper<DocumentModel> result = null;
652
653         result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
654         
655         return result;
656     }    
657
658     /*
659      * A method to find a CollectionSpace document (of any type) given just a service context and
660      * its CSID.  A search across *all* service workspaces (within a given tenant context) is performed to find
661      * the document
662      * 
663      * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
664      */
665     @Override
666     public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
667                 String csid)
668             throws Exception {
669         DocumentWrapper<DocumentModel> result = null;
670         RepositoryInstance repoSession = null;
671         try {
672                 repoSession = getRepositorySession();
673                 result = getDocFromCsid(ctx, repoSession, csid);
674         } finally {
675             if (repoSession != null) {
676                 releaseRepositorySession(repoSession);
677             }
678         }
679         
680         if (logger.isWarnEnabled() == true) {
681                 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
682         }
683         
684         return result;
685     }
686
687     /**
688      * find doc and return CSID from the Nuxeo repository
689      * @param ctx service context under which this method is invoked
690      * @param whereClause where NXQL where clause to get the document
691      * @throws DocumentException
692      */
693     @Override
694     public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
695         DocumentModel docModel = wrappedDoc.getWrappedObject();
696         String uri = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
697                         CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
698         return uri;
699     }
700
701     /*
702      * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
703      */
704         private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
705                 IterableQueryResult result = null;
706                 
707                 // the NuxeoRepository should be constructed only once, then cached
708                 // (its construction is expensive)
709                 try {
710                         NuxeoRepository repo = new NuxeoRepository(
711                                         repoSession.getRepositoryName(), repoSession
712                                                         .getRootDocument().getId());
713                         logger.debug("Repository ID:" + repo.getId() + " Root folder:"
714                                         + repo.getRootFolderId());
715
716                         CallContextImpl callContext = new CallContextImpl(
717                                         CallContext.BINDING_LOCAL, repo.getId(), false);
718                         callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
719                                         .getName());
720                         NuxeoCmisService cmisService = new NuxeoCmisService(repo,
721                                         callContext, repoSession);
722
723                         result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
724                 } catch (ClientException e) {
725                         // TODO Auto-generated catch block
726                         logger.error("Encounter trouble making the following CMIS query: " + query, e);
727                 }
728                 
729                 return result;
730         }
731      
732     /**
733      * getFiltered get all documents for an entity service from the Document repository,
734      * given filter parameters specified by the handler. 
735      * @param ctx service context under which this method is invoked
736      * @param handler should be used by the caller to provide and transform the document
737      * @throws DocumentNotFoundException if workspace not found
738      * @throws DocumentException
739      */
740     @Override
741     public void getFiltered(ServiceContext ctx, DocumentHandler handler)
742             throws DocumentNotFoundException, DocumentException {
743
744         DocumentFilter filter = handler.getDocumentFilter();
745         String oldOrderBy = filter.getOrderByClause();
746         if (isClauseEmpty(oldOrderBy) == true){
747             filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
748         }
749         QueryContext queryContext = new QueryContext(ctx, handler);
750
751         RepositoryInstance repoSession = null;
752         try {
753             handler.prepare(Action.GET_ALL);
754             repoSession = getRepositorySession();
755             
756             DocumentModelList docList = null;
757             String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
758
759             if (logger.isDebugEnabled()) {
760                 logger.debug("Executing NXQL query: " + query.toString());
761             }
762
763             // If we have limit and/or offset, then pass true to get totalSize
764             // in returned DocumentModelList.
765                 Profiler profiler = new Profiler(this, 2);
766                 profiler.log("Executing NXQL query: " + query.toString());
767                 profiler.start();
768                 if (handler.isCMISQuery() == true) {
769                         docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
770                 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
771                 docList = repoSession.query(query, null,
772                         queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
773             } else {
774                 docList = repoSession.query(query);
775             }
776             profiler.stop();
777
778             //set repoSession to handle the document
779             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
780             DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
781             handler.handle(Action.GET_ALL, wrapDoc);
782             handler.complete(Action.GET_ALL, wrapDoc);
783         } catch (DocumentException de) {
784             throw de;
785         } catch (Exception e) {
786             if (logger.isDebugEnabled()) {
787                 logger.debug("Caught exception ", e);
788             }
789             throw new DocumentException(e);
790         } finally {
791             if (repoSession != null) {
792                 releaseRepositorySession(repoSession);
793             }
794         }
795     }
796
797     private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
798             throws DocumentNotFoundException, DocumentException {
799
800         DocumentModelList result = new DocumentModelListImpl();
801         try {
802             String query = handler.getCMISQuery(queryContext);
803
804             if (logger.isDebugEnabled()) {
805                 logger.debug("Executing CMIS query: " + query.toString());
806             }
807
808             // If we have limit and/or offset, then pass true to get totalSize
809             // in returned DocumentModelList.
810                 Profiler profiler = new Profiler(this, 2);
811                 profiler.log("Executing CMIS query: " + query.toString());
812                 profiler.start();
813                 //
814                 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
815                 try {
816                                 for (Map<String, Serializable> row : queryResult) {
817                                         logger.debug(""
818         //                                      + " dc:title is: " + (String)row.get("dc:title")
819                                                 + " Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
820                                                 + " cmis:name is: " + row.get(IQueryManager.CMIS_TARGET_NAME)
821         //                                      + " nuxeo:lifecycleState is: " + row.get("nuxeo:lifecycleState")
822                                         );
823                                         String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
824                                         DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
825                                         result.add(docModel);
826                                 }
827                 } finally {
828                         queryResult.close();
829                 }
830                 //
831             profiler.stop();
832
833         } catch (Exception e) {
834             if (logger.isDebugEnabled()) {
835                 logger.debug("Caught exception ", e);
836             }
837             throw new DocumentException(e);
838         }
839         
840         return result;
841     }
842     
843     private String logException(Exception e, String msg) {
844         String result = null;
845         
846         String exceptionMessage = e.getMessage();
847         exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
848         result = msg = msg + ". Caught exception:" + exceptionMessage;
849         
850         if (logger.isTraceEnabled() == true) {
851                 logger.error(msg, e);
852         } else {
853                 logger.error(msg);
854         }
855         
856         return result;
857     }
858     
859     /**
860      * update given document in the Nuxeo repository
861      *
862      * @param ctx service context under which this method is invoked
863      * @param id
864      *            of the document
865      * @param handler
866      *            should be used by the caller to provide and transform the
867      *            document
868      * @throws DocumentException
869      */
870     @Override
871     public void update(ServiceContext ctx, String csid, DocumentHandler handler)
872             throws BadRequestException, DocumentNotFoundException,
873             DocumentException {
874         if (handler == null) {
875             throw new IllegalArgumentException(
876                     "RepositoryJavaClient.update: document handler is missing.");
877         }
878         
879         RepositoryInstance repoSession = null;
880         try {
881             handler.prepare(Action.UPDATE);
882             repoSession = getRepositorySession();
883             DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
884             DocumentModel doc = null;
885             try {
886                 doc = repoSession.getDocument(docRef);
887             } catch (ClientException ce) {
888                 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
889                 throw new DocumentNotFoundException(msg, ce);
890             }
891             //
892             // Set reposession to handle the document
893             //
894             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
895             DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
896             handler.handle(Action.UPDATE, wrapDoc);
897             repoSession.saveDocument(doc);
898             repoSession.save();
899             handler.complete(Action.UPDATE, wrapDoc);
900         } catch (BadRequestException bre) {
901             throw bre;
902         } catch (DocumentException de) {
903             throw de;
904         } catch (WebApplicationException wae){
905             throw wae;
906         } catch (Exception e) {
907             if (logger.isDebugEnabled()) {
908                 logger.debug("Caught exception ", e);
909             }
910             throw new DocumentException(e);
911         } finally {
912             if (repoSession != null) {
913                 releaseRepositorySession(repoSession);
914             }
915         }
916     }
917     
918     /**
919      * Save a documentModel to the Nuxeo repository.
920      * @param ctx service context under which this method is invoked
921      * @param docModel the document to save
922      * @param fSaveSession if TRUE, will call CoreSession.save() to save accumulated changes.
923      * @throws DocumentException
924      */
925     public void saveDocWithoutHandlerProcessing(
926             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
927             RepositoryInstance repoSession,
928             DocumentModel docModel,
929             boolean fSaveSession)
930             throws ClientException, DocumentException {
931
932         try {
933             repoSession.saveDocument(docModel);
934             if (fSaveSession) {
935                 repoSession.save();
936             }
937         } catch (ClientException ce) {
938             throw ce;
939         } catch (Exception e) {
940             if (logger.isDebugEnabled()) {
941                 logger.debug("Caught exception ", e);
942             }
943             throw new DocumentException(e);
944         }
945     }
946
947
948     /**
949      * Save a list of documentModels to the Nuxeo repository.
950      * 
951      * @param ctx service context under which this method is invoked
952      * @param docModel the document to save
953      * @param fSaveSession if TRUE, will call CoreSession.save() to save accumulated changes.
954      * @throws DocumentException
955      */
956     public void saveDocListWithoutHandlerProcessing(
957             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
958             RepositoryInstance repoSession,
959             DocumentModelList docList, 
960             boolean fSaveSession)
961             throws ClientException, DocumentException {
962         try {
963             repoSession = getRepositorySession();
964             DocumentModel[] docModelArray = new DocumentModel[docList.size()];
965             repoSession.saveDocuments(docList.toArray(docModelArray));
966             if (fSaveSession) {
967                 repoSession.save();
968             }
969         } catch (ClientException ce) {
970             throw ce;
971         } catch (Exception e) {
972             logger.error("Caught exception ", e);
973             throw new DocumentException(e);
974         }
975     }
976
977     /**
978      * delete a document from the Nuxeo repository
979      * @param ctx service context under which this method is invoked
980      * @param id
981      *            of the document
982      * @throws DocumentException
983      */
984     @Override
985     public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
986             DocumentException {
987         if (ctx == null) {
988             throw new IllegalArgumentException(
989                     "delete(ctx, ix, handler): ctx is missing");
990         }
991         if (handler == null) {
992             throw new IllegalArgumentException(
993                     "delete(ctx, ix, handler): handler is missing");
994         }
995         if (logger.isDebugEnabled()) {
996             logger.debug("Deleting document with CSID=" + id);
997         }
998         RepositoryInstance repoSession = null;
999         try {
1000                 handler.prepare(Action.DELETE);
1001             repoSession = getRepositorySession();
1002             DocumentWrapper<DocumentModel> wrapDoc = null;
1003             try {
1004                 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1005                     wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1006                     ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1007                     handler.handle(Action.DELETE, wrapDoc);
1008                 repoSession.removeDocument(docRef);
1009             } catch (ClientException ce) {
1010                 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1011                 throw new DocumentNotFoundException(msg, ce);
1012             }
1013             repoSession.save();
1014             handler.complete(Action.DELETE, wrapDoc);
1015         } catch (DocumentException de) {
1016             throw de;
1017         } catch (Exception e) {
1018             if (logger.isDebugEnabled()) {
1019                 logger.debug("Caught exception ", e);
1020             }
1021             throw new DocumentException(e);
1022         } finally {
1023             if (repoSession != null) {
1024                 releaseRepositorySession(repoSession);
1025             }
1026         }
1027     }
1028
1029     /* (non-Javadoc)
1030      * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1031      */
1032     @Override
1033     @Deprecated
1034     public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1035             throws DocumentNotFoundException, DocumentException {
1036         throw new UnsupportedOperationException();
1037         // Use the other delete instead
1038     }
1039
1040     @Override
1041     public Hashtable<String, String> retrieveWorkspaceIds(String domainName) throws Exception {
1042         return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(domainName);
1043     }
1044
1045     @Override
1046     public String createDomain(String domainName) throws Exception {
1047         RepositoryInstance repoSession = null;
1048         String domainId = null;
1049         try {
1050                 //
1051                 // First create the top-level domain directory
1052                 //
1053             repoSession = getRepositorySession();
1054             DocumentRef parentDocRef = new PathRef("/");
1055             DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1056             DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1057                     domainName, NUXEO_CORE_TYPE_DOMAIN);
1058             domainDoc.setPropertyValue("dc:title", domainName);
1059             domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1060                     + domainName);
1061             domainDoc = repoSession.createDocument(domainDoc);
1062             domainId = domainDoc.getId();
1063             repoSession.save();
1064             //
1065             // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1066             //
1067             DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1068                         NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1069             workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1070             workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1071                     + domainDoc.getPathAsString());
1072             workspacesRoot = repoSession.createDocument(workspacesRoot);
1073             String workspacesRootId = workspacesRoot.getId();
1074             repoSession.save();
1075             
1076             if (logger.isDebugEnabled()) {
1077                 logger.debug("Created tenant domain name=" + domainName
1078                         + " id=" + domainId + " " +
1079                         NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1080                 logger.debug("Path to Domain: "+domainDoc.getPathAsString());
1081                 logger.debug("Path to Workspaces root: "+workspacesRoot.getPathAsString());
1082             }
1083         } catch (Exception e) {
1084             if (logger.isDebugEnabled()) {
1085                 logger.debug("Could not create tenant domain name=" + domainName + " caught exception ", e);
1086             }
1087             throw e;
1088         } finally {
1089             if (repoSession != null) {
1090                 releaseRepositorySession(repoSession);
1091             }
1092         }
1093         
1094         return domainId;
1095     }
1096
1097     @Override
1098     public String getDomainId(String domainName) throws Exception {
1099         String domainId = null;
1100         RepositoryInstance repoSession = null;
1101         
1102         if (domainName != null && !domainName.isEmpty()) {
1103                 try {
1104                     repoSession = getRepositorySession();
1105                     DocumentRef docRef = new PathRef(
1106                             "/" + domainName);
1107                     DocumentModel domain = repoSession.getDocument(docRef);
1108                     domainId = domain.getId();
1109                 } catch (Exception e) {
1110                     if (logger.isTraceEnabled()) {
1111                         logger.trace("Caught exception ", e);
1112                     }
1113                     //there is no way to identify if document does not exist due to
1114                     //lack of typed exception for getDocument method
1115                     return null;
1116                 } finally {
1117                     if (repoSession != null) {
1118                         releaseRepositorySession(repoSession);
1119                     }
1120                 }
1121         }
1122         
1123         return domainId;
1124     }
1125
1126     /*
1127          * Returns the workspaces root directory for a given domain.
1128          */
1129         private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1130                         String domainName) throws Exception {
1131                 DocumentModel result = null;
1132                 
1133                 String domainPath = "/" + domainName;
1134                 DocumentRef parentDocRef = new PathRef(domainPath);
1135                 DocumentModelList domainChildrenList = repoSession.getChildren(
1136                                 parentDocRef);
1137                 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1138                 while (witer.hasNext()) {
1139                         DocumentModel childNode = witer.next();
1140                         if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1141                                 result = childNode;
1142                                 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1143                                 break;
1144                         }
1145                 }
1146                 
1147                 if (result == null) {
1148                         throw new ClientException("Could not find workspace root directory in: "
1149                                         + domainPath);
1150                 }
1151
1152                 return result;
1153         }
1154     
1155     /* (non-Javadoc)
1156      * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1157      */
1158     @Override
1159     public String createWorkspace(String domainName, String workspaceName) throws Exception {
1160         RepositoryInstance repoSession = null;
1161         String workspaceId = null;
1162         try {
1163             repoSession = getRepositorySession();
1164             DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainName);            
1165             DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1166                     workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1167             doc.setPropertyValue("dc:title", workspaceName);
1168             doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1169                     + workspaceName);
1170             doc = repoSession.createDocument(doc);
1171             workspaceId = doc.getId();
1172             repoSession.save();
1173             if (logger.isDebugEnabled()) {
1174                 logger.debug("Created workspace name=" + workspaceName
1175                         + " id=" + workspaceId);
1176             }
1177         } catch (Exception e) {
1178             if (logger.isDebugEnabled()) {
1179                 logger.debug("createWorkspace caught exception ", e);
1180             }
1181             throw e;
1182         } finally {
1183             if (repoSession != null) {
1184                 releaseRepositorySession(repoSession);
1185             }
1186         }
1187         return workspaceId;
1188     }
1189
1190     /* (non-Javadoc)
1191      * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1192      */
1193     @Override
1194     public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1195         String workspaceId = null;
1196         
1197         RepositoryInstance repoSession = null;
1198         try {
1199             repoSession = getRepositorySession();
1200             DocumentRef docRef = new PathRef(
1201                     "/" + tenantDomain
1202                     + "/" + NuxeoUtils.Workspaces
1203                     + "/" + workspaceName);
1204             DocumentModel workspace = repoSession.getDocument(docRef);
1205             workspaceId = workspace.getId();
1206         } catch (DocumentException de) {
1207             throw de;
1208         } catch (Exception e) {
1209             if (logger.isDebugEnabled()) {
1210                 logger.debug("Caught exception ", e);
1211             }
1212             throw new DocumentException(e);
1213         } finally {
1214             if (repoSession != null) {
1215                 releaseRepositorySession(repoSession);
1216             }
1217         }
1218         
1219         return workspaceId;
1220     }
1221
1222
1223     /**
1224      * Gets the repository session. - Package access only.
1225      *
1226      * @return the repository session
1227      * @throws Exception the exception
1228      */
1229     public RepositoryInstance getRepositorySession() throws Exception {
1230         // FIXME: is it possible to reuse repository session?
1231         // Authentication failures happen while trying to reuse the session
1232         Profiler profiler = new Profiler("getRepositorySession():", 2);
1233         profiler.start();
1234         
1235         NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1236         RepositoryInstance repoSession = client.openRepository();
1237         if (logger.isTraceEnabled()) {
1238             logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1239         }
1240         
1241         profiler.stop();
1242         return repoSession;
1243     }
1244
1245     /**
1246      * Release repository session. - Package access only.
1247      *
1248      * @param repoSession the repo session
1249      */
1250     public void releaseRepositorySession(RepositoryInstance repoSession) {
1251         try {
1252             NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1253             // release session
1254             client.releaseRepository(repoSession);
1255         } catch (Exception e) {
1256             logger.error("Could not close the repository session", e);
1257             // no need to throw this service specific exception
1258         }
1259     }
1260
1261         @Override
1262         public void doWorkflowTransition(ServiceContext ctx, String id,
1263                         DocumentHandler handler, TransitionDef transitionDef)
1264                         throws BadRequestException, DocumentNotFoundException,
1265                         DocumentException {
1266                 // This is a placeholder for when we change the StorageClient interface to treat workflow transitions as 1st class operations like 'get', 'create', 'update, 'delete', etc
1267         }
1268
1269 }