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