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