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