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