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