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