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