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;
87 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
88 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
90 import org.jboss.resteasy.util.HttpResponseCodes;
91 import org.nuxeo.ecm.core.api.DocumentModel;
92 import org.nuxeo.ecm.core.api.DocumentModelList;
93 import org.slf4j.Logger;
94 import org.slf4j.LoggerFactory;
97 * The Class AuthorityResource.
102 * @param <AuthCommon>
103 * @param <AuthItemHandler>
108 * @param <AuthCommon>
109 * @param <AuthItemHandler>
111 @Consumes("application/xml")
112 @Produces("application/xml")
113 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
114 extends NuxeoBasedResource {
116 final static String SEARCH_TYPE_TERMSTATUS = "ts";
118 protected Class<AuthCommon> authCommonClass;
119 protected Class<?> resourceClass;
120 protected String authorityCommonSchemaName;
121 protected String authorityItemCommonSchemaName;
122 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
123 final static String URN_PREFIX = "urn:cspace:";
124 final static int URN_PREFIX_LEN = URN_PREFIX.length();
125 final static String URN_PREFIX_NAME = "name(";
126 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
127 final static String URN_PREFIX_ID = "id(";
128 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
129 final static String FETCH_SHORT_ID = "_fetch_";
130 public final static String PARENT_WILDCARD = "_ALL_";
132 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
134 protected Specifier getSpecifier(String specifierIn, String method, String op) throws CSWebApplicationException {
135 if (logger.isDebugEnabled()) {
136 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
138 if (specifierIn != null) {
139 if (!specifierIn.startsWith(URN_PREFIX)) {
140 // We'll assume it is a CSID and complain if it does not match
141 return new Specifier(SpecifierForm.CSID, specifierIn);
143 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
144 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
145 if (closeParen >= 0) {
146 return new Specifier(SpecifierForm.URN_NAME,
147 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
149 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
150 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
151 if (closeParen >= 0) {
152 return new Specifier(SpecifierForm.CSID,
153 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
158 logger.error(method + ": bad or missing specifier!");
159 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
160 op + " failed on bad or missing Authority specifier").type(
161 "text/plain").build();
162 throw new CSWebApplicationException(response);
166 * Instantiates a new Authority resource.
168 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
169 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
170 this.authCommonClass = authCommonClass;
171 this.resourceClass = resourceClass;
172 this.authorityCommonSchemaName = authorityCommonSchemaName;
173 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
176 public abstract String getItemServiceName();
178 public abstract String getItemTermInfoGroupXPathBase();
181 protected String getVersionString() {
182 return "$LastChangedRevision: 2617 $";
186 public Class<AuthCommon> getCommonPartClass() {
187 return authCommonClass;
191 * Creates the item document handler.
194 * @param inAuthority the in vocabulary
196 * @return the document handler
198 * @throws Exception the exception
200 protected DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> createItemDocumentHandler(
201 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
202 String inAuthority, String parentShortIdentifier)
204 String authorityRefNameBase;
205 AuthorityItemDocumentModelHandler<?> docHandler;
207 if (parentShortIdentifier == null) {
208 authorityRefNameBase = null;
210 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
211 createServiceContext(getServiceName());
212 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
213 // Get from parent document
214 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
216 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
219 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
220 ctx.getCommonPartLabel(getItemServiceName()),
222 // FIXME - Richard and Aron think the following three lines should
223 // be in the constructor for the AuthorityItemDocumentModelHandler
224 // because all three are required fields.
225 docHandler.setInAuthority(inAuthority);
226 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
227 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
231 public String getAuthShortIdentifier(
232 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
233 throws DocumentNotFoundException, DocumentException {
234 String shortIdentifier = null;
236 AuthorityDocumentModelHandler<?> handler =
237 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
238 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
239 } catch (Exception e) {
240 if (logger.isDebugEnabled()) {
241 logger.debug("Caught exception ", e);
243 throw new DocumentException(e);
245 return shortIdentifier;
248 protected String buildAuthorityRefNameBase(
249 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
250 RefName.Authority authority = RefName.Authority.buildAuthority(ctx.getTenantName(),
251 ctx.getServiceName(),
252 null, // Only use shortId form!!!
253 shortIdentifier, null);
254 return authority.toString();
257 public static class CsidAndShortIdentifier {
259 String shortIdentifier;
262 protected String lookupParentCSID(String parentspecifier, String method,
263 String op, UriInfo uriInfo) throws Exception {
264 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(
265 parentspecifier, method, op, uriInfo);
266 return tempResult.CSID;
269 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(
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 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
292 result.CSID = parentcsid;
293 result.shortIdentifier = parentShortIdentifier;
297 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx)
298 throws DocumentException {
300 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
301 if (itemSpec.form == SpecifierForm.CSID) {
302 itemcsid = itemSpec.value;
304 String itemWhereClause = RefNameServiceUtils.buildWhereForAuthItemByName(authorityItemCommonSchemaName, itemSpec.value, parentcsid);
305 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
311 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
312 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
313 * Resource. They then call this method on that resource.
316 public DocumentModel getDocModelForAuthorityItem(CoreSessionInterface repoSession, RefName.AuthorityItem item)
317 throws Exception, DocumentNotFoundException {
321 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, item.getParentShortIdentifier());
322 // Ensure we have the right context.
323 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(item.inAuthority.resource);
325 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
326 RepositoryClientImpl client = (RepositoryClientImpl)getRepositoryClient(ctx);
327 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
329 String itemWhereClause = RefNameServiceUtils.buildWhereForAuthItemByName(authorityItemCommonSchemaName, item.getShortIdentifier(), parentcsid);
330 ctx = createServiceContext(getItemServiceName());
331 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
332 DocumentModel docModel = docWrapper.getWrappedObject();
338 public Response createAuthority(String xmlPayload) {
340 // 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
341 // transaction code to deal with a database level UNIQUE constraint violations on the 'shortidentifier' column of the vocabularies_common table.
342 // Therefore, to prevent having multiple authorities with the same shortid, we need to synchronize
343 // the code that creates new authorities. The authority document model handler will first check for authorities with the same short id before
344 // trying to create a new authority.
346 synchronized(AuthorityResource.class) {
348 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
349 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
350 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
351 String csid = getRepositoryClient(ctx).create(ctx, handler);
352 UriBuilder path = UriBuilder.fromResource(resourceClass);
353 path.path("" + csid);
354 Response response = Response.created(path.build()).build();
356 } catch (Exception e) {
357 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
364 * Synchronizes the authority and its terms with a Shared Authority Server.
366 * @param specifier either a CSID or one of the urn forms
368 * @return the authority
372 public Response synchronize(
373 @Context Request request,
375 @PathParam("csid") String csid) {
376 PoxPayloadOut result = null;
380 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
381 AuthorityDocumentModelHandler handler = (AuthorityDocumentModelHandler)createDocumentHandler(ctx);
382 specifier = getSpecifier(csid, "getAuthority", "GET");
384 getRepositoryClient(ctx).synchronize(ctx, specifier, handler);
385 result = ctx.getOutput();
387 } catch (Exception e) {
388 throw bigReThrow(e, ServiceMessages.SYNC_FAILED, csid);
391 if (result == null) {
392 Response response = Response.status(Response.Status.NOT_FOUND).entity(
393 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
394 "text/plain").build();
395 throw new CSWebApplicationException(response);
398 return Response.status(Response.Status.OK).entity(
399 "Synchronization completed, the requested Authority specifier:" + specifier.value + ": was synchronized.").type(
400 "text/plain").build();
404 * Gets the authority.
406 * @param specifier either a CSID or one of the urn forms
408 * @return the authority
414 @Context Request request,
416 @PathParam("csid") String specifier) {
417 PoxPayloadOut result = null;
419 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
420 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
422 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
423 if (spec.form == SpecifierForm.CSID) {
424 if (logger.isDebugEnabled()) {
425 logger.debug("getAuthority with csid=" + spec.value);
427 getRepositoryClient(ctx).get(ctx, spec.value, handler);
429 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
430 DocumentFilter myFilter = new NuxeoDocumentFilter(whereClause, 0, 1);
431 handler.setDocumentFilter(myFilter);
432 getRepositoryClient(ctx).get(ctx, handler);
434 result = ctx.getOutput();
436 } catch (Exception e) {
437 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
440 if (result == null) {
441 Response response = Response.status(Response.Status.NOT_FOUND).entity(
442 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
443 "text/plain").build();
444 throw new CSWebApplicationException(response);
447 return result.getBytes();
451 * Finds and populates the authority list.
455 * @return the authority list
458 @Produces("application/xml")
459 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.
460 AbstractCommonList result = null;
463 MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
464 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(uriInfo);
466 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
467 DocumentFilter myFilter = handler.getDocumentFilter();
468 // Need to make the default sort order for authority items
469 // be on the displayName field
470 String sortBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
471 if (sortBy == null || sortBy.isEmpty()) {
472 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
473 + AuthorityItemJAXBSchema.DISPLAY_NAME;
474 myFilter.setOrderByClause(qualifiedDisplayNameField);
476 String nameQ = queryParams.getFirst("refName");
478 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
480 getRepositoryClient(ctx).getFiltered(ctx, handler);
481 result = handler.getCommonPartList();
482 } catch (Exception e) {
483 throw bigReThrow(e, ServiceMessages.GET_FAILED);
492 * @param specifier the csid or id
494 * @return the multipart output
498 public byte[] updateAuthority(
499 @PathParam("csid") String specifier,
501 PoxPayloadOut result = null;
503 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
504 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
505 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
506 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
508 if (spec.form == SpecifierForm.CSID) {
511 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
512 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
514 getRepositoryClient(ctx).update(ctx, csid, handler);
515 result = ctx.getOutput();
516 } catch (Exception e) {
517 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
519 return result.getBytes();
525 * @param csid the csid
527 * @return the response
532 public Response old_deleteAuthority(@PathParam("csid") String csid) {
533 if (logger.isDebugEnabled()) {
534 logger.debug("deleteAuthority with csid=" + csid);
537 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
538 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
539 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
540 getRepositoryClient(ctx).delete(ctx, csid, handler);
541 return Response.status(HttpResponseCodes.SC_OK).build();
542 } catch (Exception e) {
543 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
550 * @param csid the csid or a URN specifier form -e.g., urn:cspace:name(OurMuseumPersonAuthority)
552 * @return the response
556 public Response deleteAuthority(
557 @Context Request request,
559 @PathParam("csid") String specifier) {
560 if (logger.isDebugEnabled()) {
561 logger.debug("deleteAuthority with specifier=" + specifier);
565 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
566 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
568 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
569 if (spec.form == SpecifierForm.CSID) {
570 if (logger.isDebugEnabled()) {
571 logger.debug("deleteAuthority with csid=" + spec.value);
573 ensureCSID(spec.value, ServiceMessages.DELETE_FAILED, "Authority.csid");
574 getRepositoryClient(ctx).delete(ctx, spec.value, handler);
576 if (logger.isDebugEnabled()) {
577 logger.debug("deleteAuthority with specifier=" + spec.value);
579 String whereClause = RefNameServiceUtils.buildWhereForAuthByName(authorityCommonSchemaName, spec.value);
580 getRepositoryClient(ctx).deleteWithWhereClause(ctx, whereClause, handler);
583 return Response.status(HttpResponseCodes.SC_OK).build();
584 } catch (Exception e) {
585 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, specifier);
590 /*************************************************************************
591 * Create an AuthorityItem - this is a sub-resource of Authority
592 * @param specifier either a CSID or one of the urn forms
593 * @return Authority item response
594 *************************************************************************/
596 @Path("{csid}/items")
597 public Response createAuthorityItem(
598 @Context ResourceMap resourceMap,
599 @Context UriInfo uriInfo,
600 @PathParam("csid") String parentspecifier,
602 Response result = null;
605 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
606 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
608 // Note: must have the parentShortId, to do the create.
609 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(parentspecifier, "createAuthorityItem", "CREATE_ITEM", null);
610 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
611 createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
612 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
613 UriBuilder path = UriBuilder.fromResource(resourceClass);
614 path.path(parent.CSID + "/items/" + itemcsid);
615 result = Response.created(path.build()).build();
616 } catch (Exception e) {
617 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
624 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
625 public byte[] getItemWorkflow(
626 @PathParam("csid") String csid,
627 @PathParam("itemcsid") String itemcsid) {
628 PoxPayloadOut result = null;
631 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
632 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
634 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
635 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
636 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
637 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
638 result = ctx.getOutput();
639 } catch (Exception e) {
640 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
642 return result.getBytes();
645 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
646 // they should be consolidated -be DRY (don't repeat yourself).
648 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
649 public byte[] updateItemWorkflowWithTransition(
650 @PathParam("csid") String csid,
651 @PathParam("itemcsid") String itemcsid,
652 @PathParam("transition") String transition) {
653 PoxPayloadOut result = null;
657 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
658 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
659 WorkflowClient.SERVICE_COMMONPART_NAME);
660 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
662 // Create a service context and document handler for the parent resource.
663 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
664 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
665 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
667 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
668 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
669 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
671 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
672 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
673 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
675 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
676 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
677 result = ctx.getOutput();
678 } catch (Exception e) {
679 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
682 return result.getBytes();
686 * Gets the authority item.
688 * @param parentspecifier either a CSID or one of the urn forms
689 * @param itemspecifier either a CSID or one of the urn forms
691 * @return the authority item
694 @Path("{csid}/items/{itemcsid}")
695 public byte[] getAuthorityItem(
696 @Context Request request,
697 @Context UriInfo uriInfo,
698 @Context ResourceMap resourceMap,
699 @PathParam("csid") String parentspecifier,
700 @PathParam("itemcsid") String itemspecifier) {
701 PoxPayloadOut result = null;
703 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", uriInfo);
705 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx =
706 (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), resourceMap, uriInfo);
708 JaxRsContext jaxRsContext = new JaxRsContext(request, uriInfo); // REM - Why are we setting this? Who is using the getter?
709 ctx.setJaxRsContext(jaxRsContext);
711 // We omit the parentShortId, only needed when doing a create...
712 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
714 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
715 if (itemSpec.form == SpecifierForm.CSID) {
716 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
718 String itemWhereClause =
719 RefNameServiceUtils.buildWhereForAuthItemByName(authorityItemCommonSchemaName, itemSpec.value, parentcsid);
720 DocumentFilter myFilter = new NuxeoDocumentFilter(itemWhereClause, 0, 1); // start at page 0 and get 1 item
721 handler.setDocumentFilter(myFilter);
722 getRepositoryClient(ctx).get(ctx, handler);
724 // TODO should we assert that the item is in the passed vocab?
725 result = ctx.getOutput();
726 } catch (Exception e) {
727 throw bigReThrow(e, ServiceMessages.GET_FAILED);
730 if (result == null) {
731 Response response = Response.status(Response.Status.NOT_FOUND).entity(
732 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
733 "text/plain").build();
734 throw new CSWebApplicationException(response);
737 return result.getBytes();
741 * Most of the authority child classes will/should use this implementation. However, the Vocabulary service's item schema is
742 * different enough that it will have to override this method in it's resource class.
745 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
746 String result = null;
748 result = NuxeoUtils.getPrimaryElPathPropertyName(
749 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
750 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
756 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
757 String result = null;
759 result = NuxeoUtils.getMultiElPathPropertyName(
760 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
761 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
767 * Gets the authorityItem list for the specified authority
768 * If partialPerm is specified, keywords will be ignored.
770 * @param specifier either a CSID or one of the urn forms
771 * @param partialTerm if non-null, matches partial terms
772 * @param keywords if non-null, matches terms in the keyword index for items
773 * @param ui passed to include additional parameters, like pagination controls
775 * @return the authorityItem list
778 @Path("{csid}/items")
779 @Produces("application/xml")
780 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
781 @Context UriInfo uriInfo) {
782 AbstractCommonList result = null;
785 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
786 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
788 String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
789 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
790 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
791 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
792 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
794 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
795 // We omit the parentShortId, only needed when doing a create...
796 String parentcsid = PARENT_WILDCARD.equals(specifier) ? null :
797 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", uriInfo);
798 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
799 createItemDocumentHandler(ctx, parentcsid, null);
801 DocumentFilter myFilter = handler.getDocumentFilter();
802 // If we are not wildcarding the parent, add a restriction
803 if (parentcsid != null) {
804 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
805 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
806 + "'" + parentcsid + "'",
807 IQueryManager.SEARCH_QUALIFIER_AND);
810 if (Tools.notBlank(termStatus)) {
811 // Start with the qualified termStatus field
812 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
813 + AuthorityItemJAXBSchema.TERM_STATUS;
814 String[] filterTerms = termStatus.trim().split("\\|");
815 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
816 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
819 result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm);
820 } catch (Exception e) {
821 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
828 * @return the name of the property used to specify references for items in this type of
829 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
830 * Some types (like Vocabulary) use a separate property.
832 protected String getRefPropName() {
833 return ServiceBindingUtils.AUTH_REF_PROP;
837 * Gets the entities referencing this Authority item instance. The service type
838 * can be passed as a query param "type", and must match a configured type
839 * for the service bindings. If not set, the type defaults to
840 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
842 * @param parentspecifier either a CSID or one of the urn forms
843 * @param itemspecifier either a CSID or one of the urn forms
846 * @return the info for the referencing objects
849 @Path("{csid}/items/{itemcsid}/refObjs")
850 @Produces("application/xml")
851 public AuthorityRefDocList getReferencingObjects(
852 @PathParam("csid") String parentspecifier,
853 @PathParam("itemcsid") String itemspecifier,
854 @Context UriTemplateRegistry uriTemplateRegistry,
855 @Context UriInfo uriInfo) {
856 AuthorityRefDocList authRefDocList = null;
858 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
859 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
861 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", uriInfo);
862 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
864 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
865 if(serviceTypes == null || serviceTypes.isEmpty()) {
866 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
869 // Note that we have to create the service context for the Items, not the main service
870 // We omit the parentShortId, only needed when doing a create...
871 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
872 createItemDocumentHandler(ctx, parentcsid, null);
874 authRefDocList = handler.getReferencingObjects(ctx, uriTemplateRegistry, serviceTypes, getRefPropName(), itemcsid);
875 } catch (Exception e) {
876 throw bigReThrow(e, ServiceMessages.GET_FAILED);
878 if (authRefDocList == null) {
879 Response response = Response.status(Response.Status.NOT_FOUND).entity(
880 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
881 "text/plain").build();
882 throw new CSWebApplicationException(response);
884 return authRefDocList;
888 * Gets the authority terms used in the indicated Authority item.
890 * @param parentspecifier either a CSID or one of the urn forms
891 * @param itemspecifier either a CSID or one of the urn forms
892 * @param ui passed to include additional parameters, like pagination controls
894 * @return the authority refs for the Authority item.
897 @Path("{csid}/items/{itemcsid}/authorityrefs")
898 @Produces("application/xml")
899 public AuthorityRefList getAuthorityItemAuthorityRefs(
900 @PathParam("csid") String parentspecifier,
901 @PathParam("itemcsid") String itemspecifier,
902 @Context UriInfo uriInfo) {
903 AuthorityRefList authRefList = null;
905 // Note that we have to create the service context for the Items, not the main service
906 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
907 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
908 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", uriInfo);
909 // We omit the parentShortId, only needed when doing a create...
910 DocumentModelHandler<?, AbstractCommonList> handler =
911 (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null /*no parent short ID*/);
913 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
915 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
916 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
917 } catch (Exception e) {
918 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
924 * Update authorityItem.
926 * @param parentspecifier either a CSID or one of the urn forms
927 * @param itemspecifier either a CSID or one of the urn forms
929 * @return the multipart output
932 @Path("{csid}/items/{itemcsid}")
933 public byte[] updateAuthorityItem(
934 @Context ResourceMap resourceMap,
935 @Context UriInfo uriInfo,
936 @PathParam("csid") String parentspecifier,
937 @PathParam("itemcsid") String itemspecifier,
939 PoxPayloadOut result = null;
941 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
942 // Note that we have to create the service context for the Items, not the main service
943 // 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
944 CsidAndShortIdentifier csidAndShortId = lookupParentCSIDAndShortIdentifer(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
945 String parentcsid = csidAndShortId.CSID;
946 String parentShortId = csidAndShortId.shortIdentifier;
948 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
949 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
951 // We omit the parentShortId, only needed when doing a create...
952 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, parentShortId);
953 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
954 result = ctx.getOutput();
956 } catch (Exception e) {
957 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
959 return result.getBytes();
963 * Delete authorityItem.
965 * @param parentcsid the parentcsid
966 * @param itemcsid the itemcsid
968 * @return the response
971 @Path("{csid}/items/{itemcsid}")
972 public Response deleteAuthorityItem(
973 @PathParam("csid") String parentcsid,
974 @PathParam("itemcsid") String itemcsid) {
976 if (logger.isDebugEnabled()) {
977 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
980 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
981 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
982 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
983 // }catch (Throwable t){
984 // System.out.println("ERROR in setting up DELETE: "+t);
987 // Note that we have to create the service context for the Items, not the main service
988 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
989 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
990 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
991 return Response.status(HttpResponseCodes.SC_OK).build();
992 } catch (Exception e) {
993 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
996 public final static String hierarchy = "hierarchy";
999 @Path("{csid}/items/{itemcsid}/" + hierarchy)
1000 @Produces("application/xml")
1001 public String getHierarchy(@PathParam("csid") String csid,
1002 @PathParam("itemcsid") String itemcsid,
1003 @Context UriInfo ui) throws Exception {
1005 // 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...?
1006 String calledUri = ui.getPath();
1007 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
1008 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), ui);
1010 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
1011 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
1012 return Hierarchy.surface(ctx, itemcsid, uri);
1014 return Hierarchy.dive(ctx, itemcsid, uri);
1016 } catch (Exception e) {
1017 throw bigReThrow(e, "Error showing hierarchy", itemcsid);
1021 protected String getItemDocType(String tenantId) {
1022 return getDocType(tenantId, getItemServiceName());
1026 * Returns a UriRegistry entry: a map of tenant-qualified URI templates
1027 * for the current resource, for all tenants
1029 * @return a map of URI templates for the current resource, for all tenants
1032 public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
1033 Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
1034 super.getUriRegistryEntries();
1035 List<String> tenantIds = getTenantBindingsReader().getTenantIds();
1036 for (String tenantId : tenantIds) {
1037 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getItemDocType(tenantId), UriTemplateFactory.ITEM));
1039 return uriRegistryEntriesMap;