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