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.vocabulary;
26 import org.collectionspace.services.client.IClientQueryParams;
27 import org.collectionspace.services.client.PayloadInputPart;
28 import org.collectionspace.services.client.PoxPayload;
29 import org.collectionspace.services.client.PoxPayloadIn;
30 import org.collectionspace.services.client.PoxPayloadOut;
31 import org.collectionspace.services.client.VocabularyClient;
32 import org.collectionspace.services.client.workflow.WorkflowClient;
33 import org.collectionspace.services.common.CSWebApplicationException;
34 import org.collectionspace.services.common.ResourceMap;
35 import org.collectionspace.services.common.ServiceMessages;
36 import org.collectionspace.services.common.UriInfoWrapper;
37 import org.collectionspace.services.common.api.Tools;
38 import org.collectionspace.services.common.context.ServiceBindingUtils;
39 import org.collectionspace.services.common.context.ServiceContext;
40 import org.collectionspace.services.common.document.DocumentException;
41 import org.collectionspace.services.common.document.DocumentHandler;
42 import org.collectionspace.services.common.document.DocumentNotFoundException;
43 import org.collectionspace.services.common.repository.RepositoryClient;
44 import org.collectionspace.services.common.vocabulary.AuthorityResource;
45 import org.collectionspace.services.common.vocabulary.AuthorityServiceUtils;
46 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
47 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
48 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
49 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityIdentifierUtils;
50 import org.collectionspace.services.jaxb.AbstractCommonList;
51 import org.collectionspace.services.jaxb.AbstractCommonList.ListItem;
52 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
53 import org.collectionspace.services.vocabulary.nuxeo.VocabularyItemDocumentModelHandler;
54 import org.nuxeo.ecm.core.api.DocumentModel;
55 import org.nuxeo.ecm.core.api.DocumentModelList;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58 import org.w3c.dom.Element;
60 import java.util.Base64;
61 import java.util.HashSet;
64 import javax.ws.rs.GET;
65 import javax.ws.rs.POST;
66 import javax.ws.rs.PUT;
67 import javax.ws.rs.Path;
68 import javax.ws.rs.PathParam;
69 import javax.ws.rs.core.Context;
70 import javax.ws.rs.core.MultivaluedMap;
71 import javax.ws.rs.core.Request;
72 import javax.ws.rs.core.Response;
73 import javax.ws.rs.core.UriBuilder;
74 import javax.ws.rs.core.UriInfo;
75 import javax.xml.bind.DatatypeConverter;
77 @Path("/" + VocabularyClient.SERVICE_PATH_COMPONENT)
78 public class VocabularyResource extends
79 AuthorityResource<VocabulariesCommon, VocabularyItemDocumentModelHandler> {
85 private final static String vocabularyServiceName = VocabularyClient.SERVICE_PATH_COMPONENT;
87 private final static String VOCABULARIES_COMMON = "vocabularies_common";
89 private final static String vocabularyItemServiceName = "vocabularyitems";
90 private final static String VOCABULARYITEMS_COMMON = "vocabularyitems_common";
92 final Logger logger = LoggerFactory.getLogger(VocabularyResource.class);
94 public VocabularyResource() {
95 super(VocabulariesCommon.class, VocabularyResource.class,
96 VOCABULARIES_COMMON, VOCABULARYITEMS_COMMON);
101 public Response createAuthority(
102 @Context ResourceMap resourceMap,
103 @Context UriInfo uriInfo,
106 // Requests to create new authorities come in on new threads. Unfortunately, we need to synchronize those threads on this block because, as of 8/27/2015, we can't seem to get Nuxeo
107 // transaction code to deal with a database level UNIQUE constraint violations on the 'shortidentifier' column of the vocabularies_common table.
108 // Therefore, to prevent having multiple authorities with the same shortid, we need to synchronize
109 // the code that creates new authorities. The authority document model handler will first check for authorities with the same short id before
110 // trying to create a new authority.
112 synchronized(AuthorityResource.class) {
114 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
115 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
116 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = this.getRepositoryClient(ctx);
118 CoreSessionInterface repoSession = repoClient.getRepositorySession(ctx);
120 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
121 String csid = repoClient.create(ctx, handler);
123 // Handle any supplied list of items/terms
125 handleItemsPayload(Method.POST, ctx, csid, resourceMap, uriInfo, input);
126 UriBuilder path = UriBuilder.fromResource(resourceClass);
127 path.path("" + csid);
128 Response response = Response.created(path.build()).build();
130 } catch (Throwable t) {
131 repoSession.setTransactionRollbackOnly();
134 repoClient.releaseRepositorySession(ctx, repoSession);
136 } catch (Exception e) {
137 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
145 public byte[] updateAuthority(
146 @Context Request request,
147 @Context ResourceMap resourceMap,
149 @PathParam("csid") String specifier,
151 PoxPayloadOut result = null;
153 UriInfoWrapper uriInfo = new UriInfoWrapper(ui); // We need to make the queryParams maps read-write instead of read-only
154 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
155 Specifier spec = Specifier.getSpecifier(specifier, "updateAuthority", "UPDATE");
156 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate, uriInfo);
157 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = this.getRepositoryClient(ctx);
159 CoreSessionInterface repoSession = repoClient.getRepositorySession(ctx);
161 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
163 if (spec.form == SpecifierForm.CSID) {
166 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
167 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
169 getRepositoryClient(ctx).update(ctx, csid, handler);
170 if (handleItemsPayload(Method.PUT, ctx, csid, resourceMap, uriInfo, theUpdate) == true) {
171 ctx.setOutput(new PoxPayloadOut(getServiceName())); // Clear the "vocabularies_common" result since we're going to create a new one with the items-list payload
172 result = this.getAuthority(ctx, request, uriInfo, specifier, true);
174 result = ctx.getOutput();
176 } catch (Throwable t) {
177 repoSession.setTransactionRollbackOnly();
180 repoClient.releaseRepositorySession(ctx, repoSession);
182 } catch (Exception e) {
183 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
185 return result.getBytes();
188 private void updateWithItemsPayload(
189 AbstractCommonList itemsList,
190 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
191 String parentIdentifier,
192 ResourceMap resourceMap,
194 PoxPayloadIn input) throws Exception {
196 CoreSessionInterface repoSession = (CoreSessionInterface) existingCtx.getCurrentRepositorySession();
197 Set<String> shortIdsInPayload = getListOfShortIds(itemsList); // record the list of existing or new terms/items
200 // First try to update and/or create items in the incoming payload
202 for (ListItem item : itemsList.getListItem()) {
203 String errMsg = null;
204 boolean success = true;
205 Response response = null;
206 PoxPayloadOut payloadOut = null;
207 PoxPayloadIn itemXmlPayload = getItemXmlPayload(item);
208 String itemSpecifier = getSpecifier(item);
209 if (itemSpecifier != null) {
211 payloadOut = updateAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemSpecifier, itemXmlPayload);
212 if (payloadOut == null) {
214 errMsg = String.format("Could not update the term list payload of vocabuary '%s'.", parentIdentifier);
216 } catch (DocumentNotFoundException dnf) {
218 // Since the item doesn't exist, we're being ask to create it
220 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
221 if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
223 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
228 // Since the item was supplied with neither a CSID nor a short identifier, we'll assume we're being
229 // asked to create it.
231 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
232 if (response.getStatus() == Response.Status.CREATED.getStatusCode()) {
233 String shortId = getShortId(itemXmlPayload);
234 shortIdsInPayload.add(shortId); // add the new short ID to the list of incoming items
237 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
241 // Throw an exception as soon as we have problems with any item
243 if (success == false) {
244 throw new DocumentException(errMsg);
249 // Next, delete the items that were omitted from the incoming payload
251 if (shouldDeleteOmittedItems(uriInfo) == true) {
252 String omittedItemAction = getOmittedItemAction(uriInfo);
253 AbstractCommonList abstractCommonList = this.getAuthorityItemList(existingCtx, parentIdentifier, uriInfo);
254 if (abstractCommonList != null && !Tools.isEmpty(abstractCommonList.getListItem())) {
255 if (omittedItemAction.equalsIgnoreCase(VocabularyClient.DELETE_OMITTED_ITEMS)) {
256 deleteAuthorityItems(existingCtx, abstractCommonList, shortIdsInPayload, parentIdentifier);
258 sotfDeleteAuthorityItems(existingCtx, abstractCommonList, shortIdsInPayload, parentIdentifier);
264 private String getShortId(PoxPayloadIn itemXmlPayload) {
265 String result = null;
267 VocabularyitemsCommon vocabularyItemsCommon = (VocabularyitemsCommon) itemXmlPayload.getPart(VOCABULARYITEMS_COMMON).getBody();
268 result = vocabularyItemsCommon.getShortIdentifier();
273 private void deleteAuthorityItems(
274 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
275 AbstractCommonList abstractCommonList,
276 Set<String> shortIdsInPayload,
277 String parentIdentifier) throws Exception {
279 for (ListItem item : abstractCommonList.getListItem()) {
280 String shortId = getShortId(item);
281 if (shortIdsInPayload.contains(shortId) == false) {
282 deleteAuthorityItem(existingCtx, parentIdentifier, getCsid(item), AuthorityServiceUtils.UPDATE_REV);
287 private void sotfDeleteAuthorityItems(
288 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
289 AbstractCommonList abstractCommonList,
290 Set<String> shortIdsInPayload,
291 String parentIdentifier) throws Exception {
293 for (ListItem item : abstractCommonList.getListItem()) {
294 String shortId = getShortId(item);
295 if (shortIdsInPayload.contains(shortId) == false) {
296 //deleteAuthorityItem(existingCtx, parentIdentifier, getCsid(item), AuthorityServiceUtils.UPDATE_REV);
297 this.updateItemWorkflowWithTransition(existingCtx, parentIdentifier, getCsid(item),
298 WorkflowClient.WORKFLOWTRANSITION_DELETE, AuthorityServiceUtils.UPDATE_REV);
303 private boolean shouldDeleteOmittedItems(UriInfo uriInfo) throws DocumentException {
304 boolean result = false;
306 String omittedItemAction = getOmittedItemAction(uriInfo);
307 if (Tools.isEmpty(omittedItemAction) == false) {
308 switch (omittedItemAction) {
309 case VocabularyClient.DELETE_OMITTED_ITEMS:
310 case VocabularyClient.SOFTDELETE_OMITTED_ITEMS:
313 case VocabularyClient.IGNORE_OMITTED_ITEMS:
317 String msg = String.format("Unknown value '%s' for update on a vocabulary/termlist resource.", omittedItemAction);
318 throw new DocumentException(msg);
325 private String getOmittedItemAction(UriInfo uriInfo) {
326 MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
327 String omittedItemAction = queryParams.getFirst(VocabularyClient.OMITTED_ITEM_ACTION_QP);
328 return omittedItemAction;
332 * Returns the set of short identifiers in the abstract common list of authority items
334 private Set<String> getListOfShortIds(AbstractCommonList itemsList) {
335 HashSet<String> result = new HashSet<String>();
337 for (ListItem item : itemsList.getListItem()) {
338 String shortId = getShortId(item);
339 if (Tools.isEmpty(shortId) == false) {
347 private void createWithItemsPayload(
348 AbstractCommonList itemsList,
349 ServiceContext<PoxPayloadIn,
350 PoxPayloadOut> existingCtx,
351 String parentIdentifier,
352 ResourceMap resourceMap,
354 PoxPayloadIn input) throws Exception {
356 for (ListItem item : itemsList.getListItem()) {
357 String errMsg = null;
358 boolean success = true;
359 Response response = null;
360 PoxPayloadIn itemXmlPayload = getItemXmlPayload(item);
362 CoreSessionInterface repoSession = (CoreSessionInterface) existingCtx.getCurrentRepositorySession();
363 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
364 if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
366 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
369 // Throw an exception as soon as we have problems with any item
371 if (success == false) {
372 throw new DocumentException(errMsg);
377 private boolean handleItemsPayload(
379 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
380 String parentIdentifier,
381 ResourceMap resourceMap,
383 PoxPayloadIn input) throws Exception {
384 boolean result = false;
386 PayloadInputPart abstractCommonListPart = input.getPart(PoxPayload.ABSTRACT_COMMON_LIST_ROOT_ELEMENT_LABEL);
387 if (abstractCommonListPart != null) {
388 AbstractCommonList itemsList = (AbstractCommonList) abstractCommonListPart.getBody();
391 createWithItemsPayload(itemsList, existingCtx, parentIdentifier, resourceMap, uriInfo, input);
394 updateWithItemsPayload(itemsList, existingCtx, parentIdentifier, resourceMap, uriInfo, input);
397 result = true; // mark that we've handled an items-list payload
403 private String getFieldValue(ListItem item, String lookingFor) {
404 String result = null;
406 for (Element ele : item.getAny()) {
407 String fieldName = ele.getTagName();
408 String fieldValue = ele.getTextContent();
409 if (fieldName.equalsIgnoreCase(lookingFor)) {
418 private String getCsid(ListItem item) {
419 return getFieldValue(item, "csid");
422 private String getShortId(ListItem item) {
423 return getFieldValue(item, "shortIdentifier");
426 private String getDisplayName(ListItem item) {
427 return getFieldValue(item, "displayName");
431 * We'll return null if we can create a specifier from the list item.
436 private String getSpecifier(ListItem item) {
437 String result = null;
439 String csid = result = getCsid(item);
441 String shortId = getShortId(item);
442 if (shortId != null) {
443 result = Specifier.createShortIdURNValue(shortId);
451 * This is very brittle. If the class VocabularyitemsCommon changed with new fields we'd have to
452 * update this method.
456 * @throws DocumentException
458 private PoxPayloadIn getItemXmlPayload(ListItem item) throws DocumentException {
459 PoxPayloadIn result = null;
461 VocabularyitemsCommon vocabularyItem = new VocabularyitemsCommon();
462 for (Element ele : item.getAny()) {
463 String fieldName = ele.getTagName();
464 String fieldValue = ele.getTextContent();
467 vocabularyItem.setDisplayName(fieldValue);
470 case "shortIdentifier":
471 vocabularyItem.setShortIdentifier(fieldValue);
475 vocabularyItem.setOrder(fieldValue);
479 vocabularyItem.setSource(fieldValue);
483 vocabularyItem.setSourcePage(fieldValue);
487 vocabularyItem.setDescription(fieldValue);
491 vocabularyItem.setCsid(fieldValue);
495 vocabularyItem.setTermStatus(fieldValue);
499 // ignore other fields
504 // We need to create a short ID if one wasn't supplied
506 if (Tools.isEmpty(vocabularyItem.getShortIdentifier())) {
507 vocabularyItem.setShortIdentifier(AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(
508 vocabularyItem.getDisplayName() , null)); ;
511 result = new PoxPayloadIn(VocabularyClient.SERVICE_ITEM_PAYLOAD_NAME, vocabularyItem,
512 VOCABULARYITEMS_COMMON);
517 private Response createAuthorityItem(
518 CoreSessionInterface repoSession,
519 ResourceMap resourceMap,
521 String parentIdentifier, // Either a CSID or a URN form -e.g., a8ad38ec-1d7d-4bf2-bd31 or urn:cspace:name(bugsbunny)
522 PoxPayloadIn input) throws Exception {
523 Response result = null;
525 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
526 ctx.setCurrentRepositorySession(repoSession);
528 result = createAuthorityItem(ctx, parentIdentifier, AuthorityServiceUtils.UPDATE_REV,
529 AuthorityServiceUtils.PROPOSED, AuthorityServiceUtils.NOT_SAS_ITEM);
534 private PoxPayloadOut updateAuthorityItem(
535 CoreSessionInterface repoSession,
536 ResourceMap resourceMap,
538 String parentSpecifier, // Either a CSID or a URN form -e.g., a8ad38ec-1d7d-4bf2-bd31 or urn:cspace:name(bugsbunny)
539 String itemSpecifier, // Either a CSID or a URN form.
540 PoxPayloadIn theUpdate) throws Exception {
541 PoxPayloadOut result = null;
543 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
544 ctx.setCurrentRepositorySession(repoSession);
546 result = updateAuthorityItem(ctx, resourceMap, uriInfo, parentSpecifier, itemSpecifier, theUpdate,
547 AuthorityServiceUtils.UPDATE_REV, // passing TRUE so rev num increases, passing
548 AuthorityServiceUtils.NO_CHANGE, // don't change the state of the "proposed" field -we could be performing a sync or just a plain update
549 AuthorityServiceUtils.NO_CHANGE); // don't change the state of the "sas" field -we could be performing a sync or just a plain update
558 @Context Request request,
559 @Context UriInfo uriInfo,
560 @PathParam("csid") String specifier) {
561 Response result = null;
562 uriInfo = new UriInfoWrapper(uriInfo);
565 MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
566 String showItemsValue = (String)queryParams.getFirst(VocabularyClient.SHOW_ITEMS_QP);
567 boolean showItems = Tools.isTrue(showItemsValue);
568 if (showItems == true) {
570 // We'll honor paging params if we find any; otherwise we'll set the page size to 0 to get ALL the items
572 if (queryParams.containsKey(IClientQueryParams.PAGE_SIZE_PARAM) == false) {
573 queryParams.add(IClientQueryParams.PAGE_SIZE_PARAM, "0");
577 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(request, uriInfo);
578 PoxPayloadOut payloadout = getAuthority(ctx, request, uriInfo, specifier, showItems);
579 result = buildResponse(ctx, payloadout);
580 } catch (Exception e) {
581 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
584 if (result == null) {
585 Response response = Response.status(Response.Status.NOT_FOUND).entity(
586 "GET request failed. The requested Authority specifier:" + specifier + ": was not found.").type(
587 "text/plain").build();
588 throw new CSWebApplicationException(response);
595 public String getServiceName() {
596 return vocabularyServiceName;
600 public String getItemServiceName() {
601 return vocabularyItemServiceName;
605 public Class<VocabulariesCommon> getCommonPartClass() {
606 return VocabulariesCommon.class;
610 * @return the name of the property used to specify references for items in this type of
611 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
612 * Some types (like Vocabulary) use a separate property.
615 protected String getRefPropName() {
616 return ServiceBindingUtils.TERM_REF_PROP;
620 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
621 String result = null;
623 result = authorityItemCommonSchemaName + ":" + VocabularyItemJAXBSchema.DISPLAY_NAME;
629 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
630 return getOrderByField(ctx);
634 * The item schema for the Vocabulary service does not support a multi-valued term list. Only authorities that support
635 * term lists need to implement this method.
638 public String getItemTermInfoGroupXPathBase() {