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