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