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.AuthorityItemJAXBSchema;
45 import org.collectionspace.services.common.vocabulary.AuthorityResource;
46 import org.collectionspace.services.common.vocabulary.AuthorityServiceUtils;
47 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
48 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
49 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
50 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityIdentifierUtils;
51 import org.collectionspace.services.jaxb.AbstractCommonList;
52 import org.collectionspace.services.jaxb.AbstractCommonList.ListItem;
53 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
54 import org.collectionspace.services.vocabulary.nuxeo.VocabularyItemDocumentModelHandler;
55 import org.nuxeo.ecm.core.api.DocumentModel;
56 import org.nuxeo.ecm.core.api.DocumentModelList;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59 import org.w3c.dom.Element;
61 import java.util.Base64;
62 import java.util.HashSet;
65 import javax.ws.rs.GET;
66 import javax.ws.rs.POST;
67 import javax.ws.rs.PUT;
68 import javax.ws.rs.Path;
69 import javax.ws.rs.PathParam;
70 import javax.ws.rs.core.Context;
71 import javax.ws.rs.core.MultivaluedMap;
72 import javax.ws.rs.core.Request;
73 import javax.ws.rs.core.Response;
74 import javax.ws.rs.core.UriBuilder;
75 import javax.ws.rs.core.UriInfo;
76 import javax.xml.bind.DatatypeConverter;
78 @Path("/" + VocabularyClient.SERVICE_PATH_COMPONENT)
79 public class VocabularyResource extends
80 AuthorityResource<VocabulariesCommon, VocabularyItemDocumentModelHandler> {
86 private final static String vocabularyServiceName = VocabularyClient.SERVICE_PATH_COMPONENT;
88 private final static String VOCABULARIES_COMMON = "vocabularies_common";
90 private final static String vocabularyItemServiceName = "vocabularyitems";
91 private final static String VOCABULARYITEMS_COMMON = "vocabularyitems_common";
93 final Logger logger = LoggerFactory.getLogger(VocabularyResource.class);
95 public VocabularyResource() {
96 super(VocabulariesCommon.class, VocabularyResource.class,
97 VOCABULARIES_COMMON, VOCABULARYITEMS_COMMON);
102 public Response createAuthority(
103 @Context ResourceMap resourceMap,
104 @Context UriInfo uriInfo,
107 // 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
108 // transaction code to deal with a database level UNIQUE constraint violations on the 'shortidentifier' column of the vocabularies_common table.
109 // Therefore, to prevent having multiple authorities with the same shortid, we need to synchronize
110 // the code that creates new authorities. The authority document model handler will first check for authorities with the same short id before
111 // trying to create a new authority.
113 synchronized(AuthorityResource.class) {
115 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
116 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
117 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = this.getRepositoryClient(ctx);
119 CoreSessionInterface repoSession = repoClient.getRepositorySession(ctx);
121 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
122 String csid = repoClient.create(ctx, handler);
124 // Handle any supplied list of items/terms
126 handleItemsPayload(Method.POST, ctx, csid, resourceMap, uriInfo, input);
127 UriBuilder path = UriBuilder.fromResource(resourceClass);
128 path.path("" + csid);
129 Response response = Response.created(path.build()).build();
131 } catch (Throwable t) {
132 repoSession.setTransactionRollbackOnly();
135 repoClient.releaseRepositorySession(ctx, repoSession);
137 } catch (Exception e) {
138 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
146 public byte[] updateAuthority(
147 @Context Request request,
148 @Context ResourceMap resourceMap,
150 @PathParam("csid") String specifier,
152 PoxPayloadOut result = null;
154 UriInfoWrapper uriInfo = new UriInfoWrapper(ui); // We need to make the queryParams maps read-write instead of read-only
155 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
156 Specifier spec = Specifier.getSpecifier(specifier, "updateAuthority", "UPDATE");
157 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate, uriInfo);
158 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = this.getRepositoryClient(ctx);
160 CoreSessionInterface repoSession = repoClient.getRepositorySession(ctx);
162 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
164 if (spec.form == SpecifierForm.CSID) {
167 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
168 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
170 getRepositoryClient(ctx).update(ctx, csid, handler);
171 if (handleItemsPayload(Method.PUT, ctx, csid, resourceMap, uriInfo, theUpdate) == true) {
172 ctx.setOutput(new PoxPayloadOut(getServiceName())); // Clear the "vocabularies_common" result since we're going to create a new one with the items-list payload
173 result = this.getAuthority(ctx, request, uriInfo, specifier, true);
175 result = ctx.getOutput();
177 } catch (Throwable t) {
178 repoSession.setTransactionRollbackOnly();
181 repoClient.releaseRepositorySession(ctx, repoSession);
183 } catch (Exception e) {
184 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
186 return result.getBytes();
189 private void updateWithItemsPayload(
190 AbstractCommonList itemsList,
191 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
192 String parentIdentifier,
193 ResourceMap resourceMap,
195 PoxPayloadIn input) throws Exception {
197 CoreSessionInterface repoSession = (CoreSessionInterface) existingCtx.getCurrentRepositorySession();
198 Set<String> shortIdsInPayload = getListOfShortIds(itemsList); // record the list of existing or new terms/items
201 // First try to update and/or create items in the incoming payload
203 for (ListItem item : itemsList.getListItem()) {
204 String errMsg = null;
205 boolean success = true;
206 Response response = null;
207 PoxPayloadOut payloadOut = null;
208 PoxPayloadIn itemXmlPayload = getItemXmlPayload(item);
209 String itemSpecifier = getSpecifier(item);
210 if (itemSpecifier != null) {
212 payloadOut = updateAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemSpecifier, itemXmlPayload);
213 if (payloadOut == null) {
215 errMsg = String.format("Could not update the term list payload of vocabuary '%s'.", parentIdentifier);
217 } catch (DocumentNotFoundException dnf) {
219 // Since the item doesn't exist, we're being ask to create it
221 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
222 if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
224 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
229 // Since the item was supplied with neither a CSID nor a short identifier, we'll assume we're being
230 // asked to create it.
232 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
233 if (response.getStatus() == Response.Status.CREATED.getStatusCode()) {
234 String shortId = getShortId(itemXmlPayload);
235 shortIdsInPayload.add(shortId); // add the new short ID to the list of incoming items
238 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
242 // Throw an exception as soon as we have problems with any item
244 if (success == false) {
245 throw new DocumentException(errMsg);
250 // Next, delete the items that were omitted from the incoming payload
252 if (shouldDeleteOmittedItems(uriInfo) == true) {
253 String omittedItemAction = getOmittedItemAction(uriInfo);
254 AbstractCommonList abstractCommonList = this.getAuthorityItemList(existingCtx, parentIdentifier, uriInfo);
255 if (abstractCommonList != null && !Tools.isEmpty(abstractCommonList.getListItem())) {
256 if (omittedItemAction.equalsIgnoreCase(VocabularyClient.DELETE_OMITTED_ITEMS)) {
257 deleteAuthorityItems(existingCtx, abstractCommonList, shortIdsInPayload, parentIdentifier);
259 sotfDeleteAuthorityItems(existingCtx, abstractCommonList, shortIdsInPayload, parentIdentifier);
265 private String getShortId(PoxPayloadIn itemXmlPayload) {
266 String result = null;
268 VocabularyitemsCommon vocabularyItemsCommon = (VocabularyitemsCommon) itemXmlPayload.getPart(VOCABULARYITEMS_COMMON).getBody();
269 result = vocabularyItemsCommon.getShortIdentifier();
274 private void deleteAuthorityItems(
275 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
276 AbstractCommonList abstractCommonList,
277 Set<String> shortIdsInPayload,
278 String parentIdentifier) throws Exception {
280 for (ListItem item : abstractCommonList.getListItem()) {
281 String shortId = getShortId(item);
282 if (shortIdsInPayload.contains(shortId) == false) {
283 deleteAuthorityItem(existingCtx, parentIdentifier, getCsid(item), AuthorityServiceUtils.UPDATE_REV);
288 private void sotfDeleteAuthorityItems(
289 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
290 AbstractCommonList abstractCommonList,
291 Set<String> shortIdsInPayload,
292 String parentIdentifier) throws Exception {
294 for (ListItem item : abstractCommonList.getListItem()) {
295 String shortId = getShortId(item);
296 if (shortIdsInPayload.contains(shortId) == false) {
297 //deleteAuthorityItem(existingCtx, parentIdentifier, getCsid(item), AuthorityServiceUtils.UPDATE_REV);
298 this.updateItemWorkflowWithTransition(existingCtx, parentIdentifier, getCsid(item),
299 WorkflowClient.WORKFLOWTRANSITION_DELETE, AuthorityServiceUtils.UPDATE_REV);
304 private boolean shouldDeleteOmittedItems(UriInfo uriInfo) throws DocumentException {
305 boolean result = false;
307 String omittedItemAction = getOmittedItemAction(uriInfo);
308 if (Tools.isEmpty(omittedItemAction) == false) {
309 switch (omittedItemAction) {
310 case VocabularyClient.DELETE_OMITTED_ITEMS:
311 case VocabularyClient.SOFTDELETE_OMITTED_ITEMS:
314 case VocabularyClient.IGNORE_OMITTED_ITEMS:
318 String msg = String.format("Unknown value '%s' for update on a vocabulary/termlist resource.", omittedItemAction);
319 throw new DocumentException(msg);
326 private String getOmittedItemAction(UriInfo uriInfo) {
327 MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
328 String omittedItemAction = queryParams.getFirst(VocabularyClient.OMITTED_ITEM_ACTION_QP);
329 return omittedItemAction;
333 * Returns the set of short identifiers in the abstract common list of authority items
335 private Set<String> getListOfShortIds(AbstractCommonList itemsList) {
336 HashSet<String> result = new HashSet<String>();
338 for (ListItem item : itemsList.getListItem()) {
339 String shortId = getShortId(item);
340 if (Tools.isEmpty(shortId) == false) {
348 private void createWithItemsPayload(
349 AbstractCommonList itemsList,
350 ServiceContext<PoxPayloadIn,
351 PoxPayloadOut> existingCtx,
352 String parentIdentifier,
353 ResourceMap resourceMap,
355 PoxPayloadIn input) throws Exception {
357 for (ListItem item : itemsList.getListItem()) {
358 String errMsg = null;
359 boolean success = true;
360 Response response = null;
361 PoxPayloadIn itemXmlPayload = getItemXmlPayload(item);
363 CoreSessionInterface repoSession = (CoreSessionInterface) existingCtx.getCurrentRepositorySession();
364 response = this.createAuthorityItem(repoSession, resourceMap, uriInfo, parentIdentifier, itemXmlPayload);
365 if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
367 errMsg = String.format("Could not create the term list payload of vocabuary '%s'.", parentIdentifier);
370 // Throw an exception as soon as we have problems with any item
372 if (success == false) {
373 throw new DocumentException(errMsg);
378 private boolean handleItemsPayload(
380 ServiceContext<PoxPayloadIn, PoxPayloadOut> existingCtx,
381 String parentIdentifier,
382 ResourceMap resourceMap,
384 PoxPayloadIn input) throws Exception {
385 boolean result = false;
387 PayloadInputPart abstractCommonListPart = input.getPart(PoxPayload.ABSTRACT_COMMON_LIST_ROOT_ELEMENT_LABEL);
388 if (abstractCommonListPart != null) {
389 AbstractCommonList itemsList = (AbstractCommonList) abstractCommonListPart.getBody();
392 createWithItemsPayload(itemsList, existingCtx, parentIdentifier, resourceMap, uriInfo, input);
395 updateWithItemsPayload(itemsList, existingCtx, parentIdentifier, resourceMap, uriInfo, input);
398 result = true; // mark that we've handled an items-list payload
404 private String getFieldValue(ListItem item, String lookingFor) {
405 String result = null;
407 for (Element ele : item.getAny()) {
408 String fieldName = ele.getTagName();
409 String fieldValue = ele.getTextContent();
410 if (fieldName.equalsIgnoreCase(lookingFor)) {
419 private String getCsid(ListItem item) {
420 return getFieldValue(item, "csid");
423 private String getShortId(ListItem item) {
424 return getFieldValue(item, "shortIdentifier");
427 private String getDisplayName(ListItem item) {
428 return getFieldValue(item, "displayName");
432 * We'll return null if we can create a specifier from the list item.
437 private String getSpecifier(ListItem item) {
438 String result = null;
440 String csid = result = getCsid(item);
442 String shortId = getShortId(item);
443 if (shortId != null) {
444 result = Specifier.createShortIdURNValue(shortId);
452 * This is very brittle. If the class VocabularyitemsCommon changed with new fields we'd have to
453 * update this method.
457 * @throws DocumentException
459 private PoxPayloadIn getItemXmlPayload(ListItem item) throws DocumentException {
460 PoxPayloadIn result = null;
462 VocabularyitemsCommon vocabularyItem = new VocabularyitemsCommon();
463 for (Element ele : item.getAny()) {
464 String fieldName = ele.getTagName();
465 String fieldValue = ele.getTextContent();
468 vocabularyItem.setDisplayName(fieldValue);
471 case "shortIdentifier":
472 vocabularyItem.setShortIdentifier(fieldValue);
476 vocabularyItem.setOrder(fieldValue);
480 vocabularyItem.setSource(fieldValue);
484 vocabularyItem.setSourcePage(fieldValue);
488 vocabularyItem.setDescription(fieldValue);
492 vocabularyItem.setCsid(fieldValue);
496 vocabularyItem.setTermStatus(fieldValue);
500 // ignore other fields
505 // We need to create a short ID if one wasn't supplied
507 if (Tools.isEmpty(vocabularyItem.getShortIdentifier())) {
508 vocabularyItem.setShortIdentifier(AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(
509 vocabularyItem.getDisplayName() , null)); ;
512 result = new PoxPayloadIn(VocabularyClient.SERVICE_ITEM_PAYLOAD_NAME, vocabularyItem,
513 VOCABULARYITEMS_COMMON);
518 private Response createAuthorityItem(
519 CoreSessionInterface repoSession,
520 ResourceMap resourceMap,
522 String parentIdentifier, // Either a CSID or a URN form -e.g., a8ad38ec-1d7d-4bf2-bd31 or urn:cspace:name(bugsbunny)
523 PoxPayloadIn input) throws Exception {
524 Response result = null;
526 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
527 ctx.setCurrentRepositorySession(repoSession);
529 result = createAuthorityItem(ctx, parentIdentifier, AuthorityServiceUtils.UPDATE_REV,
530 AuthorityServiceUtils.PROPOSED, AuthorityServiceUtils.NOT_SAS_ITEM);
535 private PoxPayloadOut updateAuthorityItem(
536 CoreSessionInterface repoSession,
537 ResourceMap resourceMap,
539 String parentSpecifier, // Either a CSID or a URN form -e.g., a8ad38ec-1d7d-4bf2-bd31 or urn:cspace:name(bugsbunny)
540 String itemSpecifier, // Either a CSID or a URN form.
541 PoxPayloadIn theUpdate) throws Exception {
542 PoxPayloadOut result = null;
544 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
545 ctx.setCurrentRepositorySession(repoSession);
547 result = updateAuthorityItem(ctx, resourceMap, uriInfo, parentSpecifier, itemSpecifier, theUpdate,
548 AuthorityServiceUtils.UPDATE_REV, // passing TRUE so rev num increases, passing
549 AuthorityServiceUtils.NO_CHANGE, // don't change the state of the "proposed" field -we could be performing a sync or just a plain update
550 AuthorityServiceUtils.NO_CHANGE); // don't change the state of the "sas" field -we could be performing a sync or just a plain update
559 @Context Request request,
560 @Context UriInfo uriInfo,
561 @PathParam("csid") String specifier) {
562 Response result = null;
563 uriInfo = new UriInfoWrapper(uriInfo);
566 MultivaluedMap<String,String> queryParams = uriInfo.getQueryParameters();
567 String showItemsValue = (String)queryParams.getFirst(VocabularyClient.SHOW_ITEMS_QP);
568 boolean showItems = Tools.isTrue(showItemsValue);
569 if (showItems == true) {
571 // We'll honor paging params if we find any; otherwise we'll set the page size to 0 to get ALL the items
573 if (queryParams.containsKey(IClientQueryParams.PAGE_SIZE_PARAM) == false) {
574 queryParams.add(IClientQueryParams.PAGE_SIZE_PARAM, "0");
578 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(request, uriInfo);
579 PoxPayloadOut payloadout = getAuthority(ctx, request, uriInfo, specifier, showItems);
580 result = buildResponse(ctx, payloadout);
581 } catch (Exception e) {
582 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
585 if (result == null) {
586 Response response = Response.status(Response.Status.NOT_FOUND).entity(
587 "GET request failed. The requested Authority specifier:" + specifier + ": was not found.").type(
588 "text/plain").build();
589 throw new CSWebApplicationException(response);
596 public String getServiceName() {
597 return vocabularyServiceName;
601 public String getItemServiceName() {
602 return vocabularyItemServiceName;
606 public Class<VocabulariesCommon> getCommonPartClass() {
607 return VocabulariesCommon.class;
611 * @return the name of the property used to specify references for items in this type of
612 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
613 * Some types (like Vocabulary) use a separate property.
616 protected String getRefPropName() {
617 return ServiceBindingUtils.TERM_REF_PROP;
621 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
622 String result = null;
624 result = ctx.getCommonPartLabel() + ":" + AuthorityItemJAXBSchema.DISPLAY_NAME;
630 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
631 return getOrderByField(ctx);
635 * The item schema for the Vocabulary service does not support a multi-valued term list. Only authorities that support
636 * term lists need to implement this method.
639 public String getItemTermInfoGroupXPathBase() {