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.WebApplicationException;
38 import javax.ws.rs.core.Context;
39 import javax.ws.rs.core.MultivaluedMap;
40 import javax.ws.rs.core.Request;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.UriBuilder;
43 import javax.ws.rs.core.UriInfo;
45 import org.collectionspace.services.client.IClientQueryParams;
46 import org.collectionspace.services.client.IQueryManager;
47 import org.collectionspace.services.client.PoxPayloadIn;
48 import org.collectionspace.services.client.PoxPayloadOut;
49 import org.collectionspace.services.client.workflow.WorkflowClient;
50 import org.collectionspace.services.common.CSWebApplicationException;
51 import org.collectionspace.services.common.ResourceBase;
52 import org.collectionspace.services.common.ResourceMap;
53 import org.collectionspace.services.common.ServiceMain;
54 import org.collectionspace.services.common.ServiceMessages;
55 import org.collectionspace.services.common.StoredValuesUriTemplate;
56 import org.collectionspace.services.common.UriTemplateFactory;
57 import org.collectionspace.services.common.UriTemplateRegistry;
58 import org.collectionspace.services.common.UriTemplateRegistryKey;
59 import org.collectionspace.services.common.api.RefName;
60 import org.collectionspace.services.common.api.Tools;
61 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
62 import org.collectionspace.services.common.authorityref.AuthorityRefList;
63 import org.collectionspace.services.common.context.JaxRsContext;
64 import org.collectionspace.services.common.context.MultipartServiceContext;
65 import org.collectionspace.services.common.context.RemoteServiceContext;
66 import org.collectionspace.services.common.context.ServiceBindingUtils;
67 import org.collectionspace.services.common.context.ServiceContext;
68 import org.collectionspace.services.common.document.DocumentException;
69 import org.collectionspace.services.common.document.DocumentFilter;
70 import org.collectionspace.services.common.document.DocumentHandler;
71 import org.collectionspace.services.common.document.DocumentNotFoundException;
72 import org.collectionspace.services.common.document.DocumentWrapper;
73 import org.collectionspace.services.common.document.Hierarchy;
74 import org.collectionspace.services.common.query.QueryManager;
75 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
76 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
77 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
78 import org.collectionspace.services.config.ClientType;
79 import org.collectionspace.services.jaxb.AbstractCommonList;
80 import org.collectionspace.services.lifecycle.TransitionDef;
81 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
82 import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface;
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.nuxeo.ecm.core.api.repository.RepositoryInstance;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
94 * The Class AuthorityResource.
100 * @param <AuthItemHandler>
105 * @param <AuthCommon>
106 * @param <AuthItemHandler>
108 @Consumes("application/xml")
109 @Produces("application/xml")
110 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
111 extends ResourceBase {
113 final static String SEARCH_TYPE_TERMSTATUS = "ts";
115 protected Class<AuthCommon> authCommonClass;
116 protected Class<?> resourceClass;
117 protected String authorityCommonSchemaName;
118 protected String authorityItemCommonSchemaName;
119 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
120 final static String URN_PREFIX = "urn:cspace:";
121 final static int URN_PREFIX_LEN = URN_PREFIX.length();
122 final static String URN_PREFIX_NAME = "name(";
123 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
124 final static String URN_PREFIX_ID = "id(";
125 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
126 final static String FETCH_SHORT_ID = "_fetch_";
127 public final static String PARENT_WILDCARD = "_ALL_";
129 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
131 public enum SpecifierForm {
136 public class Specifier {
138 public SpecifierForm form;
141 Specifier(SpecifierForm form, String value) {
147 protected Specifier getSpecifier(String specifierIn, String method, String op) throws CSWebApplicationException {
148 if (logger.isDebugEnabled()) {
149 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
151 if (specifierIn != null) {
152 if (!specifierIn.startsWith(URN_PREFIX)) {
153 // We'll assume it is a CSID and complain if it does not match
154 return new Specifier(SpecifierForm.CSID, specifierIn);
156 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
157 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
158 if (closeParen >= 0) {
159 return new Specifier(SpecifierForm.URN_NAME,
160 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
162 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
163 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
164 if (closeParen >= 0) {
165 return new Specifier(SpecifierForm.CSID,
166 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
171 logger.error(method + ": bad or missing specifier!");
172 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
173 op + " failed on bad or missing Authority specifier").type(
174 "text/plain").build();
175 throw new CSWebApplicationException(response);
179 * Instantiates a new Authority resource.
181 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
182 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
183 this.authCommonClass = authCommonClass;
184 this.resourceClass = resourceClass;
185 this.authorityCommonSchemaName = authorityCommonSchemaName;
186 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
189 public abstract String getItemServiceName();
191 public abstract String getItemTermInfoGroupXPathBase();
194 protected String getVersionString() {
195 return "$LastChangedRevision: 2617 $";
199 public Class<AuthCommon> getCommonPartClass() {
200 return authCommonClass;
204 * Creates the item document handler.
207 * @param inAuthority the in vocabulary
209 * @return the document handler
211 * @throws Exception the exception
213 protected DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> createItemDocumentHandler(
214 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
215 String inAuthority, String parentShortIdentifier)
217 String authorityRefNameBase;
218 AuthorityItemDocumentModelHandler<?> docHandler;
220 if (parentShortIdentifier == null) {
221 authorityRefNameBase = null;
223 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
224 createServiceContext(getServiceName());
225 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
226 // Get from parent document
227 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
229 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
232 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
233 ctx.getCommonPartLabel(getItemServiceName()),
235 // FIXME - Richard and Aron think the following three lines should
236 // be in the constructor for the AuthorityItemDocumentModelHandler
237 // because all three are required fields.
238 docHandler.setInAuthority(inAuthority);
239 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
240 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
244 public String getAuthShortIdentifier(
245 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
246 throws DocumentNotFoundException, DocumentException {
247 String shortIdentifier = null;
249 AuthorityDocumentModelHandler<?> handler =
250 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
251 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
252 } catch (Exception e) {
253 if (logger.isDebugEnabled()) {
254 logger.debug("Caught exception ", e);
256 throw new DocumentException(e);
258 return shortIdentifier;
261 protected String buildAuthorityRefNameBase(
262 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
263 RefName.Authority authority = RefName.Authority.buildAuthority(ctx.getTenantName(),
264 ctx.getServiceName(),
265 null, // Only use shortId form!!!
266 shortIdentifier, null);
267 return authority.toString();
270 public static class CsidAndShortIdentifier {
273 String shortIdentifier;
276 protected String lookupParentCSID(String parentspecifier, String method,
277 String op, UriInfo uriInfo) throws Exception {
278 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(
279 parentspecifier, method, op, uriInfo);
280 return tempResult.CSID;
283 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(
284 String parentspecifier,
289 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
290 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
291 // Note that we have to create the service context for the Items, not the main service
293 String parentShortIdentifier;
294 if (parentSpec.form == SpecifierForm.CSID) {
295 parentShortIdentifier = null;
296 parentcsid = parentSpec.value;
297 // Uncomment when app layer is ready to integrate
298 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
299 parentShortIdentifier = FETCH_SHORT_ID;
301 parentShortIdentifier = parentSpec.value;
302 String whereClause = buildWhereForAuthByName(parentSpec.value);
303 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getServiceName(), uriInfo);
304 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
306 result.CSID = parentcsid;
307 result.shortIdentifier = parentShortIdentifier;
311 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx)
312 throws DocumentException {
314 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
315 if (itemSpec.form == SpecifierForm.CSID) {
316 itemcsid = itemSpec.value;
318 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
319 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
325 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
326 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
327 * Resource. They then call this method on that resource.
330 public DocumentModel getDocModelForAuthorityItem(RepositoryInstanceInterface repoSession, RefName.AuthorityItem item)
331 throws Exception, DocumentNotFoundException {
335 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
336 // Ensure we have the right context.
337 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(item.inAuthority.resource);
339 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
340 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
341 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
343 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
344 ctx = createServiceContext(getItemServiceName());
345 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
346 DocumentModel docModel = docWrapper.getWrappedObject();
351 @POST //FIXME: REM - 5/1/2012 - We can probably remove this method.
352 public Response createAuthority(String xmlPayload) { //REM - This method is never reached by the JAX-RS client -instead the "create" method in ResourceBase.java is getting called.
354 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
355 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
356 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
357 String csid = getRepositoryClient(ctx).create(ctx, handler);
358 UriBuilder path = UriBuilder.fromResource(resourceClass);
359 path.path("" + csid);
360 Response response = Response.created(path.build()).build();
362 } catch (Exception e) {
363 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
367 protected String buildWhereForAuthByName(String name) {
368 return authorityCommonSchemaName
369 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
373 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
374 return authorityItemCommonSchemaName
375 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
376 + "='" + name + "' AND "
377 + authorityItemCommonSchemaName + ":"
378 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
379 + "'" + parentcsid + "'";
383 * Gets the authority.
385 * @param specifier either a CSID or one of the urn forms
387 * @return the authority
393 @Context Request request,
395 @PathParam("csid") String specifier) {
396 PoxPayloadOut result = null;
398 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
399 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
401 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
402 if (spec.form == SpecifierForm.CSID) {
403 if (logger.isDebugEnabled()) {
404 logger.debug("getAuthority with csid=" + spec.value);
406 getRepositoryClient(ctx).get(ctx, spec.value, handler);
408 String whereClause = buildWhereForAuthByName(spec.value);
409 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
410 handler.setDocumentFilter(myFilter);
411 getRepositoryClient(ctx).get(ctx, handler);
413 result = ctx.getOutput();
415 } catch (Exception e) {
416 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
419 if (result == null) {
420 Response response = Response.status(Response.Status.NOT_FOUND).entity(
421 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
422 "text/plain").build();
423 throw new CSWebApplicationException(response);
426 return result.getBytes();
430 * Finds and populates the authority list.
434 * @return the authority list
437 @Produces("application/xml")
438 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.
439 AbstractCommonList result = null;
442 MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
443 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(uriInfo);
445 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
446 DocumentFilter myFilter = handler.getDocumentFilter();
447 // Need to make the default sort order for authority items
448 // be on the displayName field
449 String sortBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
450 if (sortBy == null || sortBy.isEmpty()) {
451 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
452 + AuthorityItemJAXBSchema.DISPLAY_NAME;
453 myFilter.setOrderByClause(qualifiedDisplayNameField);
455 String nameQ = queryParams.getFirst("refName");
457 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
459 getRepositoryClient(ctx).getFiltered(ctx, handler);
460 result = handler.getCommonPartList();
461 } catch (Exception e) {
462 throw bigReThrow(e, ServiceMessages.GET_FAILED);
471 * @param specifier the csid or id
473 * @return the multipart output
477 public byte[] updateAuthority(
478 @PathParam("csid") String specifier,
480 PoxPayloadOut result = null;
482 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
483 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
484 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
485 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
487 if (spec.form == SpecifierForm.CSID) {
490 String whereClause = buildWhereForAuthByName(spec.value);
491 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
493 getRepositoryClient(ctx).update(ctx, csid, handler);
494 result = ctx.getOutput();
495 } catch (Exception e) {
496 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
498 return result.getBytes();
504 * @param csid the csid
506 * @return the response
510 public Response deleteAuthority(@PathParam("csid") String csid) {
511 if (logger.isDebugEnabled()) {
512 logger.debug("deleteAuthority with csid=" + csid);
515 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
516 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
517 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
518 getRepositoryClient(ctx).delete(ctx, csid, handler);
519 return Response.status(HttpResponseCodes.SC_OK).build();
520 } catch (Exception e) {
521 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
525 /*************************************************************************
526 * Create an AuthorityItem - this is a sub-resource of Authority
527 * @param specifier either a CSID or one of the urn forms
528 * @return Authority item response
529 *************************************************************************/
531 @Path("{csid}/items")
532 public Response createAuthorityItem(
533 @Context ResourceMap resourceMap,
534 @Context UriInfo uriInfo,
535 @PathParam("csid") String parentspecifier,
537 Response result = null;
540 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
541 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
543 // Note: must have the parentShortId, to do the create.
544 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(parentspecifier, "createAuthorityItem", "CREATE_ITEM", null);
545 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
546 createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
547 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
548 UriBuilder path = UriBuilder.fromResource(resourceClass);
549 path.path(parent.CSID + "/items/" + itemcsid);
550 result = Response.created(path.build()).build();
551 } catch (Exception e) {
552 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
559 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
560 public byte[] getItemWorkflow(
561 @PathParam("csid") String csid,
562 @PathParam("itemcsid") String itemcsid) {
563 PoxPayloadOut result = null;
566 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
567 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
569 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
570 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
571 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
572 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
573 result = ctx.getOutput();
574 } catch (Exception e) {
575 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
577 return result.getBytes();
580 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
581 // they should be consolidated -be DRY (don't repeat yourself).
583 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
584 public byte[] updateItemWorkflowWithTransition(
585 @PathParam("csid") String csid,
586 @PathParam("itemcsid") String itemcsid,
587 @PathParam("transition") String transition) {
588 PoxPayloadOut result = null;
592 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
593 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
594 WorkflowClient.SERVICE_COMMONPART_NAME);
595 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
597 // Create a service context and document handler for the parent resource.
598 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
599 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
600 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
602 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
603 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
604 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
606 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
607 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
608 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
610 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
611 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
612 result = ctx.getOutput();
613 } catch (Exception e) {
614 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
617 return result.getBytes();
621 * Gets the authority item.
623 * @param parentspecifier either a CSID or one of the urn forms
624 * @param itemspecifier either a CSID or one of the urn forms
626 * @return the authority item
629 @Path("{csid}/items/{itemcsid}")
630 public byte[] getAuthorityItem(
631 @Context Request request,
632 @Context UriInfo uriInfo,
633 @Context ResourceMap resourceMap,
634 @PathParam("csid") String parentspecifier,
635 @PathParam("itemcsid") String itemspecifier) {
636 PoxPayloadOut result = null;
638 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", uriInfo);
640 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx =
641 (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), resourceMap, uriInfo);
643 JaxRsContext jaxRsContext = new JaxRsContext(request, uriInfo); // REM - Why are we setting this? Who is using the getter?
644 ctx.setJaxRsContext(jaxRsContext);
646 // We omit the parentShortId, only needed when doing a create...
647 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
649 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
650 if (itemSpec.form == SpecifierForm.CSID) {
651 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
653 String itemWhereClause =
654 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
655 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
656 handler.setDocumentFilter(myFilter);
657 getRepositoryClient(ctx).get(ctx, handler);
659 // TODO should we assert that the item is in the passed vocab?
660 result = ctx.getOutput();
661 } catch (Exception e) {
662 throw bigReThrow(e, ServiceMessages.GET_FAILED);
665 if (result == null) {
666 Response response = Response.status(Response.Status.NOT_FOUND).entity(
667 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
668 "text/plain").build();
669 throw new CSWebApplicationException(response);
672 return result.getBytes();
676 * Most of the authority child classes will/should use this implementation. However, the Vocabulary service's item schema is
677 * different enough that it will have to override this method in it's resource class.
680 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
681 String result = null;
683 result = NuxeoUtils.getPrimaryElPathPropertyName(
684 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
685 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
691 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
692 String result = null;
694 result = NuxeoUtils.getMultiElPathPropertyName(
695 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
696 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
702 * Gets the authorityItem list for the specified authority
703 * If partialPerm is specified, keywords will be ignored.
705 * @param specifier either a CSID or one of the urn forms
706 * @param partialTerm if non-null, matches partial terms
707 * @param keywords if non-null, matches terms in the keyword index for items
708 * @param ui passed to include additional parameters, like pagination controls
710 * @return the authorityItem list
713 @Path("{csid}/items")
714 @Produces("application/xml")
715 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
716 @Context UriInfo uriInfo) {
717 AbstractCommonList result = null;
720 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
721 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
723 String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
724 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
725 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
726 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
727 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
729 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
730 // We omit the parentShortId, only needed when doing a create...
731 String parentcsid = PARENT_WILDCARD.equals(specifier) ? null :
732 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", uriInfo);
733 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
734 createItemDocumentHandler(ctx, parentcsid, null);
736 DocumentFilter myFilter = handler.getDocumentFilter();
737 // If we are not wildcarding the parent, add a restriction
738 if (parentcsid != null) {
739 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
740 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
741 + "'" + parentcsid + "'",
742 IQueryManager.SEARCH_QUALIFIER_AND);
745 if (Tools.notBlank(termStatus)) {
746 // Start with the qualified termStatus field
747 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
748 + AuthorityItemJAXBSchema.TERM_STATUS;
749 String[] filterTerms = termStatus.trim().split("\\|");
750 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
751 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
754 result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm);
755 } catch (Exception e) {
756 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
763 * @return the name of the property used to specify references for items in this type of
764 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
765 * Some types (like Vocabulary) use a separate property.
767 protected String getRefPropName() {
768 return ServiceBindingUtils.AUTH_REF_PROP;
772 * Gets the entities referencing this Authority item instance. The service type
773 * can be passed as a query param "type", and must match a configured type
774 * for the service bindings. If not set, the type defaults to
775 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
777 * @param parentspecifier either a CSID or one of the urn forms
778 * @param itemspecifier either a CSID or one of the urn forms
781 * @return the info for the referencing objects
784 @Path("{csid}/items/{itemcsid}/refObjs")
785 @Produces("application/xml")
786 public AuthorityRefDocList getReferencingObjects(
787 @PathParam("csid") String parentspecifier,
788 @PathParam("itemcsid") String itemspecifier,
789 @Context UriTemplateRegistry uriTemplateRegistry,
790 @Context UriInfo uriInfo) {
791 AuthorityRefDocList authRefDocList = null;
793 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
794 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
796 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", uriInfo);
797 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
799 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
800 if(serviceTypes == null || serviceTypes.isEmpty()) {
801 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
804 // Note that we have to create the service context for the Items, not the main service
805 // We omit the parentShortId, only needed when doing a create...
806 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
807 createItemDocumentHandler(ctx, parentcsid, null);
809 authRefDocList = handler.getReferencingObjects(ctx, uriTemplateRegistry, serviceTypes, getRefPropName(), itemcsid);
810 } catch (Exception e) {
811 throw bigReThrow(e, ServiceMessages.GET_FAILED);
813 if (authRefDocList == null) {
814 Response response = Response.status(Response.Status.NOT_FOUND).entity(
815 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
816 "text/plain").build();
817 throw new CSWebApplicationException(response);
819 return authRefDocList;
823 * Gets the authority terms used in the indicated Authority item.
825 * @param parentspecifier either a CSID or one of the urn forms
826 * @param itemspecifier either a CSID or one of the urn forms
827 * @param ui passed to include additional parameters, like pagination controls
829 * @return the authority refs for the Authority item.
832 @Path("{csid}/items/{itemcsid}/authorityrefs")
833 @Produces("application/xml")
834 public AuthorityRefList getAuthorityItemAuthorityRefs(
835 @PathParam("csid") String parentspecifier,
836 @PathParam("itemcsid") String itemspecifier,
837 @Context UriInfo uriInfo) {
838 AuthorityRefList authRefList = null;
840 // Note that we have to create the service context for the Items, not the main service
841 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
842 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
843 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", uriInfo);
844 // We omit the parentShortId, only needed when doing a create...
845 DocumentModelHandler<?, AbstractCommonList> handler =
846 (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null /*no parent short ID*/);
848 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
850 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
851 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
852 } catch (Exception e) {
853 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
859 * Update authorityItem.
861 * @param parentspecifier either a CSID or one of the urn forms
862 * @param itemspecifier either a CSID or one of the urn forms
864 * @return the multipart output
867 @Path("{csid}/items/{itemcsid}")
868 public byte[] updateAuthorityItem(
869 @Context ResourceMap resourceMap,
870 @Context UriInfo uriInfo,
871 @PathParam("csid") String parentspecifier,
872 @PathParam("itemcsid") String itemspecifier,
874 PoxPayloadOut result = null;
876 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
877 // Note that we have to create the service context for the Items, not the main service
878 // 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
879 CsidAndShortIdentifier csidAndShortId = lookupParentCSIDAndShortIdentifer(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
880 String parentcsid = csidAndShortId.CSID;
881 String parentShortId = csidAndShortId.shortIdentifier;
883 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
884 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
886 // We omit the parentShortId, only needed when doing a create...
887 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, parentShortId);
888 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
889 result = ctx.getOutput();
891 } catch (Exception e) {
892 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
894 return result.getBytes();
898 * Delete authorityItem.
900 * @param parentcsid the parentcsid
901 * @param itemcsid the itemcsid
903 * @return the response
906 @Path("{csid}/items/{itemcsid}")
907 public Response deleteAuthorityItem(
908 @PathParam("csid") String parentcsid,
909 @PathParam("itemcsid") String itemcsid) {
911 if (logger.isDebugEnabled()) {
912 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
915 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
916 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
917 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
918 // }catch (Throwable t){
919 // System.out.println("ERROR in setting up DELETE: "+t);
922 // Note that we have to create the service context for the Items, not the main service
923 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
924 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
925 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
926 return Response.status(HttpResponseCodes.SC_OK).build();
927 } catch (Exception e) {
928 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
931 public final static String hierarchy = "hierarchy";
934 @Path("{csid}/items/{itemcsid}/" + hierarchy)
935 @Produces("application/xml")
936 public String getHierarchy(@PathParam("csid") String csid,
937 @PathParam("itemcsid") String itemcsid,
938 @Context UriInfo ui) throws Exception {
940 // 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...?
941 String calledUri = ui.getPath();
942 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
943 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), ui);
945 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
946 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
947 return Hierarchy.surface(ctx, itemcsid, uri);
949 return Hierarchy.dive(ctx, itemcsid, uri);
951 } catch (Exception e) {
952 throw bigReThrow(e, "Error showing hierarchy", itemcsid);
956 protected String getItemDocType(String tenantId) {
957 return getDocType(tenantId, getItemServiceName());
961 * Returns a UriRegistry entry: a map of tenant-qualified URI templates
962 * for the current resource, for all tenants
964 * @return a map of URI templates for the current resource, for all tenants
967 public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
968 Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
969 super.getUriRegistryEntries();
970 List<String> tenantIds = getTenantBindingsReader().getTenantIds();
971 for (String tenantId : tenantIds) {
972 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getItemDocType(tenantId), UriTemplateFactory.ITEM));
974 return uriRegistryEntriesMap;