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