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