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