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