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