]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
3a1fd1adb9b6bc1c05ff508ad15a06ae38ccc8a5
[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
944         String whereClause;
945         MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
946         String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
947         // If the value of the partial term query parameter is blank ('pt='),
948         // return all records, subject to restriction by any limit clause
949         if (Tools.isBlank(partialTerm)) {
950            whereClause = "";
951         } else {
952            // Otherwise, return records that match the supplied partial term
953            whereClause =
954                 " WHERE (termgroup.termdisplayname ILIKE ?)";
955         }
956         
957         // At present, results are ordered in code, below, rather than in SQL,
958         // and the orderByClause below is thus intentionally blank.
959         //
960         // To implement the orderByClause below in SQL; e.g. via
961         // 'ORDER BY termgroup.termdisplayname', the relevant column
962         // must be returned by the SELECT statement.
963         String orderByClause = "";
964         
965         String limitClause;
966         TenantBindingConfigReaderImpl tReader =
967                 ServiceMain.getInstance().getTenantBindingConfigReader();
968         TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
969         String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
970                 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
971         limitClause =
972                 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
973         
974         List<String> params = new ArrayList<>();
975
976         // Read tenant bindings configuration to determine whether
977         // to automatically insert leading, as well as trailing, wildcards
978         // into the term matching string.
979         String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
980                 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
981         // Handle user-provided leading wildcard characters, in the
982         // configuration where a leading wildcard is not automatically inserted.
983         // (The user-provided wildcard must be in the first, or "starting"
984         // character position in the partial term value.)
985         if (Tools.notBlank(usesStartingWildcard) && usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
986             partialTerm = handleProvidedStartingWildcard(partialTerm);
987             // Otherwise, automatically insert a leading wildcard
988         } else {
989             partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
990         }
991         // Automatically insert a trailing wildcard
992         params.add(partialTerm + JDBCTools.SQL_WILDCARD); // Value for replaceable parameter 1 in the query
993         
994         // Restrict the query to filter out deleted records, if requested
995         String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
996         if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
997             joinClauses = joinClauses
998                 + " INNER JOIN misc"
999                 + "  ON misc.id = hierarchy_termgroup.parentid";
1000             whereClause = whereClause
1001                 + "  AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')";
1002         }
1003
1004         // If a particular authority is specified, restrict the query further
1005         // to return only records within that authority
1006         String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1007         if (Tools.notBlank(inAuthorityValue)) {
1008             // Handle the '_ALL_' case for inAuthority
1009             if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1010                 // Add nothing to the query here if it should match within all authorities
1011             } else {
1012                 joinClauses = joinClauses
1013                     + " INNER JOIN " + handler.getServiceContext().getCommonPartLabel() + " commonschema"
1014                     + "  ON commonschema.id = hierarchy_termgroup.parentid";
1015                 whereClause = whereClause
1016                     + "  AND (commonschema.inauthority = ?)";
1017                 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1018             }
1019         }
1020         
1021         // Restrict the query further to return only records pertaining to
1022         // the current tenant, unless:
1023         // * Data for this service, in this tenant, is stored in its own,
1024         //   separate repository, rather than being intermingled with other
1025         //   tenants' data in the default repository; or
1026         // * Restriction by tenant ID in JDBC queries has been disabled,
1027         //   via configuration for this tenant, 
1028         if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1029                 joinClauses = joinClauses
1030                     + " INNER JOIN collectionspace_core core"
1031                     + "  ON core.id = hierarchy_termgroup.parentid";
1032                 whereClause = whereClause
1033                     + "  AND (core.tenantid = ?)";
1034                 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1035         }
1036         
1037         // Piece together the SQL query from its parts
1038         String sql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1039         
1040         // Note: PostgreSQL 9.2 introduced a change that may improve performance
1041         // of certain queries using JDBC PreparedStatements.  See comments on
1042         // CSPACE-5943 for details.
1043         PreparedStatementSimpleBuilder jdbcFilterQueryBuilder = new PreparedStatementSimpleBuilder(sql, params);
1044         String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1045         String repositoryName = ctx.getRepositoryName();
1046         Set<String> docIds = new HashSet<>();
1047         try (CachedRowSet crs = JDBCTools.executePreparedQuery(jdbcFilterQueryBuilder,
1048                 dataSourceName, repositoryName, sql)) {
1049
1050             // If the response to the query is null or contains zero rows,
1051             // return an empty list of document models
1052             if (crs == null) {
1053                 return result;
1054             }
1055             crs.last();
1056             if (crs.getRow() == 0) {
1057                 return result; // empty list of document models
1058             }
1059
1060             // Otherwise, get the document IDs from the results of the query
1061             String id;
1062             crs.beforeFirst();
1063             while (crs.next()) {
1064                 id = crs.getString(1);
1065                 if (Tools.notBlank(id)) {
1066                     docIds.add(id);
1067                 }
1068             }
1069         } catch (SQLException sqle) {
1070             logger.warn("Could not obtain document IDs via SQL query '" + sql + "': " + sqle.getMessage());
1071             return result; // return an empty list of document models
1072         } 
1073
1074         // Get a list of document models, using the IDs obtained from the query
1075         DocumentModel docModel;
1076         for (String docId : docIds) {
1077             docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1078             if (docModel == null) {
1079                 logger.warn("Could not obtain document model for document with ID " + docId);
1080             } else {
1081                 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
1082             }
1083         }
1084         
1085         // Order the results
1086         final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1087         final String DISPLAY_NAME_XPATH =
1088                 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1089         Collections.sort(result, new Comparator<DocumentModel>() {
1090             @Override
1091             public int compare(DocumentModel doc1, DocumentModel doc2) {
1092                 String termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1093                 String termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1094                 return termDisplayName1.compareTo(termDisplayName2);
1095             }
1096         });
1097
1098         return result;
1099     }
1100     
1101
1102     private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
1103             throws DocumentNotFoundException, DocumentException {
1104
1105         DocumentModelList result = new DocumentModelListImpl();
1106         try {
1107             String query = handler.getCMISQuery(queryContext);
1108
1109             DocumentFilter docFilter = handler.getDocumentFilter();
1110             int pageSize = docFilter.getPageSize();
1111             int offset = docFilter.getOffset();
1112             if (logger.isDebugEnabled()) {
1113                 logger.debug("Executing CMIS query: " + query.toString()
1114                         + "with pageSize: " + pageSize + " at offset: " + offset);
1115             }
1116
1117             // If we have limit and/or offset, then pass true to get totalSize
1118             // in returned DocumentModelList.
1119             Profiler profiler = new Profiler(this, 2);
1120             profiler.log("Executing CMIS query: " + query.toString());
1121             profiler.start();
1122             //
1123             IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1124             try {
1125                 int totalSize = (int) queryResult.size();
1126                 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1127                 // Skip the rows before our offset
1128                 if (offset > 0) {
1129                     queryResult.skipTo(offset);
1130                 }
1131                 int nRows = 0;
1132                 for (Map<String, Serializable> row : queryResult) {
1133                     if (logger.isTraceEnabled()) {
1134                         logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1135                                 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1136                     }
1137                     String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1138                     DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1139                     result.add(docModel);
1140                     nRows++;
1141                     if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1142                         logger.debug("Got page full of items - quitting");
1143                         break;
1144                     }
1145                 }
1146             } finally {
1147                 queryResult.close();
1148             }
1149             //
1150             profiler.stop();
1151
1152         } catch (Exception e) {
1153             if (logger.isDebugEnabled()) {
1154                 logger.debug("Caught exception ", e);
1155             }
1156             throw new DocumentException(e);
1157         }
1158
1159         //
1160         // Since we're not supporting paging yet for CMIS queries, we need to perform
1161         // a workaround for the paging information we return in our list of results
1162         //
1163         /*
1164          if (result != null) {
1165          docFilter.setStartPage(0);
1166          if (totalSize > docFilter.getPageSize()) {
1167          docFilter.setPageSize(totalSize);
1168          ((DocumentModelListImpl)result).setTotalSize(totalSize);
1169          }
1170          }
1171          */
1172
1173         return result;
1174     }
1175
1176     private String logException(Exception e, String msg) {
1177         String result = null;
1178
1179         String exceptionMessage = e.getMessage();
1180         exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1181         result = msg = msg + ". Caught exception:" + exceptionMessage;
1182
1183         if (logger.isTraceEnabled() == true) {
1184             logger.error(msg, e);
1185         } else {
1186             logger.error(msg);
1187         }
1188
1189         return result;
1190     }
1191
1192     /**
1193      * update given document in the Nuxeo repository
1194      *
1195      * @param ctx service context under which this method is invoked
1196      * @param csid of the document
1197      * @param handler should be used by the caller to provide and transform the
1198      * document
1199      * @throws BadRequestException
1200      * @throws DocumentNotFoundException
1201      * @throws TransactionException if the transaction times out or otherwise
1202      * cannot be successfully completed
1203      * @throws DocumentException
1204      */
1205     @Override
1206     public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1207             throws BadRequestException, DocumentNotFoundException, TransactionException,
1208             DocumentException {
1209         if (handler == null) {
1210             throw new IllegalArgumentException(
1211                     "RepositoryJavaClient.update: document handler is missing.");
1212         }
1213
1214         RepositoryInstance repoSession = null;
1215         try {
1216             handler.prepare(Action.UPDATE);
1217             repoSession = getRepositorySession(ctx);
1218             DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1219             DocumentModel doc = null;
1220             try {
1221                 doc = repoSession.getDocument(docRef);
1222             } catch (ClientException ce) {
1223                 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1224                 throw new DocumentNotFoundException(msg, ce);
1225             }
1226             // Check for a versioned document, and check In and Out before we proceed.
1227             if (((DocumentModelHandler) handler).supportsVersioning()) {
1228                 /* Once we advance to 5.5 or later, we can add this. 
1229                  * See also https://jira.nuxeo.com/browse/NXP-8506
1230                  if(!doc.isVersionable()) {
1231                  throw new DocumentException("Configuration for: "
1232                  +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1233                  }
1234                  */
1235                 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1236                  if(doc.getProperty("uid","major_version") == null) {
1237                  doc.setProperty("uid","major_version",1);
1238                  }
1239                  if(doc.getProperty("uid","minor_version") == null) {
1240                  doc.setProperty("uid","minor_version",0);
1241                  }
1242                  */
1243                 doc.checkIn(VersioningOption.MINOR, null);
1244                 doc.checkOut();
1245             }
1246
1247             //
1248             // Set reposession to handle the document
1249             //
1250             ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1251             DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1252             handler.handle(Action.UPDATE, wrapDoc);
1253             repoSession.saveDocument(doc);
1254             repoSession.save();
1255             handler.complete(Action.UPDATE, wrapDoc);
1256         } catch (BadRequestException bre) {
1257             throw bre;
1258         } catch (DocumentException de) {
1259             throw de;
1260         } catch (WebApplicationException wae) {
1261             throw wae;
1262         } catch (Exception e) {
1263             if (logger.isDebugEnabled()) {
1264                 logger.debug("Caught exception ", e);
1265             }
1266             throw new DocumentException(e);
1267         } finally {
1268             if (repoSession != null) {
1269                 releaseRepositorySession(ctx, repoSession);
1270             }
1271         }
1272     }
1273
1274     /**
1275      * Save a documentModel to the Nuxeo repository.
1276      *
1277      * @param ctx service context under which this method is invoked
1278      * @param repoSession
1279      * @param docModel the document to save
1280      * @param fSaveSession if TRUE, will call CoreSession.save() to save
1281      * accumulated changes.
1282      * @throws ClientException
1283      * @throws DocumentException
1284      */
1285     public void saveDocWithoutHandlerProcessing(
1286             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1287             RepositoryInstance repoSession,
1288             DocumentModel docModel,
1289             boolean fSaveSession)
1290             throws ClientException, DocumentException {
1291
1292         try {
1293             repoSession.saveDocument(docModel);
1294             if (fSaveSession) {
1295                 repoSession.save();
1296             }
1297         } catch (ClientException ce) {
1298             throw ce;
1299         } catch (Exception e) {
1300             if (logger.isDebugEnabled()) {
1301                 logger.debug("Caught exception ", e);
1302             }
1303             throw new DocumentException(e);
1304         }
1305     }
1306
1307     /**
1308      * Save a list of documentModels to the Nuxeo repository.
1309      *
1310      * @param ctx service context under which this method is invoked
1311      * @param repoSession a repository session
1312      * @param docModelList a list of document models
1313      * @param fSaveSession if TRUE, will call CoreSession.save() to save
1314      * accumulated changes.
1315      * @throws ClientException
1316      * @throws DocumentException
1317      */
1318     public void saveDocListWithoutHandlerProcessing(
1319             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1320             RepositoryInstance repoSession,
1321             DocumentModelList docList,
1322             boolean fSaveSession)
1323             throws ClientException, DocumentException {
1324         try {
1325             DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1326             repoSession.saveDocuments(docList.toArray(docModelArray));
1327             if (fSaveSession) {
1328                 repoSession.save();
1329             }
1330         } catch (ClientException ce) {
1331             throw ce;
1332         } catch (Exception e) {
1333             logger.error("Caught exception ", e);
1334             throw new DocumentException(e);
1335         }
1336     }
1337
1338     /**
1339      * delete a document from the Nuxeo repository
1340      *
1341      * @param ctx service context under which this method is invoked
1342      * @param id of the document
1343      * @throws DocumentException
1344      */
1345     @Override
1346     public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1347             DocumentException, TransactionException {
1348         if (ctx == null) {
1349             throw new IllegalArgumentException(
1350                     "delete(ctx, ix, handler): ctx is missing");
1351         }
1352         if (handler == null) {
1353             throw new IllegalArgumentException(
1354                     "delete(ctx, ix, handler): handler is missing");
1355         }
1356         if (logger.isDebugEnabled()) {
1357             logger.debug("Deleting document with CSID=" + id);
1358         }
1359         RepositoryInstance repoSession = null;
1360         try {
1361             handler.prepare(Action.DELETE);
1362             repoSession = getRepositorySession(ctx);
1363             DocumentWrapper<DocumentModel> wrapDoc = null;
1364             try {
1365                 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1366                 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1367                 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1368                 handler.handle(Action.DELETE, wrapDoc);
1369                 repoSession.removeDocument(docRef);
1370             } catch (ClientException ce) {
1371                 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1372                 throw new DocumentNotFoundException(msg, ce);
1373             }
1374             repoSession.save();
1375             handler.complete(Action.DELETE, wrapDoc);
1376         } catch (DocumentException de) {
1377             throw de;
1378         } catch (Exception e) {
1379             if (logger.isDebugEnabled()) {
1380                 logger.debug("Caught exception ", e);
1381             }
1382             throw new DocumentException(e);
1383         } finally {
1384             if (repoSession != null) {
1385                 releaseRepositorySession(ctx, repoSession);
1386             }
1387         }
1388     }
1389
1390     /* (non-Javadoc)
1391      * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1392      */
1393     @Override
1394     @Deprecated
1395     public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1396             throws DocumentNotFoundException, DocumentException {
1397         throw new UnsupportedOperationException();
1398         // Use the other delete instead
1399     }
1400
1401     @Override
1402     public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1403         return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1404     }
1405
1406     @Override
1407     public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1408         RepositoryInstance repoSession = null;
1409         String domainId = null;
1410         try {
1411             //
1412             // Open a connection to the domain's repo/db
1413             //
1414             String repoName = repositoryDomain.getRepositoryName();
1415             repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1416             //
1417             // First create the top-level domain directory
1418             //
1419             String domainName = repositoryDomain.getStorageName();
1420             DocumentRef parentDocRef = new PathRef("/");
1421             DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1422             DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1423                     domainName, NUXEO_CORE_TYPE_DOMAIN);
1424             domainDoc.setPropertyValue("dc:title", domainName);
1425             domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1426                     + domainName);
1427             domainDoc = repoSession.createDocument(domainDoc);
1428             domainId = domainDoc.getId();
1429             repoSession.save();
1430             //
1431             // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1432             //
1433             DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1434                     NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1435             workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1436             workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1437                     + domainDoc.getPathAsString());
1438             workspacesRoot = repoSession.createDocument(workspacesRoot);
1439             String workspacesRootId = workspacesRoot.getId();
1440             repoSession.save();
1441
1442             if (logger.isDebugEnabled()) {
1443                 logger.debug("Created tenant domain name=" + domainName
1444                         + " id=" + domainId + " "
1445                         + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1446                 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1447                 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1448             }
1449         } catch (Exception e) {
1450             if (logger.isDebugEnabled()) {
1451                 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1452             }
1453             throw e;
1454         } finally {
1455             if (repoSession != null) {
1456                 releaseRepositorySession(null, repoSession);
1457             }
1458         }
1459
1460         return domainId;
1461     }
1462
1463     @Override
1464     public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1465         String domainId = null;
1466         RepositoryInstance repoSession = null;
1467
1468         String repoName = repositoryDomain.getRepositoryName();
1469         String domainStorageName = repositoryDomain.getStorageName();
1470         if (domainStorageName != null && !domainStorageName.isEmpty()) {
1471             try {
1472                 repoSession = getRepositorySession(repoName);
1473                 DocumentRef docRef = new PathRef("/" + domainStorageName);
1474                 DocumentModel domain = repoSession.getDocument(docRef);
1475                 domainId = domain.getId();
1476             } catch (Exception e) {
1477                 if (logger.isTraceEnabled()) {
1478                     logger.trace("Caught exception ", e);  // The document doesn't exist, this let's us know we need to create it
1479                 }
1480                 //there is no way to identify if document does not exist due to
1481                 //lack of typed exception for getDocument method
1482                 return null;
1483             } finally {
1484                 if (repoSession != null) {
1485                     releaseRepositorySession(null, repoSession);
1486                 }
1487             }
1488         }
1489
1490         return domainId;
1491     }
1492
1493     /*
1494      * Returns the workspaces root directory for a given domain.
1495      */
1496     private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1497             String domainName) throws Exception {
1498         DocumentModel result = null;
1499
1500         String domainPath = "/" + domainName;
1501         DocumentRef parentDocRef = new PathRef(domainPath);
1502         DocumentModelList domainChildrenList = repoSession.getChildren(
1503                 parentDocRef);
1504         Iterator<DocumentModel> witer = domainChildrenList.iterator();
1505         while (witer.hasNext()) {
1506             DocumentModel childNode = witer.next();
1507             if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1508                 result = childNode;
1509                 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1510                 break;
1511             }
1512         }
1513
1514         if (result == null) {
1515             throw new ClientException("Could not find workspace root directory in: "
1516                     + domainPath);
1517         }
1518
1519         return result;
1520     }
1521
1522     /* (non-Javadoc)
1523      * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1524      */
1525     @Override
1526     public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1527         RepositoryInstance repoSession = null;
1528         String workspaceId = null;
1529         try {
1530             String repoName = repositoryDomain.getRepositoryName();
1531             repoSession = getRepositorySession(repoName);
1532
1533             String domainStorageName = repositoryDomain.getStorageName();
1534             DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1535             if (logger.isTraceEnabled()) {
1536                 for (String facet : parentDoc.getFacets()) {
1537                     logger.trace("Facet: " + facet);
1538                 }
1539             }
1540
1541             DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1542                     workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1543             doc.setPropertyValue("dc:title", workspaceName);
1544             doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1545                     + workspaceName);
1546             doc = repoSession.createDocument(doc);
1547             workspaceId = doc.getId();
1548             repoSession.save();
1549             if (logger.isDebugEnabled()) {
1550                 logger.debug("Created workspace name=" + workspaceName
1551                         + " id=" + workspaceId);
1552             }
1553         } catch (Exception e) {
1554             if (logger.isDebugEnabled()) {
1555                 logger.debug("createWorkspace caught exception ", e);
1556             }
1557             throw e;
1558         } finally {
1559             if (repoSession != null) {
1560                 releaseRepositorySession(null, repoSession);
1561             }
1562         }
1563         return workspaceId;
1564     }
1565
1566     /* (non-Javadoc)
1567      * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1568      */
1569     @Override
1570     @Deprecated
1571     public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1572         String workspaceId = null;
1573
1574         RepositoryInstance repoSession = null;
1575         try {
1576             repoSession = getRepositorySession((ServiceContext) null);
1577             DocumentRef docRef = new PathRef(
1578                     "/" + tenantDomain
1579                     + "/" + NuxeoUtils.Workspaces
1580                     + "/" + workspaceName);
1581             DocumentModel workspace = repoSession.getDocument(docRef);
1582             workspaceId = workspace.getId();
1583         } catch (DocumentException de) {
1584             throw de;
1585         } catch (Exception e) {
1586             if (logger.isDebugEnabled()) {
1587                 logger.debug("Caught exception ", e);
1588             }
1589             throw new DocumentException(e);
1590         } finally {
1591             if (repoSession != null) {
1592                 releaseRepositorySession(null, repoSession);
1593             }
1594         }
1595
1596         return workspaceId;
1597     }
1598
1599     public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1600         return getRepositorySession(ctx, ctx.getRepositoryName());
1601     }
1602
1603     public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1604         return getRepositorySession(null, repoName);
1605     }
1606
1607     /**
1608      * Gets the repository session. - Package access only. If the 'ctx' param is
1609      * null then the repo name must be non-mull and vice-versa
1610      *
1611      * @return the repository session
1612      * @throws Exception the exception
1613      */
1614     public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1615         RepositoryInstance repoSession = null;
1616
1617         Profiler profiler = new Profiler("getRepositorySession():", 2);
1618         profiler.start();
1619         //
1620         // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1621         //
1622         if (ctx != null) {
1623             repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1624             repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1625         } else if (repoName == null || repoName.trim().isEmpty()) {
1626             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.");
1627             logger.error(errMsg);
1628             throw new Exception(errMsg);
1629         }
1630         //
1631         // 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
1632         // just the repo name
1633         //
1634         if (repoSession == null) {
1635             NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1636             repoSession = client.openRepository(repoName);
1637         } else {
1638             if (logger.isDebugEnabled() == true) {
1639                 logger.warn("Reusing the current context's repository session.");
1640             }
1641         }
1642
1643         if (logger.isTraceEnabled()) {
1644             logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1645         }
1646
1647         profiler.stop();
1648
1649         if (ctx != null) {
1650             ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1651         }
1652
1653         return repoSession;
1654     }
1655
1656     /**
1657      * Release repository session. - Package access only.
1658      *
1659      * @param repoSession the repo session
1660      */
1661     public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1662         try {
1663             NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1664             // release session
1665             if (ctx != null) {
1666                 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1667                 if (ctx.getCurrentRepositorySession() == null) {
1668                     client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1669                 }
1670             } else {
1671                 client.releaseRepository(repoSession); //repo session was acquired without a service context
1672             }
1673         } catch (TransactionRuntimeException tre) {
1674             TransactionException te = new TransactionException(tre);
1675             logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1676             throw te;
1677         } catch (Exception e) {
1678             logger.error("Could not close the repository session", e);
1679             // no need to throw this service specific exception
1680         }
1681     }
1682
1683     @Override
1684     public void doWorkflowTransition(ServiceContext ctx, String id,
1685             DocumentHandler handler, TransitionDef transitionDef)
1686             throws BadRequestException, DocumentNotFoundException,
1687             DocumentException {
1688         // 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
1689     }
1690
1691     private String handleProvidedStartingWildcard(String partialTerm) {
1692         if (Tools.notBlank(partialTerm)) {
1693             // FIXME: Get this value from an existing constant, if available
1694             final String USER_SUPPLIED_WILDCARD = "*";
1695             if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1696                 StringBuffer buffer = new StringBuffer(partialTerm);
1697                 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1698                 partialTerm = buffer.toString();
1699             }
1700         }
1701         return partialTerm;
1702     }
1703
1704     private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
1705         final int DEFAULT_ITEMS_LIMIT = 40;
1706         int itemsLimit;
1707         try {
1708             itemsLimit = Integer.parseInt(maxListItemsLimit);
1709             if (itemsLimit < 1) {
1710                 logger.warn("Value of configuration setting "
1711                         + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1712                         + " must be a positive integer; current value is " + maxListItemsLimit);
1713                 itemsLimit = DEFAULT_ITEMS_LIMIT;
1714             }
1715         } catch (NumberFormatException nfe) {
1716             logger.warn("Value of configuration setting "
1717                         + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1718                         + " must be a positive integer; current value is " + maxListItemsLimit);
1719             itemsLimit = DEFAULT_ITEMS_LIMIT;
1720         }
1721         return itemsLimit;
1722     }
1723
1724     /**
1725      * Identifies whether a restriction on tenant ID - to return only records
1726      * pertaining to the current tenant - is required in a JDBC query.
1727      * 
1728      * @param tenantBinding a tenant binding configuration.
1729      * @param ctx a service context.
1730      * @return true if a restriction on tenant ID is required in the query;
1731      * false if a restriction is not required.
1732      */
1733     private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext ctx) {
1734         boolean restrict = true;
1735         // If data for the current service, in the current tenant, is isolated
1736         // within its own separate, per-tenant repository, as contrasted with
1737         // being intermingled with other tenants' data in the default repository,
1738         // no restriction on Tenant ID is required in the query.
1739         String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
1740         if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
1741             restrict = false;
1742         }
1743         // If a configuration setting for this tenant identifies that JDBC
1744         // queries should not be restricted by tenant ID (perhaps because
1745         // there is always expected to be only one tenant's data present in
1746         // the system), no restriction on Tenant ID is required in the query.
1747         String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
1748                 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
1749         if (Tools.notBlank(queriesRestrictedByTenantId) &&
1750                 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {
1751             restrict = false;
1752         }
1753         return restrict;
1754     }
1755 }