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.common.vocabulary;
26 import java.util.List;
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.DELETE;
31 import javax.ws.rs.GET;
32 import javax.ws.rs.POST;
33 import javax.ws.rs.PUT;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.PathParam;
36 import javax.ws.rs.Produces;
37 import javax.ws.rs.core.Context;
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Request;
40 import javax.ws.rs.core.Response;
41 import javax.ws.rs.core.UriBuilder;
42 import javax.ws.rs.core.UriInfo;
44 import org.collectionspace.services.client.IClientQueryParams;
45 import org.collectionspace.services.client.IQueryManager;
46 import org.collectionspace.services.client.PoxPayloadIn;
47 import org.collectionspace.services.client.PoxPayloadOut;
48 import org.collectionspace.services.client.workflow.WorkflowClient;
49 import org.collectionspace.services.common.CSWebApplicationException;
50 import org.collectionspace.services.common.NuxeoBasedResource;
51 import org.collectionspace.services.common.ResourceMap;
52 import org.collectionspace.services.common.ServiceMain;
53 import org.collectionspace.services.common.ServiceMessages;
54 import org.collectionspace.services.common.StoredValuesUriTemplate;
55 import org.collectionspace.services.common.UriTemplateFactory;
56 import org.collectionspace.services.common.UriTemplateRegistry;
57 import org.collectionspace.services.common.UriTemplateRegistryKey;
58 import org.collectionspace.services.common.api.RefName;
59 import org.collectionspace.services.common.api.Tools;
60 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
61 import org.collectionspace.services.common.authorityref.AuthorityRefList;
62 import org.collectionspace.services.common.context.JaxRsContext;
63 import org.collectionspace.services.common.context.MultipartServiceContext;
64 import org.collectionspace.services.common.context.RemoteServiceContext;
65 import org.collectionspace.services.common.context.ServiceBindingUtils;
66 import org.collectionspace.services.common.context.ServiceContext;
67 import org.collectionspace.services.common.document.DocumentException;
68 import org.collectionspace.services.common.document.DocumentFilter;
69 import org.collectionspace.services.common.document.DocumentHandler;
70 import org.collectionspace.services.common.document.DocumentNotFoundException;
71 import org.collectionspace.services.common.document.DocumentWrapper;
72 import org.collectionspace.services.common.document.Hierarchy;
73 import org.collectionspace.services.common.query.QueryManager;
74 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
75 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
76 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
77 import org.collectionspace.services.config.ClientType;
78 import org.collectionspace.services.jaxb.AbstractCommonList;
79 import org.collectionspace.services.lifecycle.TransitionDef;
80 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
81 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
82 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentFilter;
83 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
84 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
85 import org.collectionspace.services.workflow.WorkflowCommon;
86 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
87 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
88 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
89 import org.jboss.resteasy.util.HttpResponseCodes;
90 import org.nuxeo.ecm.core.api.DocumentModel;
91 import org.nuxeo.ecm.core.api.DocumentModelList;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
96 * The Class AuthorityResource.
101 * @param <AuthCommon>
102 * @param <AuthItemHandler>
107 * @param <AuthCommon>
108 * @param <AuthItemHandler>
110 @Consumes("application/xml")
111 @Produces("application/xml")
112 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
113 extends NuxeoBasedResource {
115 final static String SEARCH_TYPE_TERMSTATUS = "ts";
117 protected Class<AuthCommon> authCommonClass;
118 protected Class<?> resourceClass;
119 protected String authorityCommonSchemaName;
120 protected String authorityItemCommonSchemaName;
121 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
122 final static String URN_PREFIX = "urn:cspace:";
123 final static int URN_PREFIX_LEN = URN_PREFIX.length();
124 final static String URN_PREFIX_NAME = "name(";
125 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
126 final static String URN_PREFIX_ID = "id(";
127 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
128 final static String FETCH_SHORT_ID = "_fetch_";
129 public final static String PARENT_WILDCARD = "_ALL_";
131 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
133 protected Specifier getSpecifier(String specifierIn, String method, String op) throws CSWebApplicationException {
134 if (logger.isDebugEnabled()) {
135 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
137 if (specifierIn != null) {
138 if (!specifierIn.startsWith(URN_PREFIX)) {
139 // We'll assume it is a CSID and complain if it does not match
140 return new Specifier(SpecifierForm.CSID, specifierIn);
142 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
143 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
144 if (closeParen >= 0) {
145 return new Specifier(SpecifierForm.URN_NAME,
146 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
148 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
149 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
150 if (closeParen >= 0) {
151 return new Specifier(SpecifierForm.CSID,
152 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
157 logger.error(method + ": bad or missing specifier!");
158 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
159 op + " failed on bad or missing Authority specifier").type(
160 "text/plain").build();
161 throw new CSWebApplicationException(response);
165 * Instantiates a new Authority resource.
167 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
168 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
169 this.authCommonClass = authCommonClass;
170 this.resourceClass = resourceClass;
171 this.authorityCommonSchemaName = authorityCommonSchemaName;
172 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
175 public abstract String getItemServiceName();
177 public abstract String getItemTermInfoGroupXPathBase();
180 protected String getVersionString() {
181 return "$LastChangedRevision: 2617 $";
185 public Class<AuthCommon> getCommonPartClass() {
186 return authCommonClass;
190 * Creates the item document handler.
193 * @param inAuthority the in vocabulary
195 * @return the document handler
197 * @throws Exception the exception
199 protected DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> createItemDocumentHandler(
200 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
201 String inAuthority, String parentShortIdentifier)
203 String authorityRefNameBase;
204 AuthorityItemDocumentModelHandler<?> docHandler;
206 if (parentShortIdentifier == null) {
207 authorityRefNameBase = null;
209 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
210 createServiceContext(getServiceName());
211 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
212 // Get from parent document
213 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
215 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
218 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
219 ctx.getCommonPartLabel(getItemServiceName()),
221 // FIXME - Richard and Aron think the following three lines should
222 // be in the constructor for the AuthorityItemDocumentModelHandler
223 // because all three are required fields.
224 docHandler.setInAuthority(inAuthority);
225 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
226 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
230 public String getAuthShortIdentifier(
231 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
232 throws DocumentNotFoundException, DocumentException {
233 String shortIdentifier = null;
235 AuthorityDocumentModelHandler<?> handler =
236 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
237 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
238 } catch (Exception e) {
239 if (logger.isDebugEnabled()) {
240 logger.debug("Caught exception ", e);
242 throw new DocumentException(e);
244 return shortIdentifier;
247 protected String buildAuthorityRefNameBase(
248 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
249 RefName.Authority authority = RefName.Authority.buildAuthority(ctx.getTenantName(),
250 ctx.getServiceName(),
251 null, // Only use shortId form!!!
252 shortIdentifier, null);
253 return authority.toString();
256 public static class CsidAndShortIdentifier {
258 String shortIdentifier;
261 protected String lookupParentCSID(String parentspecifier, String method,
262 String op, UriInfo uriInfo) throws Exception {
263 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(null,
264 parentspecifier, method, op, uriInfo);
265 return tempResult.CSID;
268 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(
269 ServiceContext itemServiceCtx,
270 String parentSpecifier,
275 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
276 Specifier parentSpec = getSpecifier(parentSpecifier, method, op);
277 // Note that we have to create the service context for the Items, not the main service
279 String parentShortIdentifier;
280 if (parentSpec.form == SpecifierForm.CSID) {
281 parentShortIdentifier = null;
282 parentcsid = parentSpec.value;
283 // Uncomment when app layer is ready to integrate
284 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
285 parentShortIdentifier = FETCH_SHORT_ID;
287 parentShortIdentifier = parentSpec.value;
288 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, parentSpec.value);
289 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getServiceName(), uriInfo);
290 CoreSessionInterface repoSession = null;
291 if (itemServiceCtx != null) {
292 repoSession = (CoreSessionInterface) itemServiceCtx.getCurrentRepositorySession(); // We want to use the thread's current repo session
294 parentcsid = getRepositoryClient(ctx).findDocCSID(repoSession, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
297 result.CSID = parentcsid;
298 result.shortIdentifier = parentShortIdentifier;
302 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx)
303 throws DocumentException {
305 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
306 if (itemSpec.form == SpecifierForm.CSID) {
307 itemcsid = itemSpec.value;
309 String itemWhereClause = RefNameServiceUtils.buildWhereForAuthItemByName(authorityItemCommonSchemaName, itemSpec.value, parentcsid);
310 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
316 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
317 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
318 * Resource. They then call this method on that resource.
321 public DocumentModel getDocModelForAuthorityItem(CoreSessionInterface repoSession, RefName.AuthorityItem item)
322 throws Exception, DocumentNotFoundException {
326 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, item.getParentShortIdentifier());
327 // Ensure we have the right context.
328 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(item.inAuthority.resource);
330 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
331 RepositoryClientImpl client = (RepositoryClientImpl)getRepositoryClient(ctx);
332 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
334 String itemWhereClause = RefNameServiceUtils.buildWhereForAuthItemByName(authorityItemCommonSchemaName, item.getShortIdentifier(), parentcsid);
335 ctx = createServiceContext(getItemServiceName());
336 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
337 DocumentModel docModel = docWrapper.getWrappedObject();
343 public Response createAuthority(String xmlPayload) {
345 // 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
346 // transaction code to deal with a database level UNIQUE constraint violations on the 'shortidentifier' column of the vocabularies_common table.
347 // Therefore, to prevent having multiple authorities with the same shortid, we need to synchronize
348 // the code that creates new authorities. The authority document model handler will first check for authorities with the same short id before
349 // trying to create a new authority.
351 synchronized(AuthorityResource.class) {
353 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
354 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
355 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
356 String csid = getRepositoryClient(ctx).create(ctx, handler);
357 UriBuilder path = UriBuilder.fromResource(resourceClass);
358 path.path("" + csid);
359 Response response = Response.created(path.build()).build();
361 } catch (Exception e) {
362 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
369 * Synchronizes the authority and its terms with a Shared Authority Server.
371 * @param specifier either a CSID or one of the urn forms
373 * @return the authority
377 public byte[] synchronize(
378 @Context Request request,
380 @PathParam("csid") String csid) {
382 boolean neededSync = false;
383 PoxPayloadOut payloadOut = null;
387 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
388 AuthorityDocumentModelHandler handler = (AuthorityDocumentModelHandler)createDocumentHandler(ctx);
389 specifier = getSpecifier(csid, "getAuthority", "GET");
390 neededSync = getRepositoryClient(ctx).synchronize(ctx, specifier, handler);
391 payloadOut = ctx.getOutput();
392 } catch (Exception e) {
393 throw bigReThrow(e, ServiceMessages.SYNC_FAILED, csid);
397 // If a sync was needed and was successful, return a copy of the updated resource. Acts like an UPDATE.
399 if (neededSync == true) {
400 result = payloadOut.getBytes();
402 result = String.format("Authority resource '%s' was already in sync with shared authority server.",
403 specifier.value).getBytes();
404 Response response = Response.status(Response.Status.NOT_MODIFIED).entity(result).type("text/plain").build();
405 throw new CSWebApplicationException(response);
412 * Gets the authority.
414 * @param specifier either a CSID or one of the urn forms
416 * @return the authority
422 @Context Request request,
424 @PathParam("csid") String specifier) {
425 PoxPayloadOut result = null;
427 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
428 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
430 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
431 if (spec.form == SpecifierForm.CSID) {
432 if (logger.isDebugEnabled()) {
433 logger.debug("getAuthority with csid=" + spec.value);
435 getRepositoryClient(ctx).get(ctx, spec.value, handler);
437 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
438 DocumentFilter myFilter = new NuxeoDocumentFilter(whereClause, 0, 1);
439 handler.setDocumentFilter(myFilter);
440 getRepositoryClient(ctx).get(ctx, handler);
442 result = ctx.getOutput();
444 } catch (Exception e) {
445 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
448 if (result == null) {
449 Response response = Response.status(Response.Status.NOT_FOUND).entity(
450 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
451 "text/plain").build();
452 throw new CSWebApplicationException(response);
455 return result.getBytes();
459 * Finds and populates the authority list.
463 * @return the authority list
466 @Produces("application/xml")
467 public AbstractCommonList getAuthorityList(@Context UriInfo uriInfo) { //FIXME - REM 5/3/2012 - This is not reachable from the JAX-RS dispatcher. Instead the equivalent method in ResourceBase is getting called.
468 AbstractCommonList result = null;
471 MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
472 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(uriInfo);
474 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
475 DocumentFilter myFilter = handler.getDocumentFilter();
476 // Need to make the default sort order for authority items
477 // be on the displayName field
478 String sortBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
479 if (sortBy == null || sortBy.isEmpty()) {
480 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
481 + AuthorityItemJAXBSchema.DISPLAY_NAME;
482 myFilter.setOrderByClause(qualifiedDisplayNameField);
484 String nameQ = queryParams.getFirst("refName");
486 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
488 getRepositoryClient(ctx).getFiltered(ctx, handler);
489 result = handler.getCommonPartList();
490 } catch (Exception e) {
491 throw bigReThrow(e, ServiceMessages.GET_FAILED);
500 * @param specifier the csid or id
502 * @return the multipart output
506 public byte[] updateAuthority(
507 @PathParam("csid") String specifier,
509 PoxPayloadOut result = null;
511 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
512 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
513 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
514 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
516 if (spec.form == SpecifierForm.CSID) {
519 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
520 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
522 getRepositoryClient(ctx).update(ctx, csid, handler);
523 result = ctx.getOutput();
524 } catch (Exception e) {
525 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
527 return result.getBytes();
533 * @param csid the csid
535 * @return the response
540 public Response old_deleteAuthority(@PathParam("csid") String csid) {
541 if (logger.isDebugEnabled()) {
542 logger.debug("deleteAuthority with csid=" + csid);
545 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
546 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
547 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
548 getRepositoryClient(ctx).delete(ctx, csid, handler);
549 return Response.status(HttpResponseCodes.SC_OK).build();
550 } catch (Exception e) {
551 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
558 * @param csid the csid or a URN specifier form -e.g., urn:cspace:name(OurMuseumPersonAuthority)
560 * @return the response
564 public Response deleteAuthority(
565 @Context Request request,
567 @PathParam("csid") String specifier) {
568 if (logger.isDebugEnabled()) {
569 logger.debug("deleteAuthority with specifier=" + specifier);
573 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
574 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
576 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
577 if (spec.form == SpecifierForm.CSID) {
578 if (logger.isDebugEnabled()) {
579 logger.debug("deleteAuthority with csid=" + spec.value);
581 ensureCSID(spec.value, ServiceMessages.DELETE_FAILED, "Authority.csid");
582 getRepositoryClient(ctx).delete(ctx, spec.value, handler);
584 if (logger.isDebugEnabled()) {
585 logger.debug("deleteAuthority with specifier=" + spec.value);
587 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
588 getRepositoryClient(ctx).deleteWithWhereClause(ctx, whereClause, handler);
591 return Response.status(HttpResponseCodes.SC_OK).build();
592 } catch (Exception e) {
593 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, specifier);
598 /*************************************************************************
599 * Create an AuthorityItem - this is a sub-resource of Authority
600 * @param specifier either a CSID or one of the urn forms
601 * @return Authority item response
602 *************************************************************************/
604 @Path("{csid}/items")
605 public Response createAuthorityItem(
606 @Context ResourceMap resourceMap,
607 @Context UriInfo uriInfo,
608 @PathParam("csid") String parentspecifier,
610 Response result = null;
613 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
614 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
616 // Note: must have the parentShortId, to do the create.
617 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(null, parentspecifier, "createAuthorityItem", "CREATE_ITEM", null);
618 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
619 createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
620 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
621 UriBuilder path = UriBuilder.fromResource(resourceClass);
622 path.path(parent.CSID + "/items/" + itemcsid);
623 result = Response.created(path.build()).build();
624 } catch (Exception e) {
625 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
632 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
633 public byte[] getItemWorkflow(
634 @PathParam("csid") String csid,
635 @PathParam("itemcsid") String itemcsid) {
636 PoxPayloadOut result = null;
639 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
640 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
642 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
643 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
644 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
645 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
646 result = ctx.getOutput();
647 } catch (Exception e) {
648 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
650 return result.getBytes();
653 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
654 // they should be consolidated -be DRY (don't repeat yourself).
656 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
657 public byte[] updateItemWorkflowWithTransition(
658 @PathParam("csid") String csid,
659 @PathParam("itemcsid") String itemcsid,
660 @PathParam("transition") String transition) {
661 PoxPayloadOut result = null;
665 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
666 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
667 WorkflowClient.SERVICE_COMMONPART_NAME);
668 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
670 // Create a service context and document handler for the parent resource.
671 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
672 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
673 ctx.setProperty(WorkflowClient.PARENT_DOCHANDLER, parentDocHandler); //added as a context param for the workflow document handler -it will call the parent's dochandler "prepareForWorkflowTranstion" method
675 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
676 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
677 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
679 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
680 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
681 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
683 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
684 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
685 result = ctx.getOutput();
686 } catch (Exception e) {
687 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
690 return result.getBytes();
694 * Gets the authority item.
696 * @param parentspecifier either a CSID or one of the urn forms
697 * @param itemspecifier either a CSID or one of the urn forms
699 * @return the authority item
702 @Path("{csid}/items/{itemcsid}")
703 public byte[] getAuthorityItem(
704 @Context Request request,
705 @Context UriInfo uriInfo,
706 @Context ResourceMap resourceMap,
707 @PathParam("csid") String parentspecifier,
708 @PathParam("itemcsid") String itemspecifier) {
709 PoxPayloadOut result = null;
711 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", uriInfo);
713 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx =
714 (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), resourceMap, uriInfo);
716 JaxRsContext jaxRsContext = new JaxRsContext(request, uriInfo); // Needed for getting account permissions part of the payload
717 ctx.setJaxRsContext(jaxRsContext);
719 // We omit the parentShortId, only needed when doing a create...
720 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
722 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
723 if (itemSpec.form == SpecifierForm.CSID) {
724 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
726 String itemWhereClause =
727 RefNameServiceUtils.buildWhereForAuthItemByName(authorityItemCommonSchemaName, itemSpec.value, parentcsid);
728 DocumentFilter myFilter = new NuxeoDocumentFilter(itemWhereClause, 0, 1); // start at page 0 and get 1 item
729 handler.setDocumentFilter(myFilter);
730 getRepositoryClient(ctx).get(ctx, handler);
732 // TODO should we assert that the item is in the passed vocab?
733 result = ctx.getOutput();
734 } catch (Exception e) {
735 throw bigReThrow(e, ServiceMessages.GET_FAILED);
738 if (result == null) {
739 Response response = Response.status(Response.Status.NOT_FOUND).entity(
740 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
741 "text/plain").build();
742 throw new CSWebApplicationException(response);
745 return result.getBytes();
749 * Most of the authority child classes will/should use this implementation. However, the Vocabulary service's item schema is
750 * different enough that it will have to override this method in it's resource class.
753 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
754 String result = null;
756 result = NuxeoUtils.getPrimaryElPathPropertyName(
757 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
758 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
764 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
765 String result = null;
767 result = NuxeoUtils.getMultiElPathPropertyName(
768 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
769 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
775 * Gets the authorityItem list for the specified authority
776 * If partialPerm is specified, keywords will be ignored.
778 * @param specifier either a CSID or one of the urn forms
779 * @param partialTerm if non-null, matches partial terms
780 * @param keywords if non-null, matches terms in the keyword index for items
781 * @param ui passed to include additional parameters, like pagination controls
783 * @return the authorityItem list
786 @Path("{csid}/items")
787 @Produces("application/xml")
788 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
789 @Context UriInfo uriInfo) {
790 AbstractCommonList result = null;
793 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
794 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
796 String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
797 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
798 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
799 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
800 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
802 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
803 // We omit the parentShortId, only needed when doing a create...
804 String parentcsid = PARENT_WILDCARD.equals(specifier) ? null :
805 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", uriInfo);
806 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
807 createItemDocumentHandler(ctx, parentcsid, null);
809 DocumentFilter myFilter = handler.getDocumentFilter();
810 // If we are not wildcarding the parent, add a restriction
811 if (parentcsid != null) {
812 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
813 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
814 + "'" + parentcsid + "'",
815 IQueryManager.SEARCH_QUALIFIER_AND);
818 if (Tools.notBlank(termStatus)) {
819 // Start with the qualified termStatus field
820 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
821 + AuthorityItemJAXBSchema.TERM_STATUS;
822 String[] filterTerms = termStatus.trim().split("\\|");
823 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
824 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
827 result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm);
828 } catch (Exception e) {
829 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
836 * @return the name of the property used to specify references for items in this type of
837 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
838 * Some types (like Vocabulary) use a separate property.
840 protected String getRefPropName() {
841 return ServiceBindingUtils.AUTH_REF_PROP;
845 * Gets the entities referencing this Authority item instance. The service type
846 * can be passed as a query param "type", and must match a configured type
847 * for the service bindings. If not set, the type defaults to
848 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
850 * @param parentspecifier either a CSID or one of the urn forms
851 * @param itemspecifier either a CSID or one of the urn forms
854 * @return the info for the referencing objects
857 @Path("{csid}/items/{itemcsid}/refObjs")
858 @Produces("application/xml")
859 public AuthorityRefDocList getReferencingObjects(
860 @PathParam("csid") String parentspecifier,
861 @PathParam("itemcsid") String itemspecifier,
862 @Context UriTemplateRegistry uriTemplateRegistry,
863 @Context UriInfo uriInfo) {
864 AuthorityRefDocList authRefDocList = null;
866 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
867 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
869 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", uriInfo);
870 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
872 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
873 if(serviceTypes == null || serviceTypes.isEmpty()) {
874 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
877 // Note that we have to create the service context for the Items, not the main service
878 // We omit the parentShortId, only needed when doing a create...
879 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
880 createItemDocumentHandler(ctx, parentcsid, null);
882 authRefDocList = handler.getReferencingObjects(ctx, uriTemplateRegistry, serviceTypes, getRefPropName(), itemcsid);
883 } catch (Exception e) {
884 throw bigReThrow(e, ServiceMessages.GET_FAILED);
886 if (authRefDocList == null) {
887 Response response = Response.status(Response.Status.NOT_FOUND).entity(
888 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
889 "text/plain").build();
890 throw new CSWebApplicationException(response);
892 return authRefDocList;
896 * Gets the authority terms used in the indicated Authority item.
898 * @param parentspecifier either a CSID or one of the urn forms
899 * @param itemspecifier either a CSID or one of the urn forms
900 * @param ui passed to include additional parameters, like pagination controls
902 * @return the authority refs for the Authority item.
905 @Path("{csid}/items/{itemcsid}/authorityrefs")
906 @Produces("application/xml")
907 public AuthorityRefList getAuthorityItemAuthorityRefs(
908 @PathParam("csid") String parentspecifier,
909 @PathParam("itemcsid") String itemspecifier,
910 @Context UriInfo uriInfo) {
911 AuthorityRefList authRefList = null;
913 // Note that we have to create the service context for the Items, not the main service
914 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
915 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
916 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", uriInfo);
917 // We omit the parentShortId, only needed when doing a create...
918 DocumentModelHandler<?, AbstractCommonList> handler =
919 (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null /*no parent short ID*/);
921 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
923 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
924 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
925 } catch (Exception e) {
926 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
932 * Synchronizes the authority and its terms with a Shared Authority Server (SAS).
934 * @param specifier either CSIDs and/or one of the urn forms
936 * @return the authority item if it was synchronized with SAS
939 @Path("{csid}/items/{itemcsid}/sync")
940 public byte[] synchronizeItem(
941 @Context ResourceMap resourceMap,
942 @Context Request request,
943 @Context UriInfo uriInfo,
944 @PathParam("csid") String parentIdentifier,
945 @PathParam("itemcsid") String itemIdentifier
948 boolean neededSync = false;
949 PoxPayloadOut payloadOut = null;
950 AuthorityItemSpecifier specifier;
951 CsidAndShortIdentifier parent;
954 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), null, resourceMap, uriInfo);
955 parent = lookupParentCSIDAndShortIdentifer(null, parentIdentifier, "syncAuthorityItem(parent)", "SYNC_ITEM", null);
956 AuthorityItemDocumentModelHandler handler = (AuthorityItemDocumentModelHandler)createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
957 Specifier parentSpecifier = getSpecifier(parent.CSID, "getAuthority", "GET");
958 Specifier itemSpecifier = getSpecifier(itemIdentifier, "getAuthorityItem", "GET");
959 specifier = new AuthorityItemSpecifier(parentSpecifier, itemSpecifier);
960 neededSync = getRepositoryClient(ctx).synchronize(ctx, specifier, handler);
961 payloadOut = ctx.getOutput();
962 } catch (Exception e) {
963 throw bigReThrow(e, ServiceMessages.SYNC_FAILED, itemIdentifier);
967 // If a sync was needed and was successful, return a copy of the updated resource. Acts like an UPDATE.
969 if (neededSync == true) {
970 result = payloadOut.getBytes();
972 result = String.format("Authority item resource '%s' was already in sync with shared authority server.",
973 itemIdentifier).getBytes();
974 Response response = Response.status(Response.Status.NOT_MODIFIED).entity(result).type("text/plain").build();
975 throw new CSWebApplicationException(response);
982 * Update authorityItem.
984 * @param parentspecifier either a CSID or one of the urn forms
985 * @param itemspecifier either a CSID or one of the urn forms
987 * @return the multipart output
990 @Path("{csid}/items/{itemcsid}")
991 public byte[] updateAuthorityItem(
992 @Context ResourceMap resourceMap,
993 @Context UriInfo uriInfo,
994 @PathParam("csid") String parentSpecifier,
995 @PathParam("itemcsid") String itemSpecifier,
997 PoxPayloadOut result = null;
1000 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
1001 result = updateAuthorityItem(null, resourceMap, uriInfo, parentSpecifier, itemSpecifier, theUpdate, true); // passing TRUE so parent authority rev num increases
1002 } catch (Exception e) {
1003 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
1006 return result.getBytes();
1009 public PoxPayloadOut updateAuthorityItem(
1010 ServiceContext itemServiceCtx, // Ok to be null
1011 ResourceMap resourceMap,
1013 String parentspecifier,
1014 String itemspecifier,
1015 PoxPayloadIn theUpdate,
1016 boolean shouldUpdateParentRev) throws Exception {
1017 PoxPayloadOut result = null;
1019 CsidAndShortIdentifier csidAndShortId = lookupParentCSIDAndShortIdentifer(itemServiceCtx, parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
1020 String parentcsid = csidAndShortId.CSID;
1021 String parentShortId = csidAndShortId.shortIdentifier;
1023 // If the itemServiceCtx context is not null, use it. Otherwise, create a new context
1025 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = itemServiceCtx;
1027 ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
1029 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx); //use itemServiceCtx if it is not null
1031 // We omit the parentShortId, only needed when doing a create...
1032 AuthorityItemDocumentModelHandler handler = (AuthorityItemDocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, parentShortId);
1033 handler.setShouldUpdateParentRevNumber(shouldUpdateParentRev);
1034 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
1035 result = ctx.getOutput();
1041 * Delete authorityItem.
1043 * @param parentcsid the parentcsid
1044 * @param itemcsid the itemcsid
1046 * @return the response
1049 @Path("{csid}/items/{itemcsid}")
1050 public Response deleteAuthorityItem(
1051 @PathParam("csid") String parentcsid,
1052 @PathParam("itemcsid") String itemcsid) {
1054 if (logger.isDebugEnabled()) {
1055 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
1058 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
1059 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
1060 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
1061 // }catch (Throwable t){
1062 // System.out.println("ERROR in setting up DELETE: "+t);
1065 // Note that we have to create the service context for the Items, not the main service
1066 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
1067 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
1068 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
1069 return Response.status(HttpResponseCodes.SC_OK).build();
1070 } catch (Exception e) {
1071 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
1074 public final static String hierarchy = "hierarchy";
1077 @Path("{csid}/items/{itemcsid}/" + hierarchy)
1078 @Produces("application/xml")
1079 public String getHierarchy(@PathParam("csid") String csid,
1080 @PathParam("itemcsid") String itemcsid,
1081 @Context UriInfo ui) throws Exception {
1083 // All items in dive can look at their child uri's to get uri. So we calculate the very first one. We could also do a GET and look at the common part uri field, but why...?
1084 String calledUri = ui.getPath();
1085 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
1086 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), ui);
1088 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
1089 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
1090 return Hierarchy.surface(ctx, itemcsid, uri);
1092 return Hierarchy.dive(ctx, itemcsid, uri);
1094 } catch (Exception e) {
1095 throw bigReThrow(e, "Error showing hierarchy", itemcsid);
1099 protected String getItemDocType(String tenantId) {
1100 return getDocType(tenantId, getItemServiceName());
1104 * Returns a UriRegistry entry: a map of tenant-qualified URI templates
1105 * for the current resource, for all tenants
1107 * @return a map of URI templates for the current resource, for all tenants
1110 public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
1111 Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
1112 super.getUriRegistryEntries();
1113 List<String> tenantIds = getTenantBindingsReader().getTenantIds();
1114 for (String tenantId : tenantIds) {
1115 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getItemDocType(tenantId), UriTemplateFactory.ITEM));
1117 return uriRegistryEntriesMap;