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 result = this.getAuthority(ctx, request, uriInfo, specifier, true);
173 result = ctx.getOutput();
175 } catch (Throwable t) {
176 repoSession.setTransactionRollbackOnly();
179 repoClient.releaseRepositorySession(ctx, repoSession);
181 } catch (Exception e) {
182 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
184 return result.getBytes();
187 private void updateWithItemsPayload(
188 AbstractCommonList itemsList,
189 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
190 String parentIdentifier,
191 ResourceMap resourceMap,
193 PoxPayloadIn input) throws Exception {
195 CoreSessionInterface repoSession = (CoreSessionInterface) existingCtx.getCurrentRepositorySession();
196 Set<String> shortIdsInPayload = getListOfShortIds(itemsList); // record the list of existing or new terms/items
199 // First try to update and/or create items in the incoming payload
201 for (ListItem item : itemsList.getListItem()) {
202 String errMsg = null;
203 boolean success = true;
204 Response response = null;
205 PoxPayloadOut payloadOut = null;
206 PoxPayloadIn itemXmlPayload = getItemXmlPayload(item);
207 String itemSpecifier = getSpecifier(item);
208 if (itemSpecifier != null) {
210 payloadOut = updateAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemSpecifier, itemXmlPayload);
211 if (payloadOut == null) {
213 errMsg = String.format("Could not update the term list payload of vocabuary '%s'.", parentIdentifier);
215 } catch (DocumentNotFoundException dnf) {
217 // Since the item doesn't exist, we're being ask to create it
219 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
220 if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
222 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
227 // Since the item was supplied with neither a CSID nor a short identifier, we'll assume we're being
228 // asked to create it.
230 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
231 if (response.getStatus() == Response.Status.CREATED.getStatusCode()) {
232 String shortId = getShortId(itemXmlPayload);
233 shortIdsInPayload.add(shortId); // add the new short ID to the list of incoming items
236 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
240 // Throw an exception as soon as we have problems with any item
242 if (success == false) {
243 throw new DocumentException(errMsg);
248 // Next, delete the items that were omitted from the incoming payload
250 if (shouldDeleteOmittedItems(uriInfo) == true) {
251 String omittedItemAction = getOmittedItemAction(uriInfo);
252 AbstractCommonList abstractCommonList = this.getAuthorityItemList(existingCtx, parentIdentifier, uriInfo);
253 if (abstractCommonList != null && !Tools.isEmpty(abstractCommonList.getListItem())) {
254 if (omittedItemAction.equalsIgnoreCase(VocabularyClient.DELETE_OMITTED_ITEMS)) {
255 deleteAuthorityItems(existingCtx, abstractCommonList, shortIdsInPayload, parentIdentifier);
257 sotfDeleteAuthorityItems(existingCtx, abstractCommonList, shortIdsInPayload, parentIdentifier);
263 private String getShortId(PoxPayloadIn itemXmlPayload) {
264 String result = null;
266 VocabularyitemsCommon vocabularyItemsCommon = (VocabularyitemsCommon) itemXmlPayload.getPart(VOCABULARYITEMS_COMMON).getBody();
267 result = vocabularyItemsCommon.getShortIdentifier();
272 private void deleteAuthorityItems(
273 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
274 AbstractCommonList abstractCommonList,
275 Set<String> shortIdsInPayload,
276 String parentIdentifier) throws Exception {
278 for (ListItem item : abstractCommonList.getListItem()) {
279 String shortId = getShortId(item);
280 if (shortIdsInPayload.contains(shortId) == false) {
281 deleteAuthorityItem(existingCtx, parentIdentifier, getCsid(item), AuthorityServiceUtils.UPDATE_REV);
286 private void sotfDeleteAuthorityItems(
287 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
288 AbstractCommonList abstractCommonList,
289 Set<String> shortIdsInPayload,
290 String parentIdentifier) throws Exception {
292 for (ListItem item : abstractCommonList.getListItem()) {
293 String shortId = getShortId(item);
294 if (shortIdsInPayload.contains(shortId) == false) {
295 //deleteAuthorityItem(existingCtx, parentIdentifier, getCsid(item), AuthorityServiceUtils.UPDATE_REV);
296 this.updateItemWorkflowWithTransition(existingCtx, parentIdentifier, getCsid(item),
297 WorkflowClient.WORKFLOWTRANSITION_DELETE, AuthorityServiceUtils.UPDATE_REV);
302 private boolean shouldDeleteOmittedItems(UriInfo uriInfo) throws DocumentException {
303 boolean result = false;
305 String omittedItemAction = getOmittedItemAction(uriInfo);
306 if (Tools.isEmpty(omittedItemAction) == false) {
307 switch (omittedItemAction) {
308 case VocabularyClient.DELETE_OMITTED_ITEMS:
309 case VocabularyClient.SOFTDELETE_OMITTED_ITEMS:
312 case VocabularyClient.IGNORE_OMITTED_ITEMS:
316 String msg = String.format("Unknown value '%s' for update on a vocabulary/termlist resource.", omittedItemAction);
317 throw new DocumentException(msg);
324 private String getOmittedItemAction(UriInfo uriInfo) {
325 MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
326 String omittedItemAction = queryParams.getFirst(VocabularyClient.OMITTED_ITEM_ACTION_QP);
327 return omittedItemAction;
331 * Returns the set of short identifiers in the abstract common list of authority items
333 private Set<String> getListOfShortIds(AbstractCommonList itemsList) {
334 HashSet<String> result = new HashSet<String>();
336 for (ListItem item : itemsList.getListItem()) {
337 String shortId = getShortId(item);
338 if (Tools.isEmpty(shortId) == false) {
346 private void createWithItemsPayload(
347 AbstractCommonList itemsList,
348 ServiceContext<PoxPayloadIn,
349 PoxPayloadOut> existingCtx,
350 String parentIdentifier,
351 ResourceMap resourceMap,
353 PoxPayloadIn input) throws Exception {
355 for (ListItem item : itemsList.getListItem()) {
356 String errMsg = null;
357 boolean success = true;
358 Response response = null;
359 PoxPayloadIn itemXmlPayload = getItemXmlPayload(item);
361 CoreSessionInterface repoSession = (CoreSessionInterface) existingCtx.getCurrentRepositorySession();
362 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
363 if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
365 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
368 // Throw an exception as soon as we have problems with any item
370 if (success == false) {
371 throw new DocumentException(errMsg);
376 private boolean handleItemsPayload(
378 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
379 String parentIdentifier,
380 ResourceMap resourceMap,
382 PoxPayloadIn input) throws Exception {
383 boolean result = false;
385 PayloadInputPart abstractCommonListPart = input.getPart(PoxPayload.ABSTRACT_COMMON_LIST_ROOT_ELEMENT_LABEL);
386 if (abstractCommonListPart != null) {
387 AbstractCommonList itemsList = (AbstractCommonList) abstractCommonListPart.getBody();
390 createWithItemsPayload(itemsList, existingCtx, parentIdentifier, resourceMap, uriInfo, input);
393 updateWithItemsPayload(itemsList, existingCtx, parentIdentifier, resourceMap, uriInfo, input);
396 result = true; // mark that we've handled an items-list payload
402 private String getFieldValue(ListItem item, String lookingFor) {
403 String result = null;
405 for (Element ele : item.getAny()) {
406 String fieldName = ele.getTagName();
407 String fieldValue = ele.getTextContent();
408 if (fieldName.equalsIgnoreCase(lookingFor)) {
417 private String getCsid(ListItem item) {
418 return getFieldValue(item, "csid");
421 private String getShortId(ListItem item) {
422 return getFieldValue(item, "shortIdentifier");
425 private String getDisplayName(ListItem item) {
426 return getFieldValue(item, "displayName");
430 * We'll return null if we can create a specifier from the list item.
435 private String getSpecifier(ListItem item) {
436 String result = null;
438 String csid = result = getCsid(item);
440 String shortId = getShortId(item);
441 if (shortId != null) {
442 result = Specifier.createShortIdURNValue(shortId);
450 * This is very brittle. If the class VocabularyitemsCommon changed with new fields we'd have to
451 * update this method.
455 * @throws DocumentException
457 private PoxPayloadIn getItemXmlPayload(ListItem item) throws DocumentException {
458 PoxPayloadIn result = null;
460 VocabularyitemsCommon vocabularyItem = new VocabularyitemsCommon();
461 for (Element ele : item.getAny()) {
462 String fieldName = ele.getTagName();
463 String fieldValue = ele.getTextContent();
466 vocabularyItem.setDisplayName(fieldValue);
469 case "shortIdentifier":
470 vocabularyItem.setShortIdentifier(fieldValue);
474 vocabularyItem.setOrder(fieldValue);
478 vocabularyItem.setSource(fieldValue);
482 vocabularyItem.setSourcePage(fieldValue);
486 vocabularyItem.setDescription(fieldValue);
490 vocabularyItem.setCsid(fieldValue);
494 vocabularyItem.setTermStatus(fieldValue);
498 // ignore other fields
503 // We need to create a short ID if one wasn't supplied
505 if (Tools.isEmpty(vocabularyItem.getShortIdentifier())) {
506 vocabularyItem.setShortIdentifier(AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(
507 vocabularyItem.getDisplayName() , null)); ;
510 result = new PoxPayloadIn(VocabularyClient.SERVICE_ITEM_PAYLOAD_NAME, vocabularyItem,
511 VOCABULARYITEMS_COMMON);
516 private Response createAuthorityItem(
517 CoreSessionInterface repoSession,
518 ResourceMap resourceMap,
520 String parentIdentifier, // Either a CSID or a URN form -e.g., a8ad38ec-1d7d-4bf2-bd31 or urn:cspace:name(bugsbunny)
521 PoxPayloadIn input) throws Exception {
522 Response result = null;
524 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
525 ctx.setCurrentRepositorySession(repoSession);
527 result = createAuthorityItem(ctx, parentIdentifier, AuthorityServiceUtils.UPDATE_REV,
528 AuthorityServiceUtils.PROPOSED, AuthorityServiceUtils.NOT_SAS_ITEM);
533 private PoxPayloadOut updateAuthorityItem(
534 CoreSessionInterface repoSession,
535 ResourceMap resourceMap,
537 String parentSpecifier, // Either a CSID or a URN form -e.g., a8ad38ec-1d7d-4bf2-bd31 or urn:cspace:name(bugsbunny)
538 String itemSpecifier, // Either a CSID or a URN form.
539 PoxPayloadIn theUpdate) throws Exception {
540 PoxPayloadOut result = null;
542 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
543 ctx.setCurrentRepositorySession(repoSession);
545 result = updateAuthorityItem(ctx, resourceMap, uriInfo, parentSpecifier, itemSpecifier, theUpdate,
546 AuthorityServiceUtils.UPDATE_REV, // passing TRUE so rev num increases, passing
547 AuthorityServiceUtils.NO_CHANGE, // don't change the state of the "proposed" field -we could be performing a sync or just a plain update
548 AuthorityServiceUtils.NO_CHANGE); // don't change the state of the "sas" field -we could be performing a sync or just a plain update
557 @Context Request request,
558 @Context UriInfo uriInfo,
559 @PathParam("csid") String specifier) {
560 Response result = null;
561 uriInfo = new UriInfoWrapper(uriInfo);
564 MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
565 String showItemsValue = (String)queryParams.getFirst(VocabularyClient.SHOW_ITEMS_QP);
566 boolean showItems = Tools.isTrue(showItemsValue);
567 if (showItems == true) {
569 // We'll honor paging params if we find any; otherwise we'll set the page size to 0 to get ALL the items
571 if (queryParams.containsKey(IClientQueryParams.PAGE_SIZE_PARAM) == false) {
572 queryParams.add(IClientQueryParams.PAGE_SIZE_PARAM, "0");
576 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(request, uriInfo);
577 PoxPayloadOut payloadout = getAuthority(ctx, request, uriInfo, specifier, showItems);
578 result = buildResponse(ctx, payloadout);
579 } catch (Exception e) {
580 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
583 if (result == null) {
584 Response response = Response.status(Response.Status.NOT_FOUND).entity(
585 "GET request failed. The requested Authority specifier:" + specifier + ": was not found.").type(
586 "text/plain").build();
587 throw new CSWebApplicationException(response);
594 public String getServiceName() {
595 return vocabularyServiceName;
599 public String getItemServiceName() {
600 return vocabularyItemServiceName;
604 public Class<VocabulariesCommon> getCommonPartClass() {
605 return VocabulariesCommon.class;
609 * @return the name of the property used to specify references for items in this type of
610 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
611 * Some types (like Vocabulary) use a separate property.
614 protected String getRefPropName() {
615 return ServiceBindingUtils.TERM_REF_PROP;
619 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
620 String result = null;
622 result = authorityItemCommonSchemaName + ":" + VocabularyItemJAXBSchema.DISPLAY_NAME;
628 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
629 return getOrderByField(ctx);
633 * The item schema for the Vocabulary service does not support a multi-valued term list. Only authorities that support
634 * term lists need to implement this method.
637 public String getItemTermInfoGroupXPathBase() {