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