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