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