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.jaxb.AbstractCommonList;
50 import org.collectionspace.services.jaxb.AbstractCommonList.ListItem;
51 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
52 import org.collectionspace.services.vocabulary.nuxeo.VocabularyItemDocumentModelHandler;
53 import org.nuxeo.ecm.core.api.DocumentModel;
54 import org.nuxeo.ecm.core.api.DocumentModelList;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.w3c.dom.Element;
59 import java.util.Base64;
60 import java.util.HashSet;
63 import javax.ws.rs.GET;
64 import javax.ws.rs.POST;
65 import javax.ws.rs.PUT;
66 import javax.ws.rs.Path;
67 import javax.ws.rs.PathParam;
68 import javax.ws.rs.core.Context;
69 import javax.ws.rs.core.MultivaluedMap;
70 import javax.ws.rs.core.Request;
71 import javax.ws.rs.core.Response;
72 import javax.ws.rs.core.UriBuilder;
73 import javax.ws.rs.core.UriInfo;
74 import javax.xml.bind.DatatypeConverter;
76 @Path("/" + VocabularyClient.SERVICE_PATH_COMPONENT)
77 public class VocabularyResource extends
78 AuthorityResource<VocabulariesCommon, VocabularyItemDocumentModelHandler> {
84 private final static String vocabularyServiceName = VocabularyClient.SERVICE_PATH_COMPONENT;
86 private final static String VOCABULARIES_COMMON = "vocabularies_common";
88 private final static String vocabularyItemServiceName = "vocabularyitems";
89 private final static String VOCABULARYITEMS_COMMON = "vocabularyitems_common";
91 final Logger logger = LoggerFactory.getLogger(VocabularyResource.class);
93 public VocabularyResource() {
94 super(VocabulariesCommon.class, VocabularyResource.class,
95 VOCABULARIES_COMMON, VOCABULARYITEMS_COMMON);
100 public Response createAuthority(
101 @Context ResourceMap resourceMap,
102 @Context UriInfo uriInfo,
105 // 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
106 // transaction code to deal with a database level UNIQUE constraint violations on the 'shortidentifier' column of the vocabularies_common table.
107 // Therefore, to prevent having multiple authorities with the same shortid, we need to synchronize
108 // the code that creates new authorities. The authority document model handler will first check for authorities with the same short id before
109 // trying to create a new authority.
111 synchronized(AuthorityResource.class) {
113 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
114 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
115 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = this.getRepositoryClient(ctx);
117 CoreSessionInterface repoSession = repoClient.getRepositorySession(ctx);
119 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
120 String csid = repoClient.create(ctx, handler);
122 // Handle any supplied list of items/terms
124 handleItemsPayload(Method.POST, ctx, csid, resourceMap, uriInfo, input);
125 UriBuilder path = UriBuilder.fromResource(resourceClass);
126 path.path("" + csid);
127 Response response = Response.created(path.build()).build();
129 } catch (Throwable t) {
130 repoSession.setTransactionRollbackOnly();
133 repoClient.releaseRepositorySession(ctx, repoSession);
135 } catch (Exception e) {
136 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
144 public byte[] updateAuthority(
145 @Context ResourceMap resourceMap,
147 @PathParam("csid") String specifier,
149 PoxPayloadOut result = null;
151 UriInfoWrapper uriInfo = new UriInfoWrapper(ui); // We need to make the queryParams maps read-write instead of read-only
152 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
153 Specifier spec = Specifier.getSpecifier(specifier, "updateAuthority", "UPDATE");
154 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate, uriInfo);
155 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = this.getRepositoryClient(ctx);
157 CoreSessionInterface repoSession = repoClient.getRepositorySession(ctx);
159 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
161 if (spec.form == SpecifierForm.CSID) {
164 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
165 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
167 getRepositoryClient(ctx).update(ctx, csid, handler);
168 handleItemsPayload(Method.PUT, ctx, csid, resourceMap, uriInfo, theUpdate);
169 result = ctx.getOutput();
170 } catch (Throwable t) {
171 repoSession.setTransactionRollbackOnly();
174 repoClient.releaseRepositorySession(ctx, repoSession);
176 } catch (Exception e) {
177 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
179 return result.getBytes();
182 private void updateWithItemsPayload(
183 AbstractCommonList itemsList,
184 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
185 String parentIdentifier,
186 ResourceMap resourceMap,
188 PoxPayloadIn input) throws Exception {
190 CoreSessionInterface repoSession = (CoreSessionInterface) existingCtx.getCurrentRepositorySession();
191 Set<String> shortIdsInPayload = getListOfShortIds(itemsList); // record the list of existing or new terms/items
194 // First try to update and/or create items in the incoming payload
196 for (ListItem item : itemsList.getListItem()) {
197 String errMsg = null;
198 boolean success = true;
199 Response response = null;
200 PoxPayloadOut payloadOut = null;
201 PoxPayloadIn itemXmlPayload = getItemXmlPayload(item);
202 String itemSpecifier = getSpecifier(item);
203 if (itemSpecifier != null) {
205 payloadOut = updateAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemSpecifier, itemXmlPayload);
206 if (payloadOut == null) {
208 errMsg = String.format("Could not update the term list payload of vocabuary '%s'.", parentIdentifier);
210 } catch (DocumentNotFoundException dnf) {
212 // Since the item doesn't exist, we're being ask to create it
214 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
215 if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
217 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
222 // Since the item was supplied with neither a CSID nor a short identifier, we'll assume we're being
223 // asked to create it.
225 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
226 if (response.getStatus() == Response.Status.CREATED.getStatusCode()) {
227 String shortId = getShortId(itemXmlPayload);
228 shortIdsInPayload.add(shortId); // add the new short ID to the list of incoming items
231 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
235 // Throw an exception as soon as we have problems with any item
237 if (success == false) {
238 throw new DocumentException(errMsg);
243 // Next, delete the items that were omitted from the incoming payload
245 if (shouldDeleteOmittedItems(uriInfo) == true) {
246 String omittedItemAction = getOmittedItemAction(uriInfo);
247 AbstractCommonList abstractCommonList = this.getAuthorityItemList(existingCtx, parentIdentifier, uriInfo);
248 if (abstractCommonList != null && !Tools.isEmpty(abstractCommonList.getListItem())) {
249 if (omittedItemAction.equalsIgnoreCase(VocabularyClient.DELETE_OMITTED_ITEMS)) {
250 deleteAuthorityItems(existingCtx, abstractCommonList, shortIdsInPayload, parentIdentifier);
252 sotfDeleteAuthorityItems(existingCtx, abstractCommonList, shortIdsInPayload, parentIdentifier);
258 private String getShortId(PoxPayloadIn itemXmlPayload) {
259 String result = null;
261 VocabularyitemsCommon vocabularyItemsCommon = (VocabularyitemsCommon) itemXmlPayload.getPart(VOCABULARYITEMS_COMMON).getBody();
262 result = vocabularyItemsCommon.getShortIdentifier();
267 private void deleteAuthorityItems(
268 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
269 AbstractCommonList abstractCommonList,
270 Set<String> shortIdsInPayload,
271 String parentIdentifier) throws Exception {
273 for (ListItem item : abstractCommonList.getListItem()) {
274 String shortId = getShortId(item);
275 if (shortIdsInPayload.contains(shortId) == false) {
276 deleteAuthorityItem(existingCtx, parentIdentifier, getCsid(item), AuthorityServiceUtils.UPDATE_REV);
281 private void sotfDeleteAuthorityItems(
282 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
283 AbstractCommonList abstractCommonList,
284 Set<String> shortIdsInPayload,
285 String parentIdentifier) throws Exception {
287 for (ListItem item : abstractCommonList.getListItem()) {
288 String shortId = getShortId(item);
289 if (shortIdsInPayload.contains(shortId) == false) {
290 //deleteAuthorityItem(existingCtx, parentIdentifier, getCsid(item), AuthorityServiceUtils.UPDATE_REV);
291 this.updateItemWorkflowWithTransition(existingCtx, parentIdentifier, getCsid(item),
292 WorkflowClient.WORKFLOWTRANSITION_DELETE, AuthorityServiceUtils.UPDATE_REV);
297 private boolean shouldDeleteOmittedItems(UriInfo uriInfo) throws DocumentException {
298 boolean result = false;
300 String omittedItemAction = getOmittedItemAction(uriInfo);
301 if (Tools.isEmpty(omittedItemAction) == false) {
302 switch (omittedItemAction) {
303 case VocabularyClient.DELETE_OMITTED_ITEMS:
304 case VocabularyClient.SOFTDELETE_OMITTED_ITEMS:
307 case VocabularyClient.IGNORE_OMITTED_ITEMS:
311 String msg = String.format("Unknown value '%s' for update on a vocabulary/termlist resource.", omittedItemAction);
312 throw new DocumentException(msg);
319 private String getOmittedItemAction(UriInfo uriInfo) {
320 MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
321 String omittedItemAction = queryParams.getFirst(VocabularyClient.OMITTED_ITEM_ACTION_QP);
322 return omittedItemAction;
326 * Returns the set of short identifiers in the abstract common list of authority items
328 private Set<String> getListOfShortIds(AbstractCommonList itemsList) {
329 HashSet<String> result = new HashSet<String>();
331 for (ListItem item : itemsList.getListItem()) {
332 String shortId = getShortId(item);
333 if (Tools.isEmpty(shortId) == false) {
341 private void createWithItemsPayload(
342 AbstractCommonList itemsList,
343 ServiceContext<PoxPayloadIn,
344 PoxPayloadOut> existingCtx,
345 String parentIdentifier,
346 ResourceMap resourceMap,
348 PoxPayloadIn input) throws Exception {
350 for (ListItem item : itemsList.getListItem()) {
351 String errMsg = null;
352 boolean success = true;
353 Response response = null;
354 PoxPayloadIn itemXmlPayload = getItemXmlPayload(item);
356 CoreSessionInterface repoSession = (CoreSessionInterface) existingCtx.getCurrentRepositorySession();
357 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
358 if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
360 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
363 // Throw an exception as soon as we have problems with any item
365 if (success == false) {
366 throw new DocumentException(errMsg);
371 private boolean handleItemsPayload(
373 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
374 String parentIdentifier,
375 ResourceMap resourceMap,
377 PoxPayloadIn input) throws Exception {
378 boolean result = true;
380 PayloadInputPart abstractCommonListPart = input.getPart(PoxPayload.ABSTRACT_COMMON_LIST_ROOT_ELEMENT_LABEL);
381 if (abstractCommonListPart != null) {
382 AbstractCommonList itemsList = (AbstractCommonList) abstractCommonListPart.getBody();
385 createWithItemsPayload(itemsList, existingCtx, parentIdentifier, resourceMap, uriInfo, input);
388 updateWithItemsPayload(itemsList, existingCtx, parentIdentifier, resourceMap, uriInfo, input);
396 private String getFieldValue(ListItem item, String lookingFor) {
397 String result = null;
399 for (Element ele : item.getAny()) {
400 String fieldName = ele.getTagName();
401 String fieldValue = ele.getTextContent();
402 if (fieldName.equalsIgnoreCase(lookingFor)) {
411 private String getCsid(ListItem item) {
412 return getFieldValue(item, "csid");
415 private String getShortId(ListItem item) {
416 return getFieldValue(item, "shortIdentifier");
419 private String getDisplayName(ListItem item) {
420 return getFieldValue(item, "displayName");
424 * We'll return null if we can create a specifier from the list item.
429 private String getSpecifier(ListItem item) {
430 String result = null;
432 String csid = result = getCsid(item);
434 String shortId = getShortId(item);
435 if (shortId != null) {
436 result = Specifier.createShortIdURNValue(shortId);
444 * This is very brittle. If the class VocabularyitemsCommon changed with new fields we'd have to
445 * update this method.
449 * @throws DocumentException
451 private PoxPayloadIn getItemXmlPayload(ListItem item) throws DocumentException {
452 PoxPayloadIn result = null;
454 VocabularyitemsCommon vocabularyItem = new VocabularyitemsCommon();
455 for (Element ele : item.getAny()) {
456 String fieldName = ele.getTagName();
457 String fieldValue = ele.getTextContent();
460 vocabularyItem.setDisplayName(fieldValue);
463 case "shortIdentifier":
464 vocabularyItem.setShortIdentifier(fieldValue);
468 vocabularyItem.setOrder(fieldValue);
472 vocabularyItem.setSource(fieldValue);
476 vocabularyItem.setSourcePage(fieldValue);
480 vocabularyItem.setDescription(fieldValue);
484 vocabularyItem.setCsid(fieldValue);
488 vocabularyItem.setTermStatus(fieldValue);
492 // ignore other fields
497 if (Tools.isEmpty(vocabularyItem.getShortIdentifier())) {
499 // We need to create a short ID since one wasn't supplied
501 String value = String.format("%s%d", getDisplayName(item), System.currentTimeMillis());
502 value = DatatypeConverter.printHexBinary(value.getBytes()).toUpperCase();
503 vocabularyItem.setShortIdentifier(value);
506 result = new PoxPayloadIn(VocabularyClient.SERVICE_ITEM_PAYLOAD_NAME, vocabularyItem,
507 VOCABULARYITEMS_COMMON);
512 private Response createAuthorityItem(
513 CoreSessionInterface repoSession,
514 ResourceMap resourceMap,
516 String parentIdentifier, // Either a CSID or a URN form -e.g., a8ad38ec-1d7d-4bf2-bd31 or urn:cspace:name(bugsbunny)
517 PoxPayloadIn input) throws Exception {
518 Response result = null;
520 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
521 ctx.setCurrentRepositorySession(repoSession);
523 result = createAuthorityItem(ctx, parentIdentifier, AuthorityServiceUtils.UPDATE_REV,
524 AuthorityServiceUtils.PROPOSED, AuthorityServiceUtils.NOT_SAS_ITEM);
529 private PoxPayloadOut updateAuthorityItem(
530 CoreSessionInterface repoSession,
531 ResourceMap resourceMap,
533 String parentSpecifier, // Either a CSID or a URN form -e.g., a8ad38ec-1d7d-4bf2-bd31 or urn:cspace:name(bugsbunny)
534 String itemSpecifier, // Either a CSID or a URN form.
535 PoxPayloadIn theUpdate) throws Exception {
536 PoxPayloadOut result = null;
538 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
539 ctx.setCurrentRepositorySession(repoSession);
541 result = updateAuthorityItem(ctx, resourceMap, uriInfo, parentSpecifier, itemSpecifier, theUpdate,
542 AuthorityServiceUtils.UPDATE_REV, // passing TRUE so rev num increases, passing
543 AuthorityServiceUtils.NO_CHANGE, // don't change the state of the "proposed" field -we could be performing a sync or just a plain update
544 AuthorityServiceUtils.NO_CHANGE); // don't change the state of the "sas" field -we could be performing a sync or just a plain update
553 @Context Request request,
554 @Context UriInfo uriInfo,
555 @PathParam("csid") String specifier) {
556 Response result = null;
557 uriInfo = new UriInfoWrapper(uriInfo);
560 MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
561 String showItemsValue = (String)queryParams.getFirst(VocabularyClient.SHOW_ITEMS_QP);
562 boolean showItems = Tools.isTrue(showItemsValue);
563 if (showItems == true) {
565 // We'll honor paging params if we find any; otherwise we'll set the page size to 0 to get ALL the items
567 if (queryParams.containsKey(IClientQueryParams.PAGE_SIZE_PARAM) == false) {
568 queryParams.add(IClientQueryParams.PAGE_SIZE_PARAM, "0");
572 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(request, uriInfo);
573 PoxPayloadOut payloadout = getAuthority(ctx, request, uriInfo, specifier, showItems);
574 result = buildResponse(ctx, payloadout);
575 } catch (Exception e) {
576 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
579 if (result == null) {
580 Response response = Response.status(Response.Status.NOT_FOUND).entity(
581 "GET request failed. The requested Authority specifier:" + specifier + ": was not found.").type(
582 "text/plain").build();
583 throw new CSWebApplicationException(response);
590 public String getServiceName() {
591 return vocabularyServiceName;
595 public String getItemServiceName() {
596 return vocabularyItemServiceName;
600 public Class<VocabulariesCommon> getCommonPartClass() {
601 return VocabulariesCommon.class;
605 * @return the name of the property used to specify references for items in this type of
606 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
607 * Some types (like Vocabulary) use a separate property.
610 protected String getRefPropName() {
611 return ServiceBindingUtils.TERM_REF_PROP;
615 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
616 String result = null;
618 result = authorityItemCommonSchemaName + ":" + VocabularyItemJAXBSchema.DISPLAY_NAME;
624 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
625 return getOrderByField(ctx);
629 * The item schema for the Vocabulary service does not support a multi-valued term list. Only authorities that support
630 * term lists need to implement this method.
633 public String getItemTermInfoGroupXPathBase() {