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:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
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.
24 package org.collectionspace.services.servicegroup.nuxeo;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.MultivaluedMap;
35 import javax.ws.rs.core.Response;
37 import org.collectionspace.services.config.service.Tags;
38 import org.collectionspace.services.nuxeo.client.java.CommonList;
39 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
40 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
41 import org.collectionspace.services.nuxeo.client.java.NuxeoRepositoryClientImpl;
42 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
43 import org.collectionspace.services.jaxb.AbstractCommonList;
44 import org.collectionspace.services.client.CollectionSpaceClient;
45 import org.collectionspace.services.client.IQueryManager;
46 import org.collectionspace.services.client.IRelationsManager;
47 import org.collectionspace.services.client.PoxPayloadIn;
48 import org.collectionspace.services.client.PoxPayloadOut;
49 import org.collectionspace.services.common.NuxeoBasedResource;
50 import org.collectionspace.services.common.CSWebApplicationException;
51 import org.collectionspace.services.common.ServiceMain;
52 import org.collectionspace.services.common.ServiceMessages;
53 import org.collectionspace.services.common.StoredValuesUriTemplate;
54 import org.collectionspace.services.common.UriTemplateFactory;
55 import org.collectionspace.services.common.UriTemplateRegistry;
56 import org.collectionspace.services.common.UriTemplateRegistryKey;
57 import org.collectionspace.services.common.api.RefName;
58 import org.collectionspace.services.common.api.RefNameUtils;
59 import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo;
60 import org.collectionspace.services.common.api.Tools;
61 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
62 import org.collectionspace.services.common.context.ServiceBindingUtils;
63 import org.collectionspace.services.common.context.ServiceContext;
64 import org.collectionspace.services.common.document.DocumentException;
65 import org.collectionspace.services.common.document.DocumentFilter;
66 import org.collectionspace.services.common.document.DocumentNotFoundException;
67 import org.collectionspace.services.common.document.DocumentWrapper;
68 import org.collectionspace.services.common.security.SecurityUtils;
69 import org.collectionspace.services.common.query.QueryContext;
70 import org.collectionspace.services.common.query.nuxeo.QueryManagerNuxeoImpl;
71 import org.collectionspace.services.common.relation.nuxeo.RelationsUtils;
72 import org.collectionspace.services.config.service.ServiceBindingType;
73 import org.collectionspace.services.config.service.ServiceObjectType;
74 import org.collectionspace.services.servicegroup.ServicegroupsCommon;
75 import org.collectionspace.services.common.vocabulary.AuthorityResource;
76 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
77 import org.nuxeo.ecm.core.api.DocumentModel;
78 import org.nuxeo.ecm.core.api.DocumentModelList;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
82 public class ServiceGroupDocumentModelHandler
83 extends NuxeoDocumentModelHandler<ServicegroupsCommon> {
85 protected final Logger logger = LoggerFactory.getLogger(this.getClass());
87 protected static final int NUM_META_FIELDS = 4; // the number of meta fields -i.e., DOC_TYPE_FIELD, DOC_NUMBER_FIELD, DOC_NAME_FIELD, STANDARD_LIST_MARK_RT_FIELD
88 protected static final String DOC_TYPE_FIELD = "docType";
89 protected static final String DOC_NUMBER_FIELD = "docNumber";
90 protected static final String DOC_NAME_FIELD = "docName";
91 protected static final String STANDARD_LIST_MARK_RT_FIELD = "related";
94 // Returns a service payload for an authority item
96 private PoxPayloadOut getAuthorityItem(ServiceContext ctx, String termRefName) throws Exception {
97 PoxPayloadOut result = null;
99 RefName.AuthorityItem item = RefName.AuthorityItem.parse(termRefName, true);
100 AuthorityResource authorityResource = (AuthorityResource) ctx.getResourceMap().get(item.inAuthority.resource);
102 AuthorityTermInfo authorityTermInfo = RefNameUtils.parseAuthorityTermInfo(termRefName);
103 String parentIdentifier = Specifier.createShortIdURNValue(authorityTermInfo.inAuthority.name);
104 String itemIdentifier = Specifier.createShortIdURNValue(authorityTermInfo.name);
106 result = authorityResource.getAuthorityItemWithExistingContext(ctx, parentIdentifier, itemIdentifier);
111 public PoxPayloadOut getResourceItemForCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
112 List<String> serviceGroupNames,
113 String csid) throws DocumentException {
114 PoxPayloadOut result = null;
115 CoreSessionInterface repoSession = null;
116 boolean releaseRepoSession = false;
119 NuxeoRepositoryClientImpl repoClient = (NuxeoRepositoryClientImpl)this.getRepositoryClient(ctx);
120 repoSession = this.getRepositorySession();
121 if (repoSession == null) {
122 repoSession = repoClient.getRepositorySession(ctx);
123 releaseRepoSession = true;
126 Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();
127 DocumentModelList docList = this.getDocListForGroup(ctx, serviceGroupNames, queriedServiceBindings,
128 repoSession, repoClient);
129 if (docList == null || docList.isEmpty()) { // found no authRef fields - nothing to process
130 throw new DocumentNotFoundException();
132 DocumentModel docModel = docList.get(0);
134 // Determine if the docModel is an authority term, object, or some other procedure record.
136 String termRefName = (String) NuxeoUtils.getProperyValue(docModel, CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME);
137 if (isAuthorityTermDocument(termRefName) == true) {
138 result = getAuthorityItem(ctx, termRefName);
140 TenantBindingConfigReaderImpl bindingReader = ServiceMain.getInstance().getTenantBindingConfigReader();
141 String serviceName = ServiceBindingUtils.getServiceNameFromObjectName(bindingReader, ctx.getTenantId(),
142 docModel.getDocumentType().getName());
143 NuxeoBasedResource resource = (NuxeoBasedResource) ctx.getResourceMap().get(serviceName);
144 result = resource.getWithParentCtx(ctx, csid);
146 } catch (DocumentException de) {
148 } catch (Exception e) {
149 if (logger.isDebugEnabled()) {
150 logger.debug("Caught exception ", e);
152 throw new DocumentException(e);
154 if (releaseRepoSession && repoSession != null) {
155 repoClient.releaseRepositorySession(ctx, repoSession);
158 } catch (Exception e) {
159 if (logger.isDebugEnabled()) {
160 logger.debug("Caught exception ", e);
162 throw new DocumentException(e);
168 private boolean isAuthorityTermDocument(String termRefName) {
169 boolean result = true;
172 //String inAuthorityCsid = (String) NuxeoUtils.getProperyValue(docModel, "inAuthority"); //docModel.getPropertyValue("inAuthority"); // AuthorityItemJAXBSchema.IN_AUTHORITY
173 //String refName = (String) NuxeoUtils.getProperyValue(docModel, CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME);
174 RefName.AuthorityItem item = RefName.AuthorityItem.parse(termRefName, true);
175 } catch (IllegalArgumentException e) {
183 * Search for documents matching a query from the service context and return the ${@link DocumentModelList}
185 * This relies on the ServiceContext in order to get the tag query parameter of the HTTP request. If no tag
186 * parameter exists in the context, all document types are queried against. If a tag does exist, we check the
187 * service bindings to see if they include said tag. If no service bindings match the tag, we throw a 400 as we
188 * cannot query using an empty set.
191 * @param serviceGroupNames
192 * @param queriedServiceBindings
195 * @return the result of the query
196 * @throws CSWebApplicationException (400) if the doc types set to query against is empty
197 * @throws CSWebApplicationException (404) if the service bindings cannot be read
199 private DocumentModelList getDocListForGroup(
200 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
201 List<String> serviceGroupNames,
202 Map<String, ServiceBindingType> queriedServiceBindings,
203 CoreSessionInterface repoSession,
204 NuxeoRepositoryClientImpl repoClient) throws Exception {
206 // Get the service bindings for this tenant
207 TenantBindingConfigReaderImpl tReader = ServiceMain.getInstance().getTenantBindingConfigReader();
208 // We need to get all the procedures, authorities, and objects.
209 List<ServiceBindingType> servicebindings =
210 tReader.getServiceBindingsByType(ctx.getTenantId(), serviceGroupNames);
211 if (servicebindings == null || servicebindings.isEmpty()) {
212 Response response = Response.status(Response.Status.NOT_FOUND)
213 .entity(ServiceMessages.READ_FAILED +
214 ServiceMessages.resourceNotFoundMsg(implode(serviceGroupNames, ",")))
215 .type(MediaType.TEXT_PLAIN_TYPE).build();
216 throw new CSWebApplicationException(response);
219 String queryTag = ctx.getQueryParams().getFirst(IQueryManager.TAG_QUERY_PARAM);
220 servicebindings = SecurityUtils.getReadableServiceBindingsForCurrentUser(servicebindings);
221 // Build the list of docTypes for allowed serviceBindings filtered optionally on tags
222 ArrayList<String> docTypes = new ArrayList<String>();
223 for (ServiceBindingType binding : servicebindings) {
224 boolean acceptDocType = true;
225 if (queryTag != null && !queryTag.isEmpty()) {
226 acceptDocType = acceptServiceBinding(binding, queryTag);
229 ServiceObjectType serviceObj = binding.getObject();
230 if (acceptDocType && serviceObj != null) {
231 String docType = serviceObj.getName();
232 docTypes.add(docType);
233 queriedServiceBindings.put(docType, binding);
237 // we can't query if no doc types match, likely from a bad tag
238 if (docTypes.isEmpty()) {
239 Response response = Response.status(Response.Status.BAD_REQUEST)
240 .entity("Cannot query against no document types. Check that tag query parameters are correct.")
241 .type(MediaType.TEXT_PLAIN_TYPE)
243 throw new CSWebApplicationException(response);
246 // This should be type "Document" but CMIS is gagging on that right now.
247 ctx.getQueryParams().add(
248 IQueryManager.SELECT_DOC_TYPE_FIELD,
249 QueryManagerNuxeoImpl.COLLECTIONSPACE_DOCUMENT_TYPE);
251 // Now we have to issue the search
252 // The findDocs() method will build a QueryContext, which wants to see a docType for our context
253 ctx.setDocumentType(QueryManagerNuxeoImpl.NUXEO_DOCUMENT_TYPE);
254 DocumentWrapper<DocumentModelList> docListWrapper = repoClient.findDocs(ctx, this, repoSession, docTypes);
255 // Now we gather the info for each document into the list and return
256 DocumentModelList docList = docListWrapper.getWrappedObject();
261 * Test if a service binding should be included in a search based on the tag query parameter passed in.
263 * If a tag starts with a "-", it is assumed this is intended to be a negation, and we check if the service binding
264 * does not contain said tag.
266 * @param binding the ServiceBinding to check
267 * @param queryTag tag query parameter
268 * @return true if the ServiceBinding contains all query parameters, false otherwise
270 public boolean acceptServiceBinding(ServiceBindingType binding, String queryTag) {
271 final Tags tags = binding.getTags();
272 final List<String> tagList = tags == null ? Collections.<String>emptyList() : tags.getTag();
275 if (queryTag.startsWith("-")) {
276 accept = !tagList.contains(queryTag.substring(1));
278 accept = tagList.contains(queryTag);
284 public AbstractCommonList getItemListForGroup(
285 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
286 List<String> serviceGroupNames) throws Exception {
287 CommonList commonList = new CommonList();
288 AbstractCommonList list = (AbstractCommonList)commonList;
289 CoreSessionInterface repoSession = null;
290 boolean releaseRepoSession = false;
293 DocumentFilter myFilter = getDocumentFilter();
294 int pageSize = myFilter.getPageSize();
295 int pageNum = myFilter.getStartPage();
296 list.setPageNum(pageNum);
297 list.setPageSize(pageSize);
299 NuxeoRepositoryClientImpl repoClient = (NuxeoRepositoryClientImpl)this.getRepositoryClient(ctx);
300 repoSession = this.getRepositorySession();
301 if (repoSession == null) {
302 repoSession = repoClient.getRepositorySession(ctx);
303 releaseRepoSession = true;
306 Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();
307 DocumentModelList docList = this.getDocListForGroup(ctx, serviceGroupNames, queriedServiceBindings,
308 repoSession, repoClient);
309 if (docList == null) { // found no authRef fields - nothing to process
312 processDocList(ctx, docList, queriedServiceBindings, commonList);
313 list.setItemsInPage(docList.size());
314 list.setTotalItems(docList.totalSize());
315 } catch (DocumentException de) {
317 } catch (Exception e) {
318 if (logger.isDebugEnabled()) {
319 logger.debug("Caught exception ", e);
321 throw new DocumentException(e);
323 if (releaseRepoSession && repoSession != null) {
324 repoClient.releaseRepositorySession(ctx, repoSession);
327 } catch (Exception e) {
328 if (logger.isDebugEnabled()) {
329 logger.debug("Caught exception ", e);
331 throw new DocumentException(e);
337 // Move this to a Utils class!
338 public static String implode(List<String> stringList, String sep) {
339 StringBuilder sb = new StringBuilder();
341 boolean fFirst = false;
342 for (String name:stringList) {
351 return sb.toString();
354 private String getUriFromServiceBinding(ServiceBindingType sb, String csid) {
355 return "/" + sb.getName().toLowerCase() + "/" + csid;
358 private void processDocList(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
359 DocumentModelList docList,
360 Map<String, ServiceBindingType> queriedServiceBindings,
361 CommonList list) throws DocumentException {
363 String tenantId = ctx.getTenantId();
364 CoreSessionInterface repoSession = null;
365 NuxeoRepositoryClientImpl repoClient = null;
366 boolean releaseRepoSession = false;
368 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
369 String markRtSbj = queryParams.getFirst(IQueryManager.MARK_RELATED_TO_CSID_AS_SUBJECT);
370 if (Tools.isBlank(markRtSbj)) {
374 String markRtSbjOrObj = queryParams.getFirst(IQueryManager.MARK_RELATED_TO_CSID_AS_EITHER);
375 if (Tools.isBlank(markRtSbjOrObj)) {
376 markRtSbjOrObj = null;
378 if (Tools.isBlank(markRtSbj) == false) {
379 logger.warn(String.format("Ignoring query param %s='%s' since overriding query param %s='%s' exists.",
380 IQueryManager.MARK_RELATED_TO_CSID_AS_SUBJECT, markRtSbj, IQueryManager.MARK_RELATED_TO_CSID_AS_EITHER, markRtSbjOrObj));
382 markRtSbj = markRtSbjOrObj; // Mark the record as related independent of whether it is the subject or object of a relationship
386 if (markRtSbj != null) {
387 repoClient = (NuxeoRepositoryClientImpl) this.getRepositoryClient(ctx);
388 NuxeoRepositoryClientImpl nuxeoRepoClient = (NuxeoRepositoryClientImpl) repoClient;
389 repoSession = this.getRepositorySession();
390 if (repoSession == null) {
391 repoSession = repoClient.getRepositorySession(ctx);
392 releaseRepoSession = true;
396 String fields[] = new String[NUM_META_FIELDS + NUM_STANDARD_LIST_RESULT_FIELDS];
397 fields[0] = STANDARD_LIST_CSID_FIELD;
398 fields[1] = STANDARD_LIST_URI_FIELD;
399 fields[2] = STANDARD_LIST_UPDATED_AT_FIELD;
400 fields[3] = STANDARD_LIST_WORKFLOW_FIELD;
401 fields[4] = STANDARD_LIST_REFNAME_FIELD;
402 fields[5] = DOC_NAME_FIELD;
403 fields[6] = DOC_NUMBER_FIELD;
404 fields[7] = DOC_TYPE_FIELD;
405 if (markRtSbj != null) {
406 fields[8] = STANDARD_LIST_MARK_RT_FIELD;
409 list.setFieldsReturned(fields);
411 Iterator<DocumentModel> iter = docList.iterator();
412 HashMap<String, Object> item = new HashMap<String, Object>();
413 while (iter.hasNext()) {
414 DocumentModel docModel = iter.next();
415 String docType = docModel.getDocumentType().getName();
416 docType = ServiceBindingUtils.getUnqualifiedTenantDocType(docType);
417 ServiceBindingType sb = queriedServiceBindings.get(docType);
419 throw new RuntimeException("processDocList: No Service Binding for docType: " + docType);
422 String csid = NuxeoUtils.getCsid(docModel);
423 item.put(STANDARD_LIST_CSID_FIELD, csid);
426 // If the mark-related query param was set, check to see if the doc we're processing
427 // is related to the value specified in the mark-related query param.
429 if (markRtSbj != null) {
430 String relationClause = RelationsUtils.buildWhereClause(markRtSbj, null, null, csid, null, markRtSbj == markRtSbjOrObj);
431 String whereClause = relationClause + IQueryManager.SEARCH_QUALIFIER_AND
432 + NuxeoUtils.buildWorkflowNotDeletedWhereClause();
433 QueryContext queryContext = new QueryContext(ctx, whereClause);
434 queryContext.setDocType(IRelationsManager.DOC_TYPE);
435 String query = NuxeoUtils.buildNXQLQuery(queryContext);
436 // Search for 1 relation that matches. 1 is enough to fail
438 DocumentModelList queryDocList = repoSession.query(query, null, 1, 0, false);
439 item.put(STANDARD_LIST_MARK_RT_FIELD, queryDocList.isEmpty() ? "false" : "true");
442 UriTemplateRegistry uriTemplateRegistry = ServiceMain.getInstance().getUriTemplateRegistry();
443 StoredValuesUriTemplate storedValuesResourceTemplate = uriTemplateRegistry.get(new UriTemplateRegistryKey(tenantId, docType));
444 Map<String, String> additionalValues = new HashMap<String, String>();
445 if (storedValuesResourceTemplate.getUriTemplateType() == UriTemplateFactory.ITEM) {
447 String inAuthorityCsid = (String) NuxeoUtils.getProperyValue(docModel, "inAuthority"); //docModel.getPropertyValue("inAuthority"); // AuthorityItemJAXBSchema.IN_AUTHORITY
448 additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, inAuthorityCsid);
449 additionalValues.put(UriTemplateFactory.ITEM_IDENTIFIER_VAR, csid);
450 } catch (Exception e) {
451 String msg = String.format("Could not extract inAuthority property from authority item with CSID = ", docModel.getName());
455 additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, csid);
458 String uriStr = storedValuesResourceTemplate.buildUri(additionalValues);
459 item.put(STANDARD_LIST_URI_FIELD, uriStr);
461 item.put(STANDARD_LIST_UPDATED_AT_FIELD, getUpdatedAtAsString(docModel));
462 item.put(STANDARD_LIST_WORKFLOW_FIELD, docModel.getCurrentLifeCycleState());
463 item.put(STANDARD_LIST_REFNAME_FIELD, getRefname(docModel));
464 } catch(Exception e) {
465 logger.error("Error getting core values for doc ["+csid+"]: "+e.getLocalizedMessage());
468 String value = ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NUMBER_PROP, docModel);
470 item.put(DOC_NUMBER_FIELD, value);
473 value = ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NAME_PROP, docModel);
475 item.put(DOC_NAME_FIELD, value);
478 item.put(DOC_TYPE_FIELD, docType);
479 // add the item to the list
483 } catch (Exception e) {
484 if (logger.isDebugEnabled()) {
485 logger.debug("Caught exception ", e);
487 throw new DocumentException(e);
489 // If we got/acquired a new session then we're responsible for releasing it.
490 if (releaseRepoSession && repoSession != null) {
491 repoClient.releaseRepositorySession(ctx, repoSession);