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.RepositoryJavaClientImpl;
84 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
85 import org.collectionspace.services.workflow.WorkflowCommon;
86 import org.jboss.resteasy.util.HttpResponseCodes;
87 import org.nuxeo.ecm.core.api.DocumentModel;
88 import org.nuxeo.ecm.core.api.DocumentModelList;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 * The Class AuthorityResource.
99 * @param <AuthItemHandler>
104 * @param <AuthCommon>
105 * @param <AuthItemHandler>
107 @Consumes("application/xml")
108 @Produces("application/xml")
109 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
110 extends NuxeoBasedResource {
112 final static String SEARCH_TYPE_TERMSTATUS = "ts";
114 protected Class<AuthCommon> authCommonClass;
115 protected Class<?> resourceClass;
116 protected String authorityCommonSchemaName;
117 protected String authorityItemCommonSchemaName;
118 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
119 final static String URN_PREFIX = "urn:cspace:";
120 final static int URN_PREFIX_LEN = URN_PREFIX.length();
121 final static String URN_PREFIX_NAME = "name(";
122 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
123 final static String URN_PREFIX_ID = "id(";
124 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
125 final static String FETCH_SHORT_ID = "_fetch_";
126 public final static String PARENT_WILDCARD = "_ALL_";
128 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
130 public enum SpecifierForm {
135 public class Specifier {
137 public SpecifierForm form;
140 Specifier(SpecifierForm form, String value) {
146 protected Specifier getSpecifier(String specifierIn, String method, String op) throws CSWebApplicationException {
147 if (logger.isDebugEnabled()) {
148 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
150 if (specifierIn != null) {
151 if (!specifierIn.startsWith(URN_PREFIX)) {
152 // We'll assume it is a CSID and complain if it does not match
153 return new Specifier(SpecifierForm.CSID, specifierIn);
155 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
156 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
157 if (closeParen >= 0) {
158 return new Specifier(SpecifierForm.URN_NAME,
159 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
161 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
162 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
163 if (closeParen >= 0) {
164 return new Specifier(SpecifierForm.CSID,
165 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
170 logger.error(method + ": bad or missing specifier!");
171 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
172 op + " failed on bad or missing Authority specifier").type(
173 "text/plain").build();
174 throw new CSWebApplicationException(response);
178 * Instantiates a new Authority resource.
180 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
181 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
182 this.authCommonClass = authCommonClass;
183 this.resourceClass = resourceClass;
184 this.authorityCommonSchemaName = authorityCommonSchemaName;
185 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
188 public abstract String getItemServiceName();
190 public abstract String getItemTermInfoGroupXPathBase();
193 protected String getVersionString() {
194 return "$LastChangedRevision: 2617 $";
198 public Class<AuthCommon> getCommonPartClass() {
199 return authCommonClass;
203 * Creates the item document handler.
206 * @param inAuthority the in vocabulary
208 * @return the document handler
210 * @throws Exception the exception
212 protected DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> createItemDocumentHandler(
213 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
214 String inAuthority, String parentShortIdentifier)
216 String authorityRefNameBase;
217 AuthorityItemDocumentModelHandler<?> docHandler;
219 if (parentShortIdentifier == null) {
220 authorityRefNameBase = null;
222 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
223 createServiceContext(getServiceName());
224 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
225 // Get from parent document
226 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
228 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
231 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
232 ctx.getCommonPartLabel(getItemServiceName()),
234 // FIXME - Richard and Aron think the following three lines should
235 // be in the constructor for the AuthorityItemDocumentModelHandler
236 // because all three are required fields.
237 docHandler.setInAuthority(inAuthority);
238 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
239 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
243 public String getAuthShortIdentifier(
244 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
245 throws DocumentNotFoundException, DocumentException {
246 String shortIdentifier = null;
248 AuthorityDocumentModelHandler<?> handler =
249 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
250 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
251 } catch (Exception e) {
252 if (logger.isDebugEnabled()) {
253 logger.debug("Caught exception ", e);
255 throw new DocumentException(e);
257 return shortIdentifier;
260 protected String buildAuthorityRefNameBase(
261 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
262 RefName.Authority authority = RefName.Authority.buildAuthority(ctx.getTenantName(),
263 ctx.getServiceName(),
264 null, // Only use shortId form!!!
265 shortIdentifier, null);
266 return authority.toString();
269 public static class CsidAndShortIdentifier {
272 String shortIdentifier;
275 protected String lookupParentCSID(String parentspecifier, String method,
276 String op, UriInfo uriInfo) throws Exception {
277 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(
278 parentspecifier, method, op, uriInfo);
279 return tempResult.CSID;
282 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(
283 String parentspecifier,
288 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
289 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
290 // Note that we have to create the service context for the Items, not the main service
292 String parentShortIdentifier;
293 if (parentSpec.form == SpecifierForm.CSID) {
294 parentShortIdentifier = null;
295 parentcsid = parentSpec.value;
296 // Uncomment when app layer is ready to integrate
297 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
298 parentShortIdentifier = FETCH_SHORT_ID;
300 parentShortIdentifier = parentSpec.value;
301 String whereClause = buildWhereForAuthByName(parentSpec.value);
302 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getServiceName(), uriInfo);
303 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
305 result.CSID = parentcsid;
306 result.shortIdentifier = parentShortIdentifier;
310 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx)
311 throws DocumentException {
313 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
314 if (itemSpec.form == SpecifierForm.CSID) {
315 itemcsid = itemSpec.value;
317 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
318 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
324 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
325 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
326 * Resource. They then call this method on that resource.
329 public DocumentModel getDocModelForAuthorityItem(CoreSessionInterface repoSession, RefName.AuthorityItem item)
330 throws Exception, DocumentNotFoundException {
334 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
335 // Ensure we have the right context.
336 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(item.inAuthority.resource);
338 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
339 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
340 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
342 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
343 ctx = createServiceContext(getItemServiceName());
344 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
345 DocumentModel docModel = docWrapper.getWrappedObject();
351 public Response createAuthority(String xmlPayload) {
353 // 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
354 // transaction code to deal with a database level UNIQUE constraint violations on the 'shortidentifier' column of the vocabularies_common table.
355 // Therefore, to prevent having multiple authorities with the same shortid, we need to synchronize
356 // the code that creates new authorities. The authority document model handler will first check for authorities with the same short id before
357 // trying to create a new authority.
359 synchronized(AuthorityResource.class) {
361 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
362 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
363 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
364 String csid = getRepositoryClient(ctx).create(ctx, handler);
365 UriBuilder path = UriBuilder.fromResource(resourceClass);
366 path.path("" + csid);
367 Response response = Response.created(path.build()).build();
369 } catch (Exception e) {
370 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
375 protected String buildWhereForAuthByName(String name) {
376 return authorityCommonSchemaName
377 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
381 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
382 return authorityItemCommonSchemaName
383 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
384 + "='" + name + "' AND "
385 + authorityItemCommonSchemaName + ":"
386 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
387 + "'" + parentcsid + "'";
391 * Gets the authority.
393 * @param specifier either a CSID or one of the urn forms
395 * @return the authority
401 @Context Request request,
403 @PathParam("csid") String specifier) {
404 PoxPayloadOut result = null;
406 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
407 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
409 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
410 if (spec.form == SpecifierForm.CSID) {
411 if (logger.isDebugEnabled()) {
412 logger.debug("getAuthority with csid=" + spec.value);
414 getRepositoryClient(ctx).get(ctx, spec.value, handler);
416 String whereClause = buildWhereForAuthByName(spec.value);
417 DocumentFilter myFilter = new NuxeoDocumentFilter(whereClause, 0, 1);
418 handler.setDocumentFilter(myFilter);
419 getRepositoryClient(ctx).get(ctx, handler);
421 result = ctx.getOutput();
423 } catch (Exception e) {
424 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
427 if (result == null) {
428 Response response = Response.status(Response.Status.NOT_FOUND).entity(
429 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
430 "text/plain").build();
431 throw new CSWebApplicationException(response);
434 return result.getBytes();
438 * Finds and populates the authority list.
442 * @return the authority list
445 @Produces("application/xml")
446 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.
447 AbstractCommonList result = null;
450 MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
451 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(uriInfo);
453 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
454 DocumentFilter myFilter = handler.getDocumentFilter();
455 // Need to make the default sort order for authority items
456 // be on the displayName field
457 String sortBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
458 if (sortBy == null || sortBy.isEmpty()) {
459 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
460 + AuthorityItemJAXBSchema.DISPLAY_NAME;
461 myFilter.setOrderByClause(qualifiedDisplayNameField);
463 String nameQ = queryParams.getFirst("refName");
465 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
467 getRepositoryClient(ctx).getFiltered(ctx, handler);
468 result = handler.getCommonPartList();
469 } catch (Exception e) {
470 throw bigReThrow(e, ServiceMessages.GET_FAILED);
479 * @param specifier the csid or id
481 * @return the multipart output
485 public byte[] updateAuthority(
486 @PathParam("csid") String specifier,
488 PoxPayloadOut result = null;
490 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
491 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
492 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
493 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
495 if (spec.form == SpecifierForm.CSID) {
498 String whereClause = buildWhereForAuthByName(spec.value);
499 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
501 getRepositoryClient(ctx).update(ctx, csid, handler);
502 result = ctx.getOutput();
503 } catch (Exception e) {
504 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
506 return result.getBytes();
512 * @param csid the csid
514 * @return the response
519 public Response old_deleteAuthority(@PathParam("csid") String csid) {
520 if (logger.isDebugEnabled()) {
521 logger.debug("deleteAuthority with csid=" + csid);
524 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
525 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
526 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
527 getRepositoryClient(ctx).delete(ctx, csid, handler);
528 return Response.status(HttpResponseCodes.SC_OK).build();
529 } catch (Exception e) {
530 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
537 * @param csid the csid or a URN specifier form -e.g., urn:cspace:name(OurMuseumPersonAuthority)
539 * @return the response
543 public Response deleteAuthority(
544 @Context Request request,
546 @PathParam("csid") String specifier) {
547 if (logger.isDebugEnabled()) {
548 logger.debug("deleteAuthority with specifier=" + specifier);
552 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
553 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
555 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
556 if (spec.form == SpecifierForm.CSID) {
557 if (logger.isDebugEnabled()) {
558 logger.debug("deleteAuthority with csid=" + spec.value);
560 ensureCSID(spec.value, ServiceMessages.DELETE_FAILED, "Authority.csid");
561 getRepositoryClient(ctx).delete(ctx, spec.value, handler);
563 if (logger.isDebugEnabled()) {
564 logger.debug("deleteAuthority with specifier=" + spec.value);
566 String whereClause = buildWhereForAuthByName(spec.value);
567 getRepositoryClient(ctx).deleteWithWhereClause(ctx, whereClause, handler);
570 return Response.status(HttpResponseCodes.SC_OK).build();
571 } catch (Exception e) {
572 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, specifier);
577 /*************************************************************************
578 * Create an AuthorityItem - this is a sub-resource of Authority
579 * @param specifier either a CSID or one of the urn forms
580 * @return Authority item response
581 *************************************************************************/
583 @Path("{csid}/items")
584 public Response createAuthorityItem(
585 @Context ResourceMap resourceMap,
586 @Context UriInfo uriInfo,
587 @PathParam("csid") String parentspecifier,
589 Response result = null;
592 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
593 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
595 // Note: must have the parentShortId, to do the create.
596 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(parentspecifier, "createAuthorityItem", "CREATE_ITEM", null);
597 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
598 createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
599 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
600 UriBuilder path = UriBuilder.fromResource(resourceClass);
601 path.path(parent.CSID + "/items/" + itemcsid);
602 result = Response.created(path.build()).build();
603 } catch (Exception e) {
604 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
611 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
612 public byte[] getItemWorkflow(
613 @PathParam("csid") String csid,
614 @PathParam("itemcsid") String itemcsid) {
615 PoxPayloadOut result = null;
618 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
619 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
621 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
622 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
623 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
624 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
625 result = ctx.getOutput();
626 } catch (Exception e) {
627 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
629 return result.getBytes();
632 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
633 // they should be consolidated -be DRY (don't repeat yourself).
635 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
636 public byte[] updateItemWorkflowWithTransition(
637 @PathParam("csid") String csid,
638 @PathParam("itemcsid") String itemcsid,
639 @PathParam("transition") String transition) {
640 PoxPayloadOut result = null;
644 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
645 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
646 WorkflowClient.SERVICE_COMMONPART_NAME);
647 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
649 // Create a service context and document handler for the parent resource.
650 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
651 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
652 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
654 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
655 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
656 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
658 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
659 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
660 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
662 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
663 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
664 result = ctx.getOutput();
665 } catch (Exception e) {
666 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
669 return result.getBytes();
673 * Gets the authority item.
675 * @param parentspecifier either a CSID or one of the urn forms
676 * @param itemspecifier either a CSID or one of the urn forms
678 * @return the authority item
681 @Path("{csid}/items/{itemcsid}")
682 public byte[] getAuthorityItem(
683 @Context Request request,
684 @Context UriInfo uriInfo,
685 @Context ResourceMap resourceMap,
686 @PathParam("csid") String parentspecifier,
687 @PathParam("itemcsid") String itemspecifier) {
688 PoxPayloadOut result = null;
690 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", uriInfo);
692 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx =
693 (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), resourceMap, uriInfo);
695 JaxRsContext jaxRsContext = new JaxRsContext(request, uriInfo); // REM - Why are we setting this? Who is using the getter?
696 ctx.setJaxRsContext(jaxRsContext);
698 // We omit the parentShortId, only needed when doing a create...
699 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
701 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
702 if (itemSpec.form == SpecifierForm.CSID) {
703 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
705 String itemWhereClause =
706 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
707 DocumentFilter myFilter = new NuxeoDocumentFilter(itemWhereClause, 0, 1); // start at page 0 and get 1 item
708 handler.setDocumentFilter(myFilter);
709 getRepositoryClient(ctx).get(ctx, handler);
711 // TODO should we assert that the item is in the passed vocab?
712 result = ctx.getOutput();
713 } catch (Exception e) {
714 throw bigReThrow(e, ServiceMessages.GET_FAILED);
717 if (result == null) {
718 Response response = Response.status(Response.Status.NOT_FOUND).entity(
719 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
720 "text/plain").build();
721 throw new CSWebApplicationException(response);
724 return result.getBytes();
728 * Most of the authority child classes will/should use this implementation. However, the Vocabulary service's item schema is
729 * different enough that it will have to override this method in it's resource class.
732 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
733 String result = null;
735 result = NuxeoUtils.getPrimaryElPathPropertyName(
736 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
737 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
743 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
744 String result = null;
746 result = NuxeoUtils.getMultiElPathPropertyName(
747 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
748 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
754 * Gets the authorityItem list for the specified authority
755 * If partialPerm is specified, keywords will be ignored.
757 * @param specifier either a CSID or one of the urn forms
758 * @param partialTerm if non-null, matches partial terms
759 * @param keywords if non-null, matches terms in the keyword index for items
760 * @param ui passed to include additional parameters, like pagination controls
762 * @return the authorityItem list
765 @Path("{csid}/items")
766 @Produces("application/xml")
767 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
768 @Context UriInfo uriInfo) {
769 AbstractCommonList result = null;
772 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
773 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
775 String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
776 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
777 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
778 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
779 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
781 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
782 // We omit the parentShortId, only needed when doing a create...
783 String parentcsid = PARENT_WILDCARD.equals(specifier) ? null :
784 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", uriInfo);
785 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
786 createItemDocumentHandler(ctx, parentcsid, null);
788 DocumentFilter myFilter = handler.getDocumentFilter();
789 // If we are not wildcarding the parent, add a restriction
790 if (parentcsid != null) {
791 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
792 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
793 + "'" + parentcsid + "'",
794 IQueryManager.SEARCH_QUALIFIER_AND);
797 if (Tools.notBlank(termStatus)) {
798 // Start with the qualified termStatus field
799 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
800 + AuthorityItemJAXBSchema.TERM_STATUS;
801 String[] filterTerms = termStatus.trim().split("\\|");
802 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
803 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
806 result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm);
807 } catch (Exception e) {
808 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
815 * @return the name of the property used to specify references for items in this type of
816 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
817 * Some types (like Vocabulary) use a separate property.
819 protected String getRefPropName() {
820 return ServiceBindingUtils.AUTH_REF_PROP;
824 * Gets the entities referencing this Authority item instance. The service type
825 * can be passed as a query param "type", and must match a configured type
826 * for the service bindings. If not set, the type defaults to
827 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
829 * @param parentspecifier either a CSID or one of the urn forms
830 * @param itemspecifier either a CSID or one of the urn forms
833 * @return the info for the referencing objects
836 @Path("{csid}/items/{itemcsid}/refObjs")
837 @Produces("application/xml")
838 public AuthorityRefDocList getReferencingObjects(
839 @PathParam("csid") String parentspecifier,
840 @PathParam("itemcsid") String itemspecifier,
841 @Context UriTemplateRegistry uriTemplateRegistry,
842 @Context UriInfo uriInfo) {
843 AuthorityRefDocList authRefDocList = null;
845 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
846 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
848 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", uriInfo);
849 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
851 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
852 if(serviceTypes == null || serviceTypes.isEmpty()) {
853 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
856 // Note that we have to create the service context for the Items, not the main service
857 // We omit the parentShortId, only needed when doing a create...
858 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
859 createItemDocumentHandler(ctx, parentcsid, null);
861 authRefDocList = handler.getReferencingObjects(ctx, uriTemplateRegistry, serviceTypes, getRefPropName(), itemcsid);
862 } catch (Exception e) {
863 throw bigReThrow(e, ServiceMessages.GET_FAILED);
865 if (authRefDocList == null) {
866 Response response = Response.status(Response.Status.NOT_FOUND).entity(
867 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
868 "text/plain").build();
869 throw new CSWebApplicationException(response);
871 return authRefDocList;
875 * Gets the authority terms used in the indicated Authority item.
877 * @param parentspecifier either a CSID or one of the urn forms
878 * @param itemspecifier either a CSID or one of the urn forms
879 * @param ui passed to include additional parameters, like pagination controls
881 * @return the authority refs for the Authority item.
884 @Path("{csid}/items/{itemcsid}/authorityrefs")
885 @Produces("application/xml")
886 public AuthorityRefList getAuthorityItemAuthorityRefs(
887 @PathParam("csid") String parentspecifier,
888 @PathParam("itemcsid") String itemspecifier,
889 @Context UriInfo uriInfo) {
890 AuthorityRefList authRefList = null;
892 // Note that we have to create the service context for the Items, not the main service
893 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
894 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
895 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", uriInfo);
896 // We omit the parentShortId, only needed when doing a create...
897 DocumentModelHandler<?, AbstractCommonList> handler =
898 (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null /*no parent short ID*/);
900 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
902 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
903 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
904 } catch (Exception e) {
905 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
911 * Update authorityItem.
913 * @param parentspecifier either a CSID or one of the urn forms
914 * @param itemspecifier either a CSID or one of the urn forms
916 * @return the multipart output
919 @Path("{csid}/items/{itemcsid}")
920 public byte[] updateAuthorityItem(
921 @Context ResourceMap resourceMap,
922 @Context UriInfo uriInfo,
923 @PathParam("csid") String parentspecifier,
924 @PathParam("itemcsid") String itemspecifier,
926 PoxPayloadOut result = null;
928 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
929 // Note that we have to create the service context for the Items, not the main service
930 // Laramie CSPACE-3175. passing null for queryParams, because prior to this refactor, the code moved to lookupParentCSID in this instance called the version of getServiceContext() that passes null
931 CsidAndShortIdentifier csidAndShortId = lookupParentCSIDAndShortIdentifer(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
932 String parentcsid = csidAndShortId.CSID;
933 String parentShortId = csidAndShortId.shortIdentifier;
935 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
936 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
938 // We omit the parentShortId, only needed when doing a create...
939 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, parentShortId);
940 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
941 result = ctx.getOutput();
943 } catch (Exception e) {
944 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
946 return result.getBytes();
950 * Delete authorityItem.
952 * @param parentcsid the parentcsid
953 * @param itemcsid the itemcsid
955 * @return the response
958 @Path("{csid}/items/{itemcsid}")
959 public Response deleteAuthorityItem(
960 @PathParam("csid") String parentcsid,
961 @PathParam("itemcsid") String itemcsid) {
963 if (logger.isDebugEnabled()) {
964 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
967 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
968 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
969 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
970 // }catch (Throwable t){
971 // System.out.println("ERROR in setting up DELETE: "+t);
974 // Note that we have to create the service context for the Items, not the main service
975 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
976 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
977 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
978 return Response.status(HttpResponseCodes.SC_OK).build();
979 } catch (Exception e) {
980 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
983 public final static String hierarchy = "hierarchy";
986 @Path("{csid}/items/{itemcsid}/" + hierarchy)
987 @Produces("application/xml")
988 public String getHierarchy(@PathParam("csid") String csid,
989 @PathParam("itemcsid") String itemcsid,
990 @Context UriInfo ui) throws Exception {
992 // 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...?
993 String calledUri = ui.getPath();
994 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
995 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), ui);
997 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
998 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
999 return Hierarchy.surface(ctx, itemcsid, uri);
1001 return Hierarchy.dive(ctx, itemcsid, uri);
1003 } catch (Exception e) {
1004 throw bigReThrow(e, "Error showing hierarchy", itemcsid);
1008 protected String getItemDocType(String tenantId) {
1009 return getDocType(tenantId, getItemServiceName());
1013 * Returns a UriRegistry entry: a map of tenant-qualified URI templates
1014 * for the current resource, for all tenants
1016 * @return a map of URI templates for the current resource, for all tenants
1019 public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
1020 Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
1021 super.getUriRegistryEntries();
1022 List<String> tenantIds = getTenantBindingsReader().getTenantIds();
1023 for (String tenantId : tenantIds) {
1024 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getItemDocType(tenantId), UriTemplateFactory.ITEM));
1026 return uriRegistryEntriesMap;