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