]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
bd176053e7b94be20e67d42352ee4f46eeab25fd
[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.collectionspace.services.client.Profiler;
32 import org.collectionspace.services.client.CollectionSpaceClient;
33 import org.collectionspace.services.client.IQueryManager;
34 import org.collectionspace.services.client.IRelationsManager;
35 import org.collectionspace.services.client.PoxPayloadIn;
36 import org.collectionspace.services.client.PoxPayloadOut;
37 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
38 import org.collectionspace.services.common.api.RefName;
39 import org.collectionspace.services.common.api.RefName.RefNameInterface;
40 import org.collectionspace.services.common.api.Tools;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
42 import org.collectionspace.services.common.context.ServiceContext;
43 import org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl;
44 import org.collectionspace.services.common.document.DocumentFilter;
45 import org.collectionspace.services.common.document.DocumentWrapper;
46 import org.collectionspace.services.common.document.DocumentWrapperImpl;
47 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
48 import org.collectionspace.services.common.query.QueryContext;
49 import org.collectionspace.services.common.repository.RepositoryClient;
50 import org.collectionspace.services.common.repository.RepositoryClientFactory;
51 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthRefConfigInfo;
52 import org.collectionspace.services.lifecycle.Lifecycle;
53 import org.collectionspace.services.lifecycle.State;
54 import org.collectionspace.services.lifecycle.StateList;
55 import org.collectionspace.services.lifecycle.TransitionDef;
56 import org.collectionspace.services.lifecycle.TransitionDefList;
57 import org.collectionspace.services.lifecycle.TransitionList;
58
59 import org.nuxeo.ecm.core.NXCore;
60 import org.nuxeo.ecm.core.api.ClientException;
61 import org.nuxeo.ecm.core.api.DocumentModel;
62 import org.nuxeo.ecm.core.api.DocumentModelList;
63 import org.nuxeo.ecm.core.api.model.PropertyException;
64 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
65 import org.nuxeo.ecm.core.lifecycle.LifeCycleService;
66
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69
70 /**
71  * DocumentModelHandler is a base abstract Nuxeo document handler
72  * using Nuxeo Java Remote APIs for CollectionSpace services
73  *
74  * $LastChangedRevision: $
75  * $LastChangedDate: $
76  */
77 public abstract class DocumentModelHandler<T, TL>
78         extends AbstractMultipartDocumentHandlerImpl<T, TL, DocumentModel, DocumentModelList> {
79
80     private final Logger logger = LoggerFactory.getLogger(DocumentModelHandler.class);
81     private RepositoryInstance repositorySession;
82
83     protected String oldRefNameOnUpdate = null;  // FIXME: REM - We should have setters and getters for these
84     protected String newRefNameOnUpdate = null;  // FIXME: two fields.
85     
86     /*
87      * Map Nuxeo's life cycle object to our JAX-B based life cycle object
88      */
89     private Lifecycle createCollectionSpaceLifecycle(org.nuxeo.ecm.core.lifecycle.LifeCycle nuxeoLifecyle) {
90         Lifecycle result = null;
91         
92         if (nuxeoLifecyle != null) {
93                 //
94                 // Copy the life cycle's name
95                 result = new Lifecycle();
96                 result.setName(nuxeoLifecyle.getName());
97                 
98                 // We currently support only one initial state, so take the first one from Nuxeo
99                 Collection<String> initialStateNames = nuxeoLifecyle.getInitialStateNames();
100                 result.setDefaultInitial(initialStateNames.iterator().next());
101                 
102                 // Next, we copy the state and corresponding transition lists
103                 StateList stateList = new StateList();
104                 List<State> states = stateList.getState();
105                 Collection<org.nuxeo.ecm.core.lifecycle.LifeCycleState> nuxeoStates = nuxeoLifecyle.getStates();
106                 for (org.nuxeo.ecm.core.lifecycle.LifeCycleState nuxeoState : nuxeoStates) {
107                         State tempState = new State();
108                         tempState.setDescription(nuxeoState.getDescription());
109                         tempState.setInitial(nuxeoState.isInitial());
110                         tempState.setName(nuxeoState.getName());
111                         // Now get the list of transitions
112                         TransitionList transitionList = new TransitionList();
113                         List<String> transitions = transitionList.getTransition();
114                         Collection<String> nuxeoTransitions = nuxeoState.getAllowedStateTransitions();
115                         for (String nuxeoTransition : nuxeoTransitions) {
116                                 transitions.add(nuxeoTransition);
117                         }
118                         tempState.setTransitionList(transitionList);
119                         states.add(tempState);
120                 }
121                 result.setStateList(stateList);
122                 
123                 // Finally, we create the transition definitions
124                 TransitionDefList transitionDefList = new TransitionDefList();
125                 List<TransitionDef> transitionDefs = transitionDefList.getTransitionDef();
126                 Collection<org.nuxeo.ecm.core.lifecycle.LifeCycleTransition> nuxeoTransitionDefs = nuxeoLifecyle.getTransitions();
127                 for (org.nuxeo.ecm.core.lifecycle.LifeCycleTransition nuxeoTransitionDef : nuxeoTransitionDefs) {
128                         TransitionDef tempTransitionDef = new TransitionDef();
129                         tempTransitionDef.setDescription(nuxeoTransitionDef.getDescription());
130                         tempTransitionDef.setDestinationState(nuxeoTransitionDef.getDestinationStateName());
131                         tempTransitionDef.setName(nuxeoTransitionDef.getName());
132                         transitionDefs.add(tempTransitionDef);
133                 }
134                 result.setTransitionDefList(transitionDefList);
135         }
136         
137         return result;
138     }
139     
140     /*
141      * Returns the the life cycle definition of the related Nuxeo document type for this handler.
142      * (non-Javadoc)
143      * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle()
144      */
145     @Override
146     public Lifecycle getLifecycle() {
147         Lifecycle result = null;
148         
149         String docTypeName = null;
150         try {
151                 docTypeName = this.getServiceContext().getDocumentType();
152                 result = getLifecycle(docTypeName);
153         } catch (Exception e) {
154                 if (logger.isTraceEnabled() == true) {
155                         logger.trace("Could not retrieve lifecycle definition for Nuxeo doctype: " + docTypeName);
156                 }
157         }
158         
159         return result;
160     }
161     
162     /*
163      * Returns the the life cycle definition of the related Nuxeo document type for this handler.
164      * (non-Javadoc)
165      * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle(java.lang.String)
166      */
167     @Override
168     public Lifecycle getLifecycle(String docTypeName) {
169         org.nuxeo.ecm.core.lifecycle.LifeCycle nuxeoLifecyle;
170         Lifecycle result = null;
171         
172         try {
173                 LifeCycleService lifeCycleService = null;
174                         try {
175                                 lifeCycleService = NXCore.getLifeCycleService();
176                         } catch (Exception e) {
177                                 e.printStackTrace();
178                         }
179                         
180                 String lifeCycleName; 
181                 lifeCycleName = lifeCycleService.getLifeCycleNameFor(docTypeName);
182                 nuxeoLifecyle = lifeCycleService.getLifeCycleByName(lifeCycleName);
183                 
184                 result = createCollectionSpaceLifecycle(nuxeoLifecyle); 
185 //                      result = (Lifecycle)FileTools.getJaxbObjectFromFile(Lifecycle.class, "default-lifecycle.xml");
186                 } catch (Exception e) {
187                         // TODO Auto-generated catch block
188                         logger.error("Could not retreive life cycle information for Nuxeo doctype: " + docTypeName, e);
189                 }
190         
191         return result;
192     }
193     
194     /*
195      * We're using the "name" field of Nuxeo's DocumentModel to store
196      * the CSID.
197      */
198     public String getCsid(DocumentModel docModel) {
199         return NuxeoUtils.getCsid(docModel);
200     }
201
202     public String getUri(DocumentModel docModel) {
203         return getServiceContextPath()+getCsid(docModel);
204     }
205         
206     public RepositoryClient<PoxPayloadIn, PoxPayloadOut> getRepositoryClient(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
207         RepositoryClient<PoxPayloadIn, PoxPayloadOut> repositoryClient = RepositoryClientFactory.getInstance().getClient(ctx.getRepositoryClientName());
208         return repositoryClient;
209     }
210
211     /**
212      * getRepositorySession returns Nuxeo Repository Session
213      * @return
214      */
215     public RepositoryInstance getRepositorySession() {
216         
217         return repositorySession;
218     }
219
220     /**
221      * setRepositorySession sets repository session
222      * @param repoSession
223      */
224     public void setRepositorySession(RepositoryInstance repoSession) {
225         this.repositorySession = repoSession;
226     }
227
228     @Override
229     public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
230         // TODO for sub-docs - check to see if the current service context is a multipart input, 
231         // OR a docfragment, and call a variant to fill the DocModel.
232         fillAllParts(wrapDoc, Action.CREATE);
233         handleCoreValues(wrapDoc, Action.CREATE);
234     }
235     
236     // TODO for sub-docs - Add completeCreate in which we look for set-aside doc fragments 
237     // and create the subitems. We will create service contexts with the doc fragments
238     // and then call 
239
240
241     @Override
242     public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
243         // TODO for sub-docs - check to see if the current service context is a multipart input, 
244         // OR a docfragment, and call a variant to fill the DocModel.
245         fillAllParts(wrapDoc, Action.UPDATE);
246         handleCoreValues(wrapDoc, Action.UPDATE);
247     }
248
249     @Override
250     public void handleGet(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
251         extractAllParts(wrapDoc);
252     }
253
254     @Override
255     public void handleGetAll(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception {
256         Profiler profiler = new Profiler(this, 2);
257         profiler.start();
258         setCommonPartList(extractCommonPartList(wrapDoc));
259         profiler.stop();
260     }
261
262     @Override
263     public abstract void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
264
265     @Override
266     public abstract void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
267
268     @Override
269     public abstract T extractCommonPart(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
270
271     @Override
272     public abstract void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception;
273
274     @Override
275     public abstract void fillCommonPart(T obj, DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
276
277     @Override
278     public abstract TL extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception;
279
280     @Override
281     public abstract T getCommonPart();
282
283     @Override
284     public abstract void setCommonPart(T obj);
285
286     @Override
287     public abstract TL getCommonPartList();
288
289     @Override
290     public abstract void setCommonPartList(TL obj);
291     
292     @Override
293     public DocumentFilter createDocumentFilter() {
294         DocumentFilter filter = new NuxeoDocumentFilter(this.getServiceContext());
295         return filter;
296     }
297     
298     /**
299      * Gets the authority refs.
300      *
301      * @param docWrapper the doc wrapper
302      * @param authRefFields the auth ref fields
303      * @return the authority refs
304      * @throws PropertyException the property exception
305      */
306     abstract public AuthorityRefList getAuthorityRefs(String csid,
307                 List<AuthRefConfigInfo> authRefsInfo) throws PropertyException, Exception;    
308
309     /*
310      * Subclasses should override this method if they need to customize their refname generation
311      */
312     protected RefName.RefNameInterface getRefName(ServiceContext ctx,
313                 DocumentModel docModel) {
314         return getRefName(new DocumentWrapperImpl<DocumentModel>(docModel), ctx.getTenantName(), ctx.getServiceName());
315     }
316     
317     /*
318      * By default, we'll use the CSID as the short ID.  Sub-classes can override this method if they want to use
319      * something else for a short ID.
320      * 
321      * (non-Javadoc)
322      * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#getRefName(org.collectionspace.services.common.document.DocumentWrapper, java.lang.String, java.lang.String)
323      */
324     @Override
325         protected RefName.RefNameInterface getRefName(DocumentWrapper<DocumentModel> docWrapper,
326                         String tenantName, String serviceName) {
327         String csid = docWrapper.getWrappedObject().getName();
328         String refnameDisplayName = getRefnameDisplayName(docWrapper);
329         RefName.RefNameInterface refname = RefName.Authority.buildAuthority(tenantName, serviceName,
330                         csid, null, refnameDisplayName);
331         return refname;
332         }
333
334     private void handleCoreValues(DocumentWrapper<DocumentModel> docWrapper, 
335                 Action action)  throws ClientException {
336         DocumentModel documentModel = docWrapper.getWrappedObject();
337         String now = GregorianCalendarDateTimeUtils.timestampUTC();
338         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
339         String userId = ctx.getUserId();
340         if (action == Action.CREATE) {
341             //
342             // Add the tenant ID value to the new entity
343             //
344                 String tenantId = ctx.getTenantId();
345             documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
346                         CollectionSpaceClient.COLLECTIONSPACE_CORE_TENANTID, tenantId);
347             //
348             // Add the uri value to the new entity
349             //
350             documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
351                         CollectionSpaceClient.COLLECTIONSPACE_CORE_URI, getUri(documentModel));
352                 //
353                 // Add the CSID to the DublinCore title so we can see the CSID in the default
354                 // Nuxeo webapp.
355                 //
356                 try {
357                 documentModel.setProperty("dublincore", "title",
358                         documentModel.getName());
359                 } catch (Exception x) {
360                         if (logger.isWarnEnabled() == true) {
361                                 logger.warn("Could not set the Dublin Core 'title' field on document CSID:" +
362                                                 documentModel.getName());
363                         }
364                 }
365                 //
366                 // Add createdAt timestamp and createdBy user
367                 //
368             documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
369                         CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_AT, now);
370             documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
371                         CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_BY, userId);
372         }
373         
374                 if (action == Action.CREATE || action == Action.UPDATE) {
375             //
376             // Add/update the resource's refname
377             //
378                         handleRefNameChanges(ctx, documentModel);
379             //
380             // Add updatedAt timestamp and updateBy user
381             //
382                         documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
383                                         CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT, now);
384                         documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
385                                         CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_BY, userId);
386                 }               
387     }
388     
389     protected boolean hasRefNameUpdate() {
390         boolean result = false;
391         
392         if (Tools.notBlank(newRefNameOnUpdate) && Tools.notBlank(oldRefNameOnUpdate)) {
393                 if (newRefNameOnUpdate.equalsIgnoreCase(oldRefNameOnUpdate) == false) {
394                         result = true; // refNames are different so updates are needed
395                 }
396         }
397         
398         return result;
399     }
400     
401     protected void handleRefNameChanges(ServiceContext ctx, DocumentModel docModel) throws ClientException {
402         // First get the old refName
403         this.oldRefNameOnUpdate = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
404                         CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME);
405         // Next, get the new refName
406         RefNameInterface refName = getRefName(ctx, docModel); // Sub-classes may override the getRefName() method called here.
407         if (refName != null) {
408                 this.newRefNameOnUpdate = refName.toString();
409         } else {
410                 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?
411         }
412         //
413         // Set the refName if it is an update or if the old refName was empty or null
414         //
415         if (hasRefNameUpdate() == true || this.oldRefNameOnUpdate == null) {
416                 docModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
417                                 CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME, this.newRefNameOnUpdate);
418         }
419     }
420         
421     /*
422      * If we see the "rtSbj" query param then we need to perform a CMIS query.  Currently, we have only one
423      * CMIS query, but we could add more.  If we do, this method should look at the incoming request and corresponding
424      * query params to determine if we need to do a CMIS query
425      * (non-Javadoc)
426      * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#isCMISQuery()
427      */
428     public boolean isCMISQuery() {
429         boolean result = false;
430         
431         MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
432         //
433         // Look the query params to see if we need to make a CMSIS query.
434         //
435         String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);           
436         String asOjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);      
437         String asEither = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);         
438         if (asSubjectCsid != null || asOjectCsid != null || asEither != null) {
439                 result = true;
440         }
441         
442         return result;
443     }
444         
445         /**
446          * Creates the CMIS query from the service context. Each document handler is
447          * responsible for returning (can override) a valid CMIS query using the information in the
448          * current service context -which includes things like the query parameters,
449          * etc.
450          * 
451          * This method implementation supports three mutually exclusive cases. We will build a query
452          * that can find a document(s) 'A' in a relationship with another document
453          * 'B' where document 'B' has a CSID equal to the query param passed in and:
454          *              1. Document 'B' is the subject of the relationship
455          *              2. Document 'B' is the object of the relationship
456          *              3. Document 'B' is either the object or the subject of the relationship
457          */
458     @Override
459     public String getCMISQuery(QueryContext queryContext) {
460         String result = null;
461         
462         if (isCMISQuery() == true) {
463                 //
464                 // Build up the query arguments
465                 //
466                 String theOnClause = "";
467                 String theWhereClause = "";
468                 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
469                 String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
470                 String asObjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
471                 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
472                 String matchObjDocTypes = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES);
473                 String selectDocType = (String)queryParams.getFirst(IQueryManager.SELECT_DOC_TYPE_FIELD);
474
475                 //String docType = this.getServiceContext().getDocumentType();
476                 // If this type in this tenant has been extended, be sure to use that so extension schema is visible.
477                 String docType = NuxeoUtils.getTenantQualifiedDocType(this.getServiceContext());
478                 if (selectDocType != null && !selectDocType.isEmpty()) {  
479                         docType = selectDocType;
480                 }
481                 String selectFields = IQueryManager.CMIS_TARGET_CSID + ", "
482                                 + IQueryManager.CMIS_TARGET_TITLE + ", "
483                                 + IRelationsManager.CMIS_CSPACE_RELATIONS_TITLE + ", "
484                                 + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID + ", "
485                                 + IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
486                 String targetTable = docType + " " + IQueryManager.CMIS_TARGET_PREFIX;
487                 String relTable = IRelationsManager.DOC_TYPE + " " + IQueryManager.CMIS_RELATIONS_PREFIX;
488                 String relObjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID;
489                 String relSubjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
490                 String targetCsidCol = IQueryManager.CMIS_TARGET_CSID;
491
492                 //
493                 // Create the "ON" and "WHERE" query clauses based on the params passed into the HTTP request.  
494                 //
495                 // First come, first serve -the first match determines the "ON" and "WHERE" query clauses.
496                 //
497                 if (asSubjectCsid != null && !asSubjectCsid.isEmpty()) {  
498                         // 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.
499                         theOnClause = relObjectCsidCol + " = " + targetCsidCol;
500                         theWhereClause = relSubjectCsidCol + " = " + "'" + asSubjectCsid + "'";
501                 } else if (asObjectCsid != null && !asObjectCsid.isEmpty()) {
502                         // 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.
503                         theOnClause = relSubjectCsidCol + " = " + targetCsidCol; 
504                         theWhereClause = relObjectCsidCol + " = " + "'" + asObjectCsid + "'";
505                 } else if (asEitherCsid != null && !asEitherCsid.isEmpty()) {
506                         theOnClause = relObjectCsidCol + " = " + targetCsidCol
507                                         + " OR " + relSubjectCsidCol + " = " + targetCsidCol;
508                         theWhereClause = relSubjectCsidCol + " = " + "'" + asEitherCsid + "'"
509                                         + " OR " + relObjectCsidCol + " = " + "'" + asEitherCsid + "'";
510                 } else {
511                         //Since the call to isCMISQuery() return true, we should never get here.
512                         logger.error("Attempt to make CMIS query failed because the HTTP request was missing valid query parameters.");
513                 }
514                 
515                 // Now consider a constraint on the object doc types (for search by service group)
516                 if (matchObjDocTypes != null && !matchObjDocTypes.isEmpty()) {  
517                         // 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.
518                         theWhereClause += " AND (" + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_TYPE 
519                                                                 + " IN " + matchObjDocTypes + ")";
520                 }
521                 
522                 // This could later be in control of a queryParam, to omit if we want to see versions, or to
523                 // only see old versions.
524                 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_NUXEO_IS_VERSION_FILTER;
525                 
526                 StringBuilder query = new StringBuilder();
527                 // assemble the query from the string arguments
528                 query.append("SELECT ");
529                 query.append(selectFields);
530                 query.append(" FROM " + targetTable + " JOIN " + relTable);
531                 query.append(" ON " + theOnClause);
532                 query.append(" WHERE " + theWhereClause);
533                 
534                 try {
535                                 NuxeoUtils.appendCMISOrderBy(query, queryContext);
536                         } catch (Exception e) {
537                                 logger.error("Could not append ORDER BY clause to CMIS query", e);
538                         }
539                 
540                 // An example:
541                 // SELECT D.cmis:name, D.dc:title, R.dc:title, R.relations_common:subjectCsid
542                 // FROM Dimension D JOIN Relation R
543                 // ON R.relations_common:objectCsid = D.cmis:name
544                 // WHERE R.relations_common:subjectCsid = '737527ec-a560-4776-99de'
545                 // ORDER BY D.collectionspace_core:updatedAt DESC
546                 
547                 result = query.toString();
548                 if (logger.isDebugEnabled() == true && result != null) {
549                         logger.debug("The CMIS query is: " + result);
550                 }
551         }
552         
553         return result;
554     }
555     
556 }