]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
4bde46cf553cb77ea466476458bb8d545f32eb28
[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.sql.Connection;
22 import java.sql.ResultSet;
23 import java.sql.Statement;
24 import java.util.ArrayList;
25 import java.util.Hashtable;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.UUID;
30
31 import javax.ws.rs.WebApplicationException;
32 import javax.ws.rs.core.MultivaluedMap;
33
34 import org.collectionspace.services.client.CollectionSpaceClient;
35 import org.collectionspace.services.client.IQueryManager;
36 import org.collectionspace.services.client.PoxPayloadIn;
37 import org.collectionspace.services.client.PoxPayloadOut;
38 import org.collectionspace.services.client.Profiler;
39 import org.collectionspace.services.client.workflow.WorkflowClient;
40 import org.collectionspace.services.common.context.ServiceContext;
41 import org.collectionspace.services.common.query.QueryContext;
42 import org.collectionspace.services.common.repository.RepositoryClient;
43 import org.collectionspace.services.common.storage.JDBCTools;
44 import org.collectionspace.services.lifecycle.TransitionDef;
45 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
46
47 import org.collectionspace.services.common.document.BadRequestException;
48 import org.collectionspace.services.common.document.DocumentException;
49 import org.collectionspace.services.common.document.DocumentFilter;
50 import org.collectionspace.services.common.document.DocumentHandler;
51 import org.collectionspace.services.common.document.DocumentNotFoundException;
52 import org.collectionspace.services.common.document.DocumentHandler.Action;
53 import org.collectionspace.services.common.document.DocumentWrapper;
54 import org.collectionspace.services.common.document.DocumentWrapperImpl;
55 import org.collectionspace.services.common.document.TransactionException;
56 import org.collectionspace.services.config.tenant.RepositoryDomainType;
57
58 import org.nuxeo.common.utils.IdUtils;
59 import org.nuxeo.ecm.core.api.ClientException;
60 import org.nuxeo.ecm.core.api.DocumentModel;
61 import org.nuxeo.ecm.core.api.DocumentModelList;
62 import org.nuxeo.ecm.core.api.IterableQueryResult;
63 import org.nuxeo.ecm.core.api.VersioningOption;
64 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
65 import org.nuxeo.ecm.core.api.DocumentRef;
66 import org.nuxeo.ecm.core.api.IdRef;
67 import org.nuxeo.ecm.core.api.PathRef;
68 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
69 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
70
71 //
72 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
73 //
74 import org.apache.chemistry.opencmis.commons.server.CallContext;
75 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
76 import org.collectionspace.services.common.api.Tools;
77 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
78 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoRepository;
79
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
82
83 /**
84  * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo
85  * repository using Remote Java APIs. It uses @see DocumentHandler as IOHandler
86  * with the client.
87  * 
88  * $LastChangedRevision: $ $LastChangedDate: $
89  */
90 public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
91
92     /** The logger. */
93     private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class);
94 //    private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
95 //    private String foo = Profiler.createLogger();
96
97     public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
98     public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
99     
100     /**
101      * Instantiates a new repository java client impl.
102      */
103     public RepositoryJavaClientImpl() {
104         //Empty constructor
105         
106     }
107
108     public void assertWorkflowState(ServiceContext ctx,
109                 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
110         MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
111         if (queryParams != null) {
112                 //
113                 // Look for the workflow "delete" query param and see if we need to assert that the
114                 // docModel is in a non-deleted workflow state.
115                 //
116                 String currentState = docModel.getCurrentLifeCycleState();
117                 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
118                 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
119                 if (includeDeleted == false) {
120                         //
121                         // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
122                         //
123                         if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
124                                 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
125                                 logger.debug(msg);
126                                 throw new DocumentNotFoundException(msg);
127                         }
128                 }
129         }
130     }
131     
132     /**
133      * create document in the Nuxeo repository
134      *
135      * @param ctx service context under which this method is invoked
136      * @param handler
137      *            should be used by the caller to provide and transform the
138      *            document
139      * @return id in repository of the newly created document
140      * @throws BadRequestException
141      * @throws TransactionException
142      * @throws DocumentException
143      */
144     @Override
145     public String create(ServiceContext ctx,
146             DocumentHandler handler) throws BadRequestException,
147             TransactionException, DocumentException {
148
149         String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
150         if (docType == null) {
151             throw new IllegalArgumentException(
152                     "RepositoryJavaClient.create: docType is missing");
153         }
154         
155         if (handler == null) {
156             throw new IllegalArgumentException(
157                     "RepositoryJavaClient.create: handler is missing");
158         }
159         String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
160         if (nuxeoWspaceId == null) {
161             throw new DocumentNotFoundException(
162                     "Unable to find workspace for service " + ctx.getServiceName()
163                     + " check if the workspace exists in the Nuxeo repository");
164         }
165         
166         RepositoryInstance repoSession = null;
167         try {
168             handler.prepare(Action.CREATE);
169             repoSession = getRepositorySession(ctx);
170             DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
171             DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
172             String wspacePath = wspaceDoc.getPathAsString();
173             //give our own ID so PathRef could be constructed later on
174             String id = IdUtils.generateId(UUID.randomUUID().toString());
175             // create document model
176             DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
177             /* Check for a versioned document, and check In and Out before we proceed.
178              * This does not work as we do not have the uid schema on our docs.
179             if(((DocumentModelHandler) handler).supportsVersioning()) {
180                     doc.setProperty("uid","major_version",1);
181                     doc.setProperty("uid","minor_version",0);
182             }
183             */
184             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
185             DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
186             handler.handle(Action.CREATE, wrapDoc);
187             // create document with documentmodel
188             doc = repoSession.createDocument(doc);
189             repoSession.save();
190 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
191 // and assume the handler has the state it needs (doc fragments). 
192             handler.complete(Action.CREATE, wrapDoc);
193             return id;
194         } catch (BadRequestException bre) {
195             throw bre;
196         } catch (Exception e) {
197                 logger.error("Caught exception ", e);
198             throw new DocumentException(e);
199         } finally {
200             if (repoSession != null) {
201                 releaseRepositorySession(ctx, repoSession);
202             }
203         }
204
205     }
206
207     /**
208      * get document from the Nuxeo repository
209      * @param ctx service context under which this method is invoked
210      * @param id
211      *            of the document to retrieve
212      * @param handler
213      *            should be used by the caller to provide and transform the
214      *            document
215      * @throws DocumentNotFoundException if the document cannot be found in the repository
216      * @throws TransactionException
217      * @throws DocumentException
218      */
219     @Override
220     public void get(ServiceContext ctx, String id, DocumentHandler handler)
221             throws DocumentNotFoundException, TransactionException, DocumentException {
222
223         if (handler == null) {
224             throw new IllegalArgumentException(
225                     "RepositoryJavaClient.get: handler is missing");
226         }
227         
228         RepositoryInstance repoSession = null;
229         try {
230             handler.prepare(Action.GET);
231             repoSession = getRepositorySession(ctx);
232             DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
233             DocumentModel docModel = null;
234             try {
235                 docModel = repoSession.getDocument(docRef);
236                 assertWorkflowState(ctx, docModel);
237             } catch (ClientException ce) {
238                 String msg = logException(ce, "Could not find document with CSID=" + id);
239                 throw new DocumentNotFoundException(msg, ce);
240             }
241             //
242             // Set repository session to handle the document
243             //
244             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
245             DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
246             handler.handle(Action.GET, wrapDoc);
247             handler.complete(Action.GET, wrapDoc);
248         } catch (IllegalArgumentException iae) {
249             throw iae;
250         } catch (DocumentException de) {
251             throw de;
252         } catch (Exception e) {
253             if (logger.isDebugEnabled()) {
254                 logger.debug("Caught exception ", e);
255             }
256             throw new DocumentException(e);
257         } finally {
258             if (repoSession != null) {
259                 releaseRepositorySession(ctx, repoSession);
260             }
261         }
262     }
263
264     /**
265      * get a document from the Nuxeo repository, using the docFilter params.
266      * @param ctx service context under which this method is invoked
267      * @param handler
268      *            should be used by the caller to provide and transform the
269      *            document. Handler must have a docFilter set to return a single item.
270      * @throws DocumentNotFoundException if the document cannot be found in the repository
271      * @throws TransactionException
272      * @throws DocumentException
273      */
274     @Override
275     public void get(ServiceContext ctx, DocumentHandler handler)
276             throws DocumentNotFoundException, TransactionException, DocumentException {
277         QueryContext queryContext = new QueryContext(ctx, handler);
278         RepositoryInstance repoSession = null;
279
280         try {
281             handler.prepare(Action.GET);
282             repoSession = getRepositorySession(ctx);
283
284             DocumentModelList docList = null;
285             // force limit to 1, and ignore totalSize
286             String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
287             docList = repoSession.query(query, null, 1, 0, false);
288             if (docList.size() != 1) {
289                 throw new DocumentNotFoundException("No document found matching filter params: " + query);
290             }
291             DocumentModel doc = docList.get(0);
292
293             if (logger.isDebugEnabled()) {
294                 logger.debug("Executed NXQL query: " + query);
295             }
296
297             //set reposession to handle the document
298             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
299             DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
300             handler.handle(Action.GET, wrapDoc);
301             handler.complete(Action.GET, wrapDoc);
302         } catch (IllegalArgumentException iae) {
303             throw iae;
304         } catch (DocumentException de) {
305             throw de;
306         } catch (Exception e) {
307             if (logger.isDebugEnabled()) {
308                 logger.debug("Caught exception ", e);
309             }
310             throw new DocumentException(e);
311         } finally {
312             if (repoSession != null) {
313                 releaseRepositorySession(ctx, repoSession);
314             }
315         }
316     }
317     
318     public DocumentWrapper<DocumentModel> getDoc(
319                 RepositoryInstance repoSession,
320             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
321             String csid) throws DocumentNotFoundException, DocumentException {
322         DocumentWrapper<DocumentModel> wrapDoc = null;
323
324         try {
325             DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
326             DocumentModel doc = null;
327             try {
328                 doc = repoSession.getDocument(docRef);
329             } catch (ClientException ce) {
330                 String msg = logException(ce, "Could not find document with CSID=" + csid);
331                 throw new DocumentNotFoundException(msg, ce);
332             }
333             wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
334         } catch (IllegalArgumentException iae) {
335             throw iae;
336         } catch (DocumentException de) {
337             throw de;
338         }
339
340         return wrapDoc;
341     }
342     
343     /**
344      * Get wrapped documentModel from the Nuxeo repository.  The search is restricted to the workspace
345      * of the current context.
346      * 
347      * @param ctx service context under which this method is invoked
348      * @param csid
349      *            of the document to retrieve
350      * @throws DocumentNotFoundException
351      * @throws TransactionException
352      * @throws DocumentException
353      * @return a wrapped documentModel
354      */
355     @Override
356     public DocumentWrapper<DocumentModel> getDoc(
357             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
358             String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
359         RepositoryInstance repoSession = null;
360         DocumentWrapper<DocumentModel> wrapDoc = null;
361
362         try {
363                 // Open a new repository session
364             repoSession = getRepositorySession(ctx);
365             wrapDoc = getDoc(repoSession, ctx, csid);
366         } catch (IllegalArgumentException iae) {
367             throw iae;
368         } catch (DocumentException de) {
369             throw de;
370         } catch (Exception e) {
371             if (logger.isDebugEnabled()) {
372                 logger.debug("Caught exception ", e);
373             }
374             throw new DocumentException(e);
375         } finally {
376             if (repoSession != null) {
377                 releaseRepositorySession(ctx, repoSession);
378             }
379         }
380         
381         if (logger.isWarnEnabled() == true) {
382                 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
383         }
384         return wrapDoc;
385     }
386
387     public DocumentWrapper<DocumentModel> findDoc(
388             RepositoryInstance repoSession,
389             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
390             String whereClause)
391             throws DocumentNotFoundException, DocumentException {
392         DocumentWrapper<DocumentModel> wrapDoc = null;
393
394         try {
395             QueryContext queryContext = new QueryContext(ctx, whereClause);
396             DocumentModelList docList = null;
397             // force limit to 1, and ignore totalSize
398             String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
399             docList = repoSession.query(query,
400                     null, //Filter
401                     1, //limit
402                     0, //offset
403                     false); //countTotal
404             if (docList.size() != 1) {
405                 if (logger.isDebugEnabled()) {
406                     logger.debug("findDoc: Query found: " + docList.size() + " items.");
407                     logger.debug(" Query: " + query);
408                 }
409                 throw new DocumentNotFoundException("No document found matching filter params: " + query);
410             }
411             DocumentModel doc = docList.get(0);
412             wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
413         } catch (IllegalArgumentException iae) {
414             throw iae;
415         } catch (DocumentException de) {
416             throw de;
417         } catch (Exception e) {
418             if (logger.isDebugEnabled()) {
419                 logger.debug("Caught exception ", e);
420             }
421             throw new DocumentException(e);
422         }
423         
424         return wrapDoc;
425     }
426     
427     /**
428      * find wrapped documentModel from the Nuxeo repository
429      * @param ctx service context under which this method is invoked
430      * @param whereClause where NXQL where clause to get the document
431      * @throws DocumentNotFoundException
432      * @throws TransactionException
433      * @throws DocumentException
434      * @return a wrapped documentModel retrieved by the repository query
435      */
436     @Override
437     public DocumentWrapper<DocumentModel> findDoc(
438             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
439             String whereClause)
440                         throws DocumentNotFoundException, TransactionException, DocumentException {
441         RepositoryInstance repoSession = null;
442         DocumentWrapper<DocumentModel> wrapDoc = null;
443
444         try {
445             repoSession = getRepositorySession(ctx);
446             wrapDoc = findDoc(repoSession, ctx, whereClause);
447         } catch (Exception e) {
448                         throw new DocumentException("Unable to create a Nuxeo repository session.", e);
449                 } finally {
450             if (repoSession != null) {
451                 releaseRepositorySession(ctx, repoSession);
452             }
453         }
454         
455         if (logger.isWarnEnabled() == true) {
456                 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
457         }
458         
459         return wrapDoc;
460     }
461
462     /**
463      * find doc and return CSID from the Nuxeo repository
464      * @param repoSession
465      * @param ctx service context under which this method is invoked
466      * @param whereClause where NXQL where clause to get the document
467      * @throws DocumentNotFoundException
468      * @throws TransactionException
469      * @throws DocumentException
470      * @return the CollectionSpace ID (CSID) of the requested document
471      */
472     @Override
473     public String findDocCSID(RepositoryInstance repoSession, 
474             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
475             throws DocumentNotFoundException, TransactionException, DocumentException {
476         String csid = null;
477         boolean releaseSession = false;
478         try {
479                 if (repoSession == null) {
480                         repoSession = this.getRepositorySession(ctx);
481                         releaseSession = true;
482                 }
483             DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
484             DocumentModel docModel = wrapDoc.getWrappedObject();
485             csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
486         } catch (DocumentNotFoundException dnfe) {
487             throw dnfe;
488         } catch (IllegalArgumentException iae) {
489             throw iae;
490         } catch (DocumentException de) {
491             throw de;
492         } catch (Exception e) {
493             if (logger.isDebugEnabled()) {
494                 logger.debug("Caught exception ", e);
495             }
496             throw new DocumentException(e);
497         } finally {
498                 if(releaseSession && (repoSession != null)) {
499                         this.releaseRepositorySession(ctx, repoSession);
500                 }
501         }
502         return csid;
503     }
504
505     public DocumentWrapper<DocumentModelList> findDocs(
506             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
507             RepositoryInstance repoSession,
508             List<String> docTypes,
509             String whereClause,
510             String orderByClause,
511             int pageSize,
512             int pageNum,
513             boolean computeTotal)
514                         throws DocumentNotFoundException, DocumentException {
515         DocumentWrapper<DocumentModelList> wrapDoc = null;
516
517         try {
518             if (docTypes == null || docTypes.size() < 1) {
519                 throw new DocumentNotFoundException(
520                         "The findDocs() method must specify at least one DocumentType.");
521             }
522             DocumentModelList docList = null;
523             QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
524             String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
525             if (logger.isDebugEnabled()) {
526                 logger.debug("findDocs() NXQL: "+query);
527             }
528             docList = repoSession.query(query, null, pageSize, pageSize*pageNum, computeTotal);
529             wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
530         } catch (IllegalArgumentException iae) {
531             throw iae;
532         } catch (Exception e) {
533             if (logger.isDebugEnabled()) {
534                 logger.debug("Caught exception ", e);
535             }
536             throw new DocumentException(e);
537         }
538                 
539         return wrapDoc;
540     }
541     
542     protected static String buildInListForDocTypes(List<String> docTypes) {
543         StringBuilder sb = new StringBuilder();
544         sb.append("(");
545         boolean first = true;
546         for(String docType:docTypes) {
547                 if(first) {
548                         first = false;
549                 } else {
550                         sb.append(",");
551                 }
552                         sb.append("'");
553                 sb.append(docType);
554                         sb.append("'");
555         }
556         sb.append(")");
557         return sb.toString();
558     }
559     
560     public DocumentWrapper<DocumentModelList> findDocs(
561             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
562             DocumentHandler handler,
563             RepositoryInstance repoSession,
564             List<String> docTypes)
565                         throws DocumentNotFoundException, DocumentException {
566         DocumentWrapper<DocumentModelList> wrapDoc = null;
567
568         DocumentFilter filter = handler.getDocumentFilter();
569         String oldOrderBy = filter.getOrderByClause();
570         if (isClauseEmpty(oldOrderBy) == true){
571             filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
572         }
573         QueryContext queryContext = new QueryContext(ctx, handler);
574
575         try {
576             if (docTypes == null || docTypes.size() < 1) {
577                 throw new DocumentNotFoundException(
578                         "The findDocs() method must specify at least one DocumentType.");
579             }
580             DocumentModelList docList = null;
581                 if (handler.isCMISQuery() == true) {
582                         String inList = buildInListForDocTypes(docTypes);
583                         ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
584                         docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
585             } else {
586                 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
587                 if (logger.isDebugEnabled()) {
588                     logger.debug("findDocs() NXQL: "+query);
589                 }
590                 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
591             }
592             wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
593         } catch (IllegalArgumentException iae) {
594             throw iae;
595         } catch (Exception e) {
596             if (logger.isDebugEnabled()) {
597                 logger.debug("Caught exception ", e);
598             }
599             throw new DocumentException(e);
600         }
601                 
602         return wrapDoc;
603     }
604     
605
606     
607     /**
608      * Find a list of documentModels from the Nuxeo repository
609      * @param docTypes a list of DocType names to match
610      * @param  whereClause where the clause to qualify on
611      * @throws DocumentNotFoundException
612      * @throws TransactionException
613      * @throws DocumentException
614      * @return a list of documentModels
615      */
616     @Override
617     public DocumentWrapper<DocumentModelList> findDocs(
618             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
619             List<String> docTypes,
620             String whereClause,
621             int pageSize, int pageNum, boolean computeTotal)
622             throws DocumentNotFoundException, TransactionException, DocumentException {
623         RepositoryInstance repoSession = null;
624         DocumentWrapper<DocumentModelList> wrapDoc = null;
625
626         try {
627             repoSession = getRepositorySession(ctx);
628             wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
629                         pageSize, pageNum, computeTotal);
630         } catch (IllegalArgumentException iae) {
631             throw iae;
632         } catch (Exception e) {
633             if (logger.isDebugEnabled()) {
634                 logger.debug("Caught exception ", e);
635             }
636             throw new DocumentException(e);
637         } finally {
638             if (repoSession != null) {
639                 releaseRepositorySession(ctx, repoSession);
640             }
641         }
642         
643         if (logger.isWarnEnabled() == true) {
644                 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
645         }
646         
647         return wrapDoc;
648     }
649
650     /* (non-Javadoc)
651      * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
652      */
653     @Override
654     public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
655             throws DocumentNotFoundException, TransactionException, DocumentException {
656         if (handler == null) {
657             throw new IllegalArgumentException(
658                     "RepositoryJavaClient.getAll: handler is missing");
659         }
660
661         RepositoryInstance repoSession = null;
662         try {
663             handler.prepare(Action.GET_ALL);
664             repoSession = getRepositorySession(ctx);
665             DocumentModelList docModelList = new DocumentModelListImpl();
666             //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
667             for (String csid : csidList) {
668                 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
669                 DocumentModel docModel = repoSession.getDocument(docRef);
670                 docModelList.add(docModel);
671             }
672
673             //set reposession to handle the document
674             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
675             DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
676             handler.handle(Action.GET_ALL, wrapDoc);
677             handler.complete(Action.GET_ALL, wrapDoc);
678         } catch (DocumentException de) {
679             throw de;
680         } catch (Exception e) {
681             if (logger.isDebugEnabled()) {
682                 logger.debug("Caught exception ", e);
683             }
684             throw new DocumentException(e);
685         } finally {
686             if (repoSession != null) {
687                 releaseRepositorySession(ctx, repoSession);
688             }
689         }
690     }
691
692     /**
693      * getAll get all documents for an entity entity service from the Nuxeo
694      * repository
695      *
696      * @param ctx service context under which this method is invoked
697      * @param handler
698      *            should be used by the caller to provide and transform the
699      *            document
700      * @throws DocumentNotFoundException
701      * @throws TransactionException
702      * @throws DocumentException
703      */
704     @Override
705     public void getAll(ServiceContext ctx, DocumentHandler handler)
706             throws DocumentNotFoundException, TransactionException, DocumentException {
707         if (handler == null) {
708             throw new IllegalArgumentException(
709                     "RepositoryJavaClient.getAll: handler is missing");
710         }
711         String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
712         if (nuxeoWspaceId == null) {
713             throw new DocumentNotFoundException(
714                     "Unable to find workspace for service "
715                     + ctx.getServiceName()
716                     + " check if the workspace exists in the Nuxeo repository.");
717         }
718         
719         RepositoryInstance repoSession = null;
720         try {
721             handler.prepare(Action.GET_ALL);
722             repoSession = getRepositorySession(ctx);
723             DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
724             DocumentModelList docList = repoSession.getChildren(wsDocRef);
725             //set reposession to handle the document
726             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
727             DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
728             handler.handle(Action.GET_ALL, wrapDoc);
729             handler.complete(Action.GET_ALL, wrapDoc);
730         } catch (DocumentException de) {
731             throw de;
732         } catch (Exception e) {
733             if (logger.isDebugEnabled()) {
734                 logger.debug("Caught exception ", e);
735             }
736             throw new DocumentException(e);
737         } finally {
738             if (repoSession != null) {
739                 releaseRepositorySession(ctx, repoSession);
740             }
741         }
742     }
743     
744     private boolean isClauseEmpty(String theString) {
745         boolean result = true;
746         if (theString != null && !theString.isEmpty()) {
747                 result = false;
748         }
749         return result;
750     }
751     
752     public DocumentWrapper<DocumentModel> getDocFromCsid(
753                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
754                 RepositoryInstance repoSession,
755                 String csid)
756             throws Exception {
757         DocumentWrapper<DocumentModel> result = null;
758
759         result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
760         
761         return result;
762     }    
763
764     /*
765      * A method to find a CollectionSpace document (of any type) given just a service context and
766      * its CSID.  A search across *all* service workspaces (within a given tenant context) is performed to find
767      * the document
768      * 
769      * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
770      */
771     @Override
772     public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
773                 String csid)
774             throws Exception {
775         DocumentWrapper<DocumentModel> result = null;
776         RepositoryInstance repoSession = null;
777         try {
778                 repoSession = getRepositorySession(ctx);
779                 result = getDocFromCsid(ctx, repoSession, csid);
780         } finally {
781             if (repoSession != null) {
782                 releaseRepositorySession(ctx, repoSession);
783             }
784         }
785         
786         if (logger.isWarnEnabled() == true) {
787                 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
788         }
789         
790         return result;
791     }
792
793     /**
794      * Returns a URI value for a document in the Nuxeo repository
795      * @param wrappedDoc a wrapped documentModel
796      * @throws ClientException
797      * @return a document URI
798      */
799     @Override
800     public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
801         DocumentModel docModel = wrappedDoc.getWrappedObject();
802         String uri = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
803                         CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
804         return uri;
805     }
806
807     /*
808      * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
809      */
810         private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
811                 IterableQueryResult result = null;
812                 
813                 // the NuxeoRepository should be constructed only once, then cached
814                 // (its construction is expensive)
815                 try {
816                         NuxeoRepository repo = new NuxeoRepository(
817                                         repoSession.getRepositoryName(), repoSession
818                                                         .getRootDocument().getId());
819                         logger.debug("Repository ID:" + repo.getId() + " Root folder:"
820                                         + repo.getRootFolderId());
821
822                         CallContextImpl callContext = new CallContextImpl(
823                                         CallContext.BINDING_LOCAL, repo.getId(), false);
824                         callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
825                                         .getName());
826                         NuxeoCmisService cmisService = new NuxeoCmisService(repo,
827                                         callContext, repoSession);
828
829                         result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
830                 } catch (ClientException e) {
831                         // TODO Auto-generated catch block
832                         logger.error("Encounter trouble making the following CMIS query: " + query, e);
833                 }
834                 
835                 return result;
836         }
837      
838     /**
839      * getFiltered get all documents for an entity service from the Document repository,
840      * given filter parameters specified by the handler. 
841      * @param ctx service context under which this method is invoked
842      * @param handler should be used by the caller to provide and transform the document
843      * @throws DocumentNotFoundException if workspace not found
844      * @throws TransactionException
845      * @throws DocumentException
846      */
847     @Override
848     public void getFiltered(ServiceContext ctx, DocumentHandler handler)
849             throws DocumentNotFoundException, TransactionException, DocumentException {
850
851         DocumentFilter filter = handler.getDocumentFilter();
852         String oldOrderBy = filter.getOrderByClause();
853         if (isClauseEmpty(oldOrderBy) == true){
854             filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
855         }
856         QueryContext queryContext = new QueryContext(ctx, handler);
857
858         RepositoryInstance repoSession = null;
859         try {
860             handler.prepare(Action.GET_ALL);
861             repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
862             
863             DocumentModelList docList = null;
864             String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
865
866             if (logger.isDebugEnabled()) {
867                 logger.debug("Executing NXQL query: " + query.toString());
868             }
869
870             // If we have limit and/or offset, then pass true to get totalSize
871             // in returned DocumentModelList.
872                 Profiler profiler = new Profiler(this, 2);
873                 profiler.log("Executing NXQL query: " + query.toString());
874                 profiler.start();
875                 if (handler.isJDBCQuery() == true) {
876                         docList = getFilteredJDBC(repoSession, ctx, handler, queryContext);
877                 } else if (handler.isCMISQuery() == true) {
878                         docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
879                 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
880                 docList = repoSession.query(query, null,
881                         queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
882             } else {
883                 docList = repoSession.query(query);
884             }
885             profiler.stop();
886
887             //set repoSession to handle the document
888             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
889             DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
890             handler.handle(Action.GET_ALL, wrapDoc);
891             handler.complete(Action.GET_ALL, wrapDoc);
892         } catch (DocumentException de) {
893             throw de;
894         } catch (Exception e) {
895             if (logger.isDebugEnabled()) {
896                 logger.debug("Caught exception ", e);
897             }
898             throw new DocumentException(e);
899         } finally {
900             if (repoSession != null) {
901                 releaseRepositorySession(ctx, repoSession);
902             }
903         }
904     }
905     
906     private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
907             throws Exception {
908         DocumentModelList result = new DocumentModelListImpl();
909         
910         String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
911         String repositoryName = ctx.getRepositoryName();
912         Connection connection = JDBCTools.getConnection(dataSourceName, repositoryName);
913         
914         MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
915         String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
916         
917         // FIXME: Replace this placeholder with an appropriate per-authority value
918         // obtained from the relevant document handler
919         String termInfoGroupTable = "loctermgroup";
920         
921         // FIXME: Replace this placeholder query with an actual query from CSPACE-5945
922         // FIXME: Consider using a prepared statement here
923         String theQuery =
924                 "SELECT termdisplayname FROM "
925                 + termInfoGroupTable
926                 + " WHERE termdisplayname LIKE '" + partialTerm + "%'";
927
928         // Make sure autocommit is off. See:
929         // http://jdbc.postgresql.org/documentation/80/query.html#query-with-cursor
930         // http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
931         connection.setAutoCommit(false);
932         
933         // FIXME: Add exception handling and 'finally' blocks to ensure we close resources
934         // FIXME: Identify whether we can piggyback on existing JDBC method(s) in common.storage,
935         // and if so, add whatever additional functionality may be required to those method(s)
936         // FIXME: Add pagination handling
937         
938         Statement st = connection.createStatement();
939         // Enable use of the cursor for pagination
940         st.setFetchSize(50);
941         List<String> docIds = new ArrayList<String>();
942         ResultSet rs = st.executeQuery(theQuery);
943         String id;
944         while (rs.next()) {
945             id = rs.getString("id");
946             if (Tools.notBlank(id)) {
947                 docIds.add(id);
948             }
949         }
950         rs.close();
951
952         // Close the statement.
953         st.close();
954
955         // Get a list of document models, using the IDs obtained from the query
956         for (String docId : docIds) {
957             result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
958         }
959         
960         return result;
961     }
962
963     private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
964             throws DocumentNotFoundException, DocumentException {
965
966         DocumentModelList result = new DocumentModelListImpl();
967         try {
968             String query = handler.getCMISQuery(queryContext);
969
970                 DocumentFilter docFilter = handler.getDocumentFilter();
971             int pageSize = docFilter.getPageSize();
972             int offset = docFilter.getOffset();
973             if (logger.isDebugEnabled()) {
974                 logger.debug("Executing CMIS query: " + query.toString()
975                                 + "with pageSize: "+pageSize+" at offset: "+offset);
976             }
977
978             // If we have limit and/or offset, then pass true to get totalSize
979             // in returned DocumentModelList.
980                 Profiler profiler = new Profiler(this, 2);
981                 profiler.log("Executing CMIS query: " + query.toString());
982                 profiler.start();
983                 //
984                 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
985                 try {
986                 int totalSize = (int)queryResult.size();
987                 ((DocumentModelListImpl)result).setTotalSize(totalSize);
988                                 // Skip the rows before our offset
989                                 if (offset > 0) {
990                                         queryResult.skipTo(offset);
991                                 }
992                         int nRows = 0;
993                         for (Map<String, Serializable> row : queryResult) {
994                                 if (logger.isTraceEnabled()) {
995                                         logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
996                                                         + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
997                                 }
998                                 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
999                                 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1000                                 result.add(docModel);
1001                                 nRows++;
1002                                         if (nRows >= pageSize && pageSize != 0 ) { // A page size of zero means that they want all of them
1003                                                 logger.debug("Got page full of items - quitting");
1004                                                 break;
1005                                         }
1006                         }
1007                 } finally {
1008                         queryResult.close();
1009                 }
1010                 //
1011             profiler.stop();
1012
1013         } catch (Exception e) {
1014             if (logger.isDebugEnabled()) {
1015                 logger.debug("Caught exception ", e);
1016             }
1017             throw new DocumentException(e);
1018         }
1019         
1020         //
1021         // Since we're not supporting paging yet for CMIS queries, we need to perform
1022         // a workaround for the paging information we return in our list of results
1023         //
1024         /*
1025         if (result != null) {
1026                 docFilter.setStartPage(0);
1027                 if (totalSize > docFilter.getPageSize()) {
1028                         docFilter.setPageSize(totalSize);
1029                 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1030                 }
1031         }
1032         */
1033         
1034         return result;
1035     }
1036     
1037     private String logException(Exception e, String msg) {
1038         String result = null;
1039         
1040         String exceptionMessage = e.getMessage();
1041         exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1042         result = msg = msg + ". Caught exception:" + exceptionMessage;
1043         
1044         if (logger.isTraceEnabled() == true) {
1045                 logger.error(msg, e);
1046         } else {
1047                 logger.error(msg);
1048         }
1049         
1050         return result;
1051     }
1052     
1053     /**
1054      * update given document in the Nuxeo repository
1055      *
1056      * @param ctx service context under which this method is invoked
1057      * @param csid
1058      *            of the document
1059      * @param handler
1060      *            should be used by the caller to provide and transform the
1061      *            document
1062      * @throws BadRequestException
1063      * @throws DocumentNotFoundException
1064      * @throws TransactionException if the transaction times out or otherwise cannot be successfully completed
1065      * @throws DocumentException
1066      */
1067     @Override
1068     public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1069             throws BadRequestException, DocumentNotFoundException, TransactionException,
1070             DocumentException {
1071         if (handler == null) {
1072             throw new IllegalArgumentException(
1073                     "RepositoryJavaClient.update: document handler is missing.");
1074         }
1075         
1076         RepositoryInstance repoSession = null;
1077         try {
1078             handler.prepare(Action.UPDATE);
1079             repoSession = getRepositorySession(ctx);
1080             DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1081             DocumentModel doc = null;
1082             try {
1083                 doc = repoSession.getDocument(docRef);
1084             } catch (ClientException ce) {
1085                 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1086                 throw new DocumentNotFoundException(msg, ce);
1087             }
1088             // Check for a versioned document, and check In and Out before we proceed.
1089             if(((DocumentModelHandler) handler).supportsVersioning()) {
1090                 /* Once we advance to 5.5 or later, we can add this. 
1091                  * See also https://jira.nuxeo.com/browse/NXP-8506
1092                 if(!doc.isVersionable()) {
1093                         throw new DocumentException("Configuration for: "
1094                                         +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1095                 }
1096                  */
1097                 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1098                     if(doc.getProperty("uid","major_version") == null) {
1099                             doc.setProperty("uid","major_version",1);
1100                     }
1101                     if(doc.getProperty("uid","minor_version") == null) {
1102                             doc.setProperty("uid","minor_version",0);
1103                     }
1104                     */
1105                 doc.checkIn(VersioningOption.MINOR, null); 
1106                 doc.checkOut();
1107             }
1108             
1109             //
1110             // Set reposession to handle the document
1111             //
1112             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1113             DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1114             handler.handle(Action.UPDATE, wrapDoc);
1115             repoSession.saveDocument(doc);
1116             repoSession.save();
1117             handler.complete(Action.UPDATE, wrapDoc);
1118         } catch (BadRequestException bre) {
1119             throw bre;
1120         } catch (DocumentException de) {
1121             throw de;
1122         } catch (WebApplicationException wae){
1123             throw wae;
1124         } catch (Exception e) {
1125             if (logger.isDebugEnabled()) {
1126                 logger.debug("Caught exception ", e);
1127             }
1128             throw new DocumentException(e);
1129         } finally {
1130             if (repoSession != null) {
1131                 releaseRepositorySession(ctx, repoSession);
1132             }
1133         }
1134     }
1135     
1136     /**
1137      * Save a documentModel to the Nuxeo repository.
1138      * @param ctx service context under which this method is invoked
1139      * @param repoSession
1140      * @param docModel the document to save
1141      * @param fSaveSession if TRUE, will call CoreSession.save() to save accumulated changes.
1142      * @throws ClientException
1143      * @throws DocumentException
1144      */
1145     public void saveDocWithoutHandlerProcessing(
1146             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1147             RepositoryInstance repoSession,
1148             DocumentModel docModel,
1149             boolean fSaveSession)
1150             throws ClientException, DocumentException {
1151
1152         try {
1153             repoSession.saveDocument(docModel);
1154             if (fSaveSession) {
1155                 repoSession.save();
1156             }
1157         } catch (ClientException ce) {
1158             throw ce;
1159         } catch (Exception e) {
1160             if (logger.isDebugEnabled()) {
1161                 logger.debug("Caught exception ", e);
1162             }
1163             throw new DocumentException(e);
1164         }
1165     }
1166
1167
1168     /**
1169      * Save a list of documentModels to the Nuxeo repository.
1170      * 
1171      * @param ctx service context under which this method is invoked
1172      * @param repoSession a repository session
1173      * @param docModelList a list of document models
1174      * @param fSaveSession if TRUE, will call CoreSession.save() to save accumulated changes.
1175      * @throws ClientException
1176      * @throws DocumentException
1177      */
1178     public void saveDocListWithoutHandlerProcessing(
1179             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1180             RepositoryInstance repoSession,
1181             DocumentModelList docList, 
1182             boolean fSaveSession)
1183             throws ClientException, DocumentException {
1184         try {
1185             DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1186             repoSession.saveDocuments(docList.toArray(docModelArray));
1187             if (fSaveSession) {
1188                 repoSession.save();
1189             }
1190         } catch (ClientException ce) {
1191             throw ce;
1192         } catch (Exception e) {
1193             logger.error("Caught exception ", e);
1194             throw new DocumentException(e);
1195         }
1196     }
1197
1198     /**
1199      * delete a document from the Nuxeo repository
1200      * @param ctx service context under which this method is invoked
1201      * @param id
1202      *            of the document
1203      * @throws DocumentException
1204      */
1205     @Override
1206     public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1207             DocumentException, TransactionException {
1208         if (ctx == null) {
1209             throw new IllegalArgumentException(
1210                     "delete(ctx, ix, handler): ctx is missing");
1211         }
1212         if (handler == null) {
1213             throw new IllegalArgumentException(
1214                     "delete(ctx, ix, handler): handler is missing");
1215         }
1216         if (logger.isDebugEnabled()) {
1217             logger.debug("Deleting document with CSID=" + id);
1218         }
1219         RepositoryInstance repoSession = null;
1220         try {
1221                 handler.prepare(Action.DELETE);
1222             repoSession = getRepositorySession(ctx);
1223             DocumentWrapper<DocumentModel> wrapDoc = null;
1224             try {
1225                 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1226                     wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1227                     ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1228                     handler.handle(Action.DELETE, wrapDoc);
1229                 repoSession.removeDocument(docRef);
1230             } catch (ClientException ce) {
1231                 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1232                 throw new DocumentNotFoundException(msg, ce);
1233             }
1234             repoSession.save();
1235             handler.complete(Action.DELETE, wrapDoc);
1236         } catch (DocumentException de) {
1237             throw de;
1238         } catch (Exception e) {
1239             if (logger.isDebugEnabled()) {
1240                 logger.debug("Caught exception ", e);
1241             }
1242             throw new DocumentException(e);
1243         } finally {
1244             if (repoSession != null) {
1245                 releaseRepositorySession(ctx, repoSession);
1246             }
1247         }
1248     }
1249
1250     /* (non-Javadoc)
1251      * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1252      */
1253     @Override
1254     @Deprecated
1255     public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1256             throws DocumentNotFoundException, DocumentException {
1257         throw new UnsupportedOperationException();
1258         // Use the other delete instead
1259     }
1260
1261     @Override
1262     public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1263         return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1264     }
1265
1266     @Override
1267     public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1268         RepositoryInstance repoSession = null;
1269         String domainId = null;
1270         try {
1271                 //
1272                 // Open a connection to the domain's repo/db
1273                 //
1274                 String repoName = repositoryDomain.getRepositoryName();
1275             repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1276                 //
1277                 // First create the top-level domain directory
1278                 //
1279                 String domainName = repositoryDomain.getStorageName();
1280             DocumentRef parentDocRef = new PathRef("/");
1281             DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1282             DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1283                     domainName, NUXEO_CORE_TYPE_DOMAIN);
1284             domainDoc.setPropertyValue("dc:title", domainName);
1285             domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1286                     + domainName);
1287             domainDoc = repoSession.createDocument(domainDoc);
1288             domainId = domainDoc.getId();
1289             repoSession.save();
1290             //
1291             // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1292             //
1293             DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1294                         NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1295             workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1296             workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1297                     + domainDoc.getPathAsString());
1298             workspacesRoot = repoSession.createDocument(workspacesRoot);
1299             String workspacesRootId = workspacesRoot.getId();
1300             repoSession.save();
1301             
1302             if (logger.isDebugEnabled()) {
1303                 logger.debug("Created tenant domain name=" + domainName
1304                         + " id=" + domainId + " " +
1305                         NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1306                 logger.debug("Path to Domain: "+domainDoc.getPathAsString());
1307                 logger.debug("Path to Workspaces root: "+workspacesRoot.getPathAsString());
1308             }
1309         } catch (Exception e) {
1310             if (logger.isDebugEnabled()) {
1311                 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1312             }
1313             throw e;
1314         } finally {
1315             if (repoSession != null) {
1316                 releaseRepositorySession(null, repoSession);
1317             }
1318         }
1319         
1320         return domainId;
1321     }
1322
1323     @Override
1324     public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1325         String domainId = null;
1326         RepositoryInstance repoSession = null;
1327         
1328         String repoName = repositoryDomain.getRepositoryName();
1329         String domainStorageName = repositoryDomain.getStorageName();
1330         if (domainStorageName != null && !domainStorageName.isEmpty()) {
1331                 try {
1332                     repoSession = getRepositorySession(repoName);
1333                     DocumentRef docRef = new PathRef("/" + domainStorageName);
1334                     DocumentModel domain = repoSession.getDocument(docRef);
1335                     domainId = domain.getId();
1336                 } catch (Exception e) {
1337                     if (logger.isTraceEnabled()) {
1338                         logger.trace("Caught exception ", e);  // The document doesn't exist, this let's us know we need to create it
1339                     }
1340                     //there is no way to identify if document does not exist due to
1341                     //lack of typed exception for getDocument method
1342                     return null;
1343                 } finally {
1344                     if (repoSession != null) {
1345                         releaseRepositorySession(null, repoSession);
1346                     }
1347                 }
1348         }
1349         
1350         return domainId;
1351     }
1352
1353     /*
1354          * Returns the workspaces root directory for a given domain.
1355          */
1356         private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1357                         String domainName) throws Exception {
1358                 DocumentModel result = null;
1359                 
1360                 String domainPath = "/" + domainName;
1361                 DocumentRef parentDocRef = new PathRef(domainPath);
1362                 DocumentModelList domainChildrenList = repoSession.getChildren(
1363                                 parentDocRef);
1364                 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1365                 while (witer.hasNext()) {
1366                         DocumentModel childNode = witer.next();
1367                         if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1368                                 result = childNode;
1369                                 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1370                                 break;
1371                         }
1372                 }
1373                 
1374                 if (result == null) {
1375                         throw new ClientException("Could not find workspace root directory in: "
1376                                         + domainPath);
1377                 }
1378
1379                 return result;
1380         }
1381     
1382     /* (non-Javadoc)
1383      * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1384      */
1385     @Override
1386     public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1387         RepositoryInstance repoSession = null;
1388         String workspaceId = null;
1389         try {
1390                 String repoName = repositoryDomain.getRepositoryName();
1391             repoSession = getRepositorySession(repoName);
1392             
1393             String domainStorageName = repositoryDomain.getStorageName();
1394             DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1395             if (logger.isTraceEnabled()) {
1396                     for (String facet : parentDoc.getFacets()) {
1397                         logger.trace("Facet: " + facet);
1398                     }
1399             }
1400             
1401             DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1402                     workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1403             doc.setPropertyValue("dc:title", workspaceName);
1404             doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1405                     + workspaceName);
1406             doc = repoSession.createDocument(doc);
1407             workspaceId = doc.getId();
1408             repoSession.save();
1409             if (logger.isDebugEnabled()) {
1410                 logger.debug("Created workspace name=" + workspaceName
1411                         + " id=" + workspaceId);
1412             }
1413         } catch (Exception e) {
1414             if (logger.isDebugEnabled()) {
1415                 logger.debug("createWorkspace caught exception ", e);
1416             }
1417             throw e;
1418         } finally {
1419             if (repoSession != null) {
1420                 releaseRepositorySession(null, repoSession);
1421             }
1422         }
1423         return workspaceId;
1424     }
1425
1426     /* (non-Javadoc)
1427      * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1428      */
1429     @Override
1430     @Deprecated
1431     public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1432         String workspaceId = null;
1433         
1434         RepositoryInstance repoSession = null;
1435         try {
1436             repoSession = getRepositorySession((ServiceContext)null);
1437             DocumentRef docRef = new PathRef(
1438                     "/" + tenantDomain
1439                     + "/" + NuxeoUtils.Workspaces
1440                     + "/" + workspaceName);
1441             DocumentModel workspace = repoSession.getDocument(docRef);
1442             workspaceId = workspace.getId();
1443         } catch (DocumentException de) {
1444             throw de;
1445         } catch (Exception e) {
1446             if (logger.isDebugEnabled()) {
1447                 logger.debug("Caught exception ", e);
1448             }
1449             throw new DocumentException(e);
1450         } finally {
1451             if (repoSession != null) {
1452                 releaseRepositorySession(null, repoSession);
1453             }
1454         }
1455         
1456         return workspaceId;
1457     }
1458
1459     public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1460         return getRepositorySession(ctx, ctx.getRepositoryName());
1461     }
1462     
1463     public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1464         return getRepositorySession(null, repoName);
1465     }
1466     
1467     /**
1468      * Gets the repository session. - Package access only.  If the 'ctx' param is null then the repo name must be non-mull and vice-versa
1469      *
1470      * @return the repository session
1471      * @throws Exception the exception
1472      */
1473     public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1474         RepositoryInstance repoSession = null;
1475         
1476         Profiler profiler = new Profiler("getRepositorySession():", 2);
1477         profiler.start();
1478         //
1479         // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1480         //
1481         if (ctx != null) {
1482                 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1483                 repoSession = (RepositoryInstance)ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1484         } else if (repoName == null || repoName.trim().isEmpty()) {
1485                 String errMsg = String.format("We can't get a connection to the Nuxeo repo because the service context passed in was null and no repository name was passed in either.");
1486                 logger.error(errMsg);
1487                 throw new Exception(errMsg);
1488         }        
1489         //
1490         // If we couldn't find a repoSession from the service context (or the context was null) then we need to create a new one using
1491         // just the repo name
1492         //
1493         if (repoSession == null) {
1494                 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1495                 repoSession = client.openRepository(repoName);
1496         } else {
1497             if (logger.isDebugEnabled() == true) {
1498                 logger.warn("Reusing the current context's repository session.");
1499             }           
1500         }
1501         
1502         if (logger.isTraceEnabled()) {
1503             logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1504         }
1505         
1506         profiler.stop();
1507         
1508         if (ctx != null) {
1509                 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1510         }
1511         
1512         return repoSession;
1513     }
1514
1515     /**
1516      * Release repository session. - Package access only.
1517      *
1518      * @param repoSession the repo session
1519      */
1520     public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1521         try {
1522             NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1523             // release session
1524             if (ctx != null) {
1525                 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1526                 if (ctx.getCurrentRepositorySession() == null) {
1527                     client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1528                 }
1529             } else {
1530                 client.releaseRepository(repoSession); //repo session was acquired without a service context
1531             }
1532         } catch (TransactionRuntimeException tre) {
1533             TransactionException te = new TransactionException(tre);
1534             logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1535             throw te;
1536         } catch (Exception e) {
1537             logger.error("Could not close the repository session", e);
1538             // no need to throw this service specific exception
1539         }
1540     }
1541
1542         @Override
1543         public void doWorkflowTransition(ServiceContext ctx, String id,
1544                         DocumentHandler handler, TransitionDef transitionDef)
1545                         throws BadRequestException, DocumentNotFoundException,
1546                         DocumentException {
1547                 // 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
1548         }
1549                 
1550 }