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