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