]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
3f87b3e9ccc5386de74e679cbc0044ed3e323c90
[tmp/jakarta-migration.git] /
1 /**
2  *  This document is a part of the source code and related artifacts
3  *  for CollectionSpace, an open source collections management system
4  *  for museums and related institutions:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
18  *  Unless required by applicable law or agreed to in writing, software
19  *  distributed under the License is distributed on an "AS IS" BASIS,
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  *  See the License for the specific language governing permissions and
22  *  limitations under the License.
23  */
24 package org.collectionspace.services.nuxeo.client.java;
25
26 import java.util.Collection;
27 import java.util.List;
28
29 import javax.ws.rs.core.MultivaluedMap;
30
31 import org.apache.commons.lang.StringUtils;
32 import org.collectionspace.services.client.Profiler;
33 import org.collectionspace.services.client.CollectionSpaceClient;
34 import org.collectionspace.services.client.IClientQueryParams;
35 import org.collectionspace.services.client.IQueryManager;
36 import org.collectionspace.services.client.IRelationsManager;
37 import org.collectionspace.services.client.PoxPayloadIn;
38 import org.collectionspace.services.client.PoxPayloadOut;
39 import org.collectionspace.services.common.api.CommonAPI;
40 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
41 import org.collectionspace.services.common.api.RefName;
42 import org.collectionspace.services.common.api.RefName.RefNameInterface;
43 import org.collectionspace.services.common.api.RefNameUtils;
44 import org.collectionspace.services.common.api.Tools;
45 import org.collectionspace.services.common.authorityref.AuthorityRefList;
46 import org.collectionspace.services.common.context.ServiceContext;
47 import org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl;
48 import org.collectionspace.services.common.document.DocumentException;
49 import org.collectionspace.services.common.document.DocumentFilter;
50 import org.collectionspace.services.common.document.DocumentNotFoundException;
51 import org.collectionspace.services.common.document.DocumentWrapper;
52 import org.collectionspace.services.common.document.DocumentWrapperImpl;
53 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
54 import org.collectionspace.services.common.query.QueryContext;
55 import org.collectionspace.services.common.repository.RepositoryClient;
56 import org.collectionspace.services.common.repository.RepositoryClientFactory;
57 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthRefConfigInfo;
58 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
59 import org.collectionspace.services.lifecycle.Lifecycle;
60 import org.collectionspace.services.lifecycle.State;
61 import org.collectionspace.services.lifecycle.StateList;
62 import org.collectionspace.services.lifecycle.TransitionDef;
63 import org.collectionspace.services.lifecycle.TransitionDefList;
64 import org.collectionspace.services.lifecycle.TransitionList;
65 import org.nuxeo.ecm.core.NXCore;
66 import org.nuxeo.ecm.core.api.ClientException;
67 import org.nuxeo.ecm.core.api.DocumentModel;
68 import org.nuxeo.ecm.core.api.DocumentModelList;
69 import org.nuxeo.ecm.core.api.model.PropertyException;
70 import org.nuxeo.ecm.core.lifecycle.LifeCycle;
71 import org.nuxeo.ecm.core.lifecycle.LifeCycleService;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 /**
76  * DocumentModelHandler is a base abstract Nuxeo document handler
77  * using Nuxeo Java Remote APIs for CollectionSpace services
78  *
79  * $LastChangedRevision: $
80  * $LastChangedDate: $
81  */
82 public abstract class DocumentModelHandler<T, TL>
83         extends AbstractMultipartDocumentHandlerImpl<T, TL, DocumentModel, DocumentModelList> {
84
85     private final Logger logger = LoggerFactory.getLogger(DocumentModelHandler.class);
86     private CoreSessionInterface repositorySession;
87
88     protected String oldRefNameOnUpdate = null;  // FIXME: REM - We should have setters and getters for these
89     protected String newRefNameOnUpdate = null;  // FIXME: two fields.
90     
91     
92     /*
93      * Returns the the life cycle definition of the related Nuxeo document type for this handler.
94      * (non-Javadoc)
95      * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle()
96      */
97     @Override
98     public Lifecycle getLifecycle() {
99         Lifecycle result = null;
100         
101         String docTypeName = null;
102         try {
103                 docTypeName = this.getServiceContext().getDocumentType();
104                 result = getLifecycle(docTypeName);
105         } catch (Exception e) {
106                 if (logger.isTraceEnabled() == true) {
107                         logger.trace("Could not retrieve lifecycle definition for Nuxeo doctype: " + docTypeName);
108                 }
109         }
110         
111         return result;
112     }
113     
114     /*
115      * Returns the the life cycle definition of the related Nuxeo document type for this handler.
116      * (non-Javadoc)
117      * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle(java.lang.String)
118      */
119     @Override
120     public Lifecycle getLifecycle(String docTypeName) {         
121         return NuxeoUtils.getLifecycle(docTypeName);
122     }
123     
124     /*
125      * We're using the "name" field of Nuxeo's DocumentModel to store
126      * the CSID.
127      */
128     public String getCsid(DocumentModel docModel) {
129         return NuxeoUtils.getCsid(docModel);
130     }
131
132     public String getUri(DocumentModel docModel) {
133         return getServiceContextPath()+getCsid(docModel);
134     }
135     
136     public String getUri(Specifier specifier) {
137         return getServiceContextPath() + specifier.value;
138     }
139     
140         
141     public RepositoryClient<PoxPayloadIn, PoxPayloadOut> getRepositoryClient(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
142         RepositoryClient<PoxPayloadIn, PoxPayloadOut> repositoryClient = 
143                         (RepositoryClient<PoxPayloadIn, PoxPayloadOut>) RepositoryClientFactory.getInstance().getClient(ctx.getRepositoryClientName());
144         return repositoryClient;
145     }
146
147     /**
148      * getRepositorySession returns Nuxeo Repository Session
149      * @return
150      */
151     public CoreSessionInterface getRepositorySession() {
152         
153         return repositorySession;
154     }
155
156     /**
157      * setRepositorySession sets repository session
158      * @param repoSession
159      */
160     public void setRepositorySession(CoreSessionInterface repoSession) {
161         this.repositorySession = repoSession;
162     }
163
164     @Override
165     public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
166         // TODO for sub-docs - check to see if the current service context is a multipart input, 
167         // OR a docfragment, and call a variant to fill the DocModel.
168         fillAllParts(wrapDoc, Action.CREATE);
169         handleCoreValues(wrapDoc, Action.CREATE);
170     }
171     
172     // TODO for sub-docs - Add completeCreate in which we look for set-aside doc fragments 
173     // and create the subitems. We will create service contexts with the doc fragments
174     // and then call 
175
176
177     @Override
178     public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
179         // TODO for sub-docs - check to see if the current service context is a multipart input, 
180         // OR a docfragment, and call a variant to fill the DocModel.
181         fillAllParts(wrapDoc, Action.UPDATE);
182         handleCoreValues(wrapDoc, Action.UPDATE);
183     }
184
185     @Override
186     public void handleGet(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
187                 extractAllParts(wrapDoc);
188     }
189
190     @Override
191     public void handleGetAll(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception {
192         Profiler profiler = new Profiler(this, 2);
193         profiler.start();
194         setCommonPartList(extractCommonPartList(wrapDoc));
195         profiler.stop();
196     }
197
198     @Override
199     public abstract void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
200
201     @Override
202     public abstract void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
203
204     @Override
205     public abstract T extractCommonPart(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
206
207     @Override
208     public abstract void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception;
209
210     @Override
211     public abstract void fillCommonPart(T obj, DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
212
213     @Override
214     public abstract TL extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception;
215
216     @Override
217     public abstract T getCommonPart();
218
219     @Override
220     public abstract void setCommonPart(T obj);
221
222     @Override
223     public abstract TL getCommonPartList();
224
225     @Override
226     public abstract void setCommonPartList(TL obj);
227     
228     @Override
229     public DocumentFilter createDocumentFilter() {
230         DocumentFilter filter = new NuxeoDocumentFilter(this.getServiceContext());
231         return filter;
232     }
233     
234     /**
235      * Gets the authority refs.
236      *
237      * @param docWrapper the doc wrapper
238      * @param authRefFields the auth ref fields
239      * @return the authority refs
240      * @throws PropertyException the property exception
241      */
242     abstract public AuthorityRefList getAuthorityRefs(String csid,
243                 List<AuthRefConfigInfo> authRefConfigInfoList) throws PropertyException, Exception;    
244
245     /*
246      * Subclasses should override this method if they need to customize their refname generation
247      */
248     protected RefName.RefNameInterface getRefName(ServiceContext ctx,
249                 DocumentModel docModel) {
250         return getRefName(new DocumentWrapperImpl<DocumentModel>(docModel), ctx.getTenantName(), ctx.getServiceName());
251     }
252     
253     /*
254      * By default, we'll use the CSID as the short ID.  Sub-classes can override this method if they want to use
255      * something else for a short ID.
256      * 
257      * (non-Javadoc)
258      * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#getRefName(org.collectionspace.services.common.document.DocumentWrapper, java.lang.String, java.lang.String)
259      */
260     @Override
261         protected RefName.RefNameInterface getRefName(DocumentWrapper<DocumentModel> docWrapper,
262                         String tenantName, String serviceName) {
263         String csid = docWrapper.getWrappedObject().getName();
264         String refnameDisplayName = getRefnameDisplayName(docWrapper);
265         RefName.RefNameInterface refname = RefName.Authority.buildAuthority(tenantName, serviceName,
266                         csid, null, refnameDisplayName);
267         return refname;
268         }
269
270     private void handleCoreValues(DocumentWrapper<DocumentModel> docWrapper, 
271                 Action action)  throws ClientException {
272         DocumentModel documentModel = docWrapper.getWrappedObject();
273         String now = GregorianCalendarDateTimeUtils.timestampUTC();
274         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
275         String userId = ctx.getUserId();
276         if (action == Action.CREATE) {
277             //
278             // Add the tenant ID value to the new entity
279             //
280                 String tenantId = ctx.getTenantId();
281             documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
282                         CollectionSpaceClient.COLLECTIONSPACE_CORE_TENANTID, tenantId);
283             //
284             // Add the uri value to the new entity
285             //
286             documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
287                         CollectionSpaceClient.COLLECTIONSPACE_CORE_URI, getUri(documentModel));
288                 //
289                 // Add the CSID to the DublinCore title so we can see the CSID in the default
290                 // Nuxeo webapp.
291                 //
292                 try {
293                 documentModel.setProperty(CommonAPI.NUXEO_DUBLINCORE_SCHEMANAME, CommonAPI.NUXEO_DUBLINCORE_TITLE,
294                         documentModel.getName());
295                 } catch (Exception x) {
296                         if (logger.isWarnEnabled() == true) {
297                                 logger.warn("Could not set the Dublin Core 'title' field on document CSID:" +
298                                                 documentModel.getName());
299                         }
300                 }
301                 //
302                 // Add createdAt timestamp and createdBy user
303                 //
304             documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
305                         CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_AT, now);
306             documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
307                         CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_BY, userId);
308         }
309         
310                 if (action == Action.CREATE || action == Action.UPDATE) {
311             //
312             // Add/update the resource's refname
313             //
314                         handleRefNameChanges(ctx, documentModel);
315             //
316             // Add updatedAt timestamp and updateBy user
317             //
318                         if (ctx.shouldUpdateCoreValues() == true) { // Ensure that our caller wants us to record this update
319                                 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
320                                                 CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT, now);
321                                 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
322                                                 CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_BY, userId);
323                         } else {
324                                 logger.debug(String.format("Document with CSID=%s updated %s by user %s", documentModel.getName(), now, userId));
325                         }
326                 }               
327     }
328     
329     protected boolean hasRefNameUpdate() {
330         boolean result = false;
331         
332         //
333         // Check to see if the request contains a query parameter asking us to force a refname update
334         //
335         if (getServiceContext().shouldForceUpdateRefnameReferences() == true) {
336                 return true;
337         }
338         
339         if (Tools.notBlank(newRefNameOnUpdate) && Tools.notBlank(oldRefNameOnUpdate)) {
340                 // CSPACE-6372: refNames are different if:
341                 //   - any part of the refName is different, using a case insensitive comparison, or
342                 //   - the display name portions are different, using a case sensitive comparison
343                 if (newRefNameOnUpdate.equalsIgnoreCase(oldRefNameOnUpdate) == false) {
344                         result = true; // refNames are different so updates are needed
345                 }
346                 else {
347                         String newDisplayNameOnUpdate = RefNameUtils.getDisplayName(newRefNameOnUpdate);
348                         String oldDisplayNameOnUpdate = RefNameUtils.getDisplayName(oldRefNameOnUpdate);
349                         
350                         if (StringUtils.equals(newDisplayNameOnUpdate, oldDisplayNameOnUpdate) == false) {
351                                 result = true; // display names are different so updates are needed
352                         }
353                 }
354         }
355         
356         return result;
357     }
358     
359     protected void handleRefNameChanges(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentModel docModel) throws ClientException {
360         // First get the old refName
361         this.oldRefNameOnUpdate = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
362                         CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME);
363         // Next, get the new refName
364         RefNameInterface refName = getRefName(ctx, docModel); // Sub-classes may override the getRefName() method called here.
365         if (refName != null) {
366                 this.newRefNameOnUpdate = refName.toString();
367         } else {
368                 logger.error(String.format("The refName for document is missing.  Document CSID=%s", docModel.getName())); // FIXME: REM - We should probably be throwing an exception here?
369         }
370         //
371         // Set the refName if it is an update or if the old refName was empty or null
372         //
373         if (hasRefNameUpdate() == true || this.oldRefNameOnUpdate == null) {
374                 docModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
375                                 CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME, this.newRefNameOnUpdate);
376         }
377     }
378         
379     /*
380      * If we see the "rtSbj" query param then we need to perform a CMIS query.  Currently, we have only one
381      * CMIS query, but we could add more.  If we do, this method should look at the incoming request and corresponding
382      * query params to determine if we need to do a CMIS query
383      * (non-Javadoc)
384      * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#isCMISQuery()
385      */
386     public boolean isCMISQuery() {
387         boolean result = false;
388         
389         MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
390         //
391         // Look the query params to see if we need to make a CMSIS query.
392         //
393         String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);           
394         String asOjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);      
395         String asEither = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);         
396         if (asSubjectCsid != null || asOjectCsid != null || asEither != null) {
397                 result = true;
398         }
399         
400         return result;
401     }
402     
403     @Override
404     public String getDocumentsToIndexQuery(String indexId, String csid) throws DocumentException, Exception {
405         String result = null;
406         
407         ServiceContext<PoxPayloadIn,PoxPayloadOut> ctx = this.getServiceContext();
408         String selectClause = "SELECT ecm:uuid, ecm:primaryType FROM ";
409         String docFilterWhereClause = this.getDocumentFilter().getWhereClause();
410         //
411         // The where clause could be a combination of the document filter's where clause plus a CSID qualifier
412         //
413         String whereClause = (csid == null) ? null : String.format("ecm:name = '%s'", csid); // AND ecm:currentLifeCycleState <> 'deleted'"
414         if (whereClause != null && !whereClause.trim().isEmpty()) {
415             // Due to an apparent bug/issue in how Nuxeo translates the NXQL query string
416             // into SQL, we need to parenthesize our 'where' clause
417                 if (docFilterWhereClause != null && !docFilterWhereClause.trim().isEmpty()) {
418                         whereClause = whereClause + IQueryManager.SEARCH_QUALIFIER_AND + "(" + docFilterWhereClause + ")";
419                 }
420         } else {
421                 whereClause = docFilterWhereClause;
422         }
423         String orderByClause = "ecm:uuid";
424         
425         try {
426                 QueryContext queryContext = new QueryContext(ctx, selectClause, whereClause, orderByClause);
427                 result = NuxeoUtils.buildNXQLQuery(queryContext);
428         } catch (DocumentException de) {
429                 throw de;
430         } catch (Exception x) {
431                 throw x;
432         }
433
434         return result;
435     }
436     
437         /**
438          * Creates the CMIS query from the service context. Each document handler is
439          * responsible for returning (can override) a valid CMIS query using the information in the
440          * current service context -which includes things like the query parameters,
441          * etc.
442          * 
443          * This method implementation supports three mutually exclusive cases. We will build a query
444          * that can find a document(s) 'A' in a relationship with another document
445          * 'B' where document 'B' has a CSID equal to the query param passed in and:
446          *              1. Document 'B' is the subject of the relationship
447          *              2. Document 'B' is the object of the relationship
448          *              3. Document 'B' is either the object or the subject of the relationship
449          * @throws DocumentException 
450          */
451     @Override
452     public String getCMISQuery(QueryContext queryContext) throws DocumentException {
453         String result = null;
454         
455         if (isCMISQuery() == true) {
456                 //
457                 // Build up the query arguments
458                 //
459                 String theOnClause = "";
460                 String theWhereClause = "";
461                 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
462                 String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
463                 String asObjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
464                 
465                 String matchObjDocTypes = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES);
466                 String selectDocType = (String)queryParams.getFirst(IQueryManager.SELECT_DOC_TYPE_FIELD);
467
468                 String docType = NuxeoUtils.getTenantQualifiedDocType(this.getServiceContext()); // Fixed for https://issues.collectionspace.org/browse/DRYD-302
469                 if (selectDocType != null && !selectDocType.isEmpty()) {
470                         docType = selectDocType;
471                 }
472                 String selectFields = IQueryManager.CMIS_TARGET_CSID + ", "
473                                 + IQueryManager.CMIS_TARGET_TITLE + ", "
474                                 + IRelationsManager.CMIS_CSPACE_RELATIONS_TITLE + ", "
475                                 + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID + ", "
476                                 + IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
477
478                 String targetTable = docType + " " + IQueryManager.CMIS_TARGET_PREFIX;
479                 String relTable = IRelationsManager.DOC_TYPE + " " + IQueryManager.CMIS_RELATIONS_PREFIX;
480                 
481                 String relSubjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
482                 String relObjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID;
483                 
484                 String targetCsidCol = IQueryManager.CMIS_TARGET_CSID;
485                 String tenantID = this.getServiceContext().getTenantId();
486
487                 //
488                 // Create the "ON" and "WHERE" query clauses based on the params passed into the HTTP request.  
489                 //
490                 // First come, first serve -the first match determines the "ON" and "WHERE" query clauses.
491                 //
492                 if (asSubjectCsid != null && !asSubjectCsid.isEmpty()) {  
493                         // Since our query param is the "subject" value, join the tables where the CSID of the document is the other side (the "object") of the relationship.
494                         theOnClause = relObjectCsidCol + " = " + targetCsidCol;
495                         theWhereClause = relSubjectCsidCol + " = " + "'" + asSubjectCsid + "'";
496                 } else if (asObjectCsid != null && !asObjectCsid.isEmpty()) {
497                         // Since our query param is the "object" value, join the tables where the CSID of the document is the other side (the "subject") of the relationship.
498                         theOnClause = relSubjectCsidCol + " = " + targetCsidCol; 
499                         theWhereClause = relObjectCsidCol + " = " + "'" + asObjectCsid + "'";
500                 } else {
501                         //Since the call to isCMISQuery() return true, we should never get here.
502                         logger.error("Attempt to make CMIS query failed because the HTTP request was missing valid query parameters.");
503                 }
504                 
505                 // Now consider a constraint on the object doc types (for search by service group)
506                 if (matchObjDocTypes != null && !matchObjDocTypes.isEmpty()) {  
507                         // Since our query param is the "subject" value, join the tables where the CSID of the document is the other side (the "object") of the relationship.
508                         theWhereClause += " AND (" + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_TYPE 
509                                                                 + " IN " + matchObjDocTypes + ")";
510                 }
511                 
512                 // Qualify the search for predicate types
513                 theWhereClause = addWhereClauseForPredicates(theWhereClause, queryParams);
514                 
515                 // Qualify the query with the current tenant ID.
516                 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_TENANT_ID_FILTER + " = '" + tenantID + "'";
517                 
518                 // This could later be in control of a queryParam, to omit if we want to see versions, or to
519                 // only see old versions.
520                 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_NUXEO_IS_VERSION_FILTER;
521                 
522                 StringBuilder query = new StringBuilder();
523                 // assemble the query from the string arguments
524                 query.append("SELECT ");
525                 query.append(selectFields);
526                 query.append(" FROM " + targetTable + " JOIN " + relTable);
527                 query.append(" ON " + theOnClause);
528                 query.append(" WHERE " + theWhereClause);
529                 
530                 try {
531                                 NuxeoUtils.appendCMISOrderBy(query, queryContext);
532                         } catch (Exception e) {
533                                 logger.error("Could not append ORDER BY clause to CMIS query", e);
534                         }
535                 
536                 // An example:
537                 // SELECT D.cmis:name, D.dc:title, R.dc:title, R.relations_common:subjectCsid
538                 // FROM Dimension D JOIN Relation R
539                 // ON R.relations_common:objectCsid = D.cmis:name
540                 // WHERE R.relations_common:subjectCsid = '737527ec-a560-4776-99de'
541                 // ORDER BY D.collectionspace_core:updatedAt DESC
542                 
543                 result = query.toString();
544                 if (logger.isDebugEnabled() == true && result != null) {
545                         logger.debug("The CMIS query is: " + result);
546                 }
547         }
548         
549         return result;
550     }
551
552         private String addWhereClauseForPredicates(String theWhereClause, MultivaluedMap<String, String> queryParams) {
553                 if (queryParams.containsKey(IQueryManager.SEARCH_RELATED_PREDICATE)) {
554                         List<String> predicateList = queryParams.get(IQueryManager.SEARCH_RELATED_PREDICATE);
555                         
556                         if (predicateList.size() == 1) {
557                         String predicate = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_PREDICATE);
558                         if (predicate != null && !predicate.trim().isEmpty()) {
559                                 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IRelationsManager.CMIS_CSPACE_RELATIONS_PREDICATE + " = '" + predicate + "'";
560                         }
561                         } else if (predicateList.size() > 1) {
562                                 StringBuffer partialClause = new StringBuffer();
563                                 for (String predicate : predicateList) {
564                                         if (!predicate.trim().isEmpty()) {
565                                                 partialClause.append("'" + predicate + "', ");
566                                         }
567                                 }
568                                 String inValues = partialClause.toString().replaceAll(", $", ""); // remove the last ', ' squence
569                                 if (!inValues.trim().isEmpty()) {
570                                         theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IRelationsManager.CMIS_CSPACE_RELATIONS_PREDICATE + " IN (" + inValues + ")";
571                                 }
572                         }
573                 }
574                 
575                 return theWhereClause;
576         }
577     
578 }