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