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