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