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