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