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.RepositoryJavaClientImpl;
83 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
84 import org.collectionspace.services.workflow.WorkflowCommon;
85 import org.jboss.resteasy.util.HttpResponseCodes;
86 import org.nuxeo.ecm.core.api.DocumentModel;
87 import org.nuxeo.ecm.core.api.DocumentModelList;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
92 * The Class AuthorityResource.
98 * @param <AuthItemHandler>
103 * @param <AuthCommon>
104 * @param <AuthItemHandler>
106 @Consumes("application/xml")
107 @Produces("application/xml")
108 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
109 extends NuxeoBasedResource {
111 final static String SEARCH_TYPE_TERMSTATUS = "ts";
113 protected Class<AuthCommon> authCommonClass;
114 protected Class<?> resourceClass;
115 protected String authorityCommonSchemaName;
116 protected String authorityItemCommonSchemaName;
117 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
118 final static String URN_PREFIX = "urn:cspace:";
119 final static int URN_PREFIX_LEN = URN_PREFIX.length();
120 final static String URN_PREFIX_NAME = "name(";
121 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
122 final static String URN_PREFIX_ID = "id(";
123 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
124 final static String FETCH_SHORT_ID = "_fetch_";
125 public final static String PARENT_WILDCARD = "_ALL_";
127 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
129 public enum SpecifierForm {
134 public class Specifier {
136 public SpecifierForm form;
139 Specifier(SpecifierForm form, String value) {
145 protected Specifier getSpecifier(String specifierIn, String method, String op) throws CSWebApplicationException {
146 if (logger.isDebugEnabled()) {
147 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
149 if (specifierIn != null) {
150 if (!specifierIn.startsWith(URN_PREFIX)) {
151 // We'll assume it is a CSID and complain if it does not match
152 return new Specifier(SpecifierForm.CSID, specifierIn);
154 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
155 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
156 if (closeParen >= 0) {
157 return new Specifier(SpecifierForm.URN_NAME,
158 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
160 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
161 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
162 if (closeParen >= 0) {
163 return new Specifier(SpecifierForm.CSID,
164 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
169 logger.error(method + ": bad or missing specifier!");
170 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
171 op + " failed on bad or missing Authority specifier").type(
172 "text/plain").build();
173 throw new CSWebApplicationException(response);
177 * Instantiates a new Authority resource.
179 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
180 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
181 this.authCommonClass = authCommonClass;
182 this.resourceClass = resourceClass;
183 this.authorityCommonSchemaName = authorityCommonSchemaName;
184 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
187 public abstract String getItemServiceName();
189 public abstract String getItemTermInfoGroupXPathBase();
192 protected String getVersionString() {
193 return "$LastChangedRevision: 2617 $";
197 public Class<AuthCommon> getCommonPartClass() {
198 return authCommonClass;
202 * Creates the item document handler.
205 * @param inAuthority the in vocabulary
207 * @return the document handler
209 * @throws Exception the exception
211 protected DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> createItemDocumentHandler(
212 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
213 String inAuthority, String parentShortIdentifier)
215 String authorityRefNameBase;
216 AuthorityItemDocumentModelHandler<?> docHandler;
218 if (parentShortIdentifier == null) {
219 authorityRefNameBase = null;
221 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
222 createServiceContext(getServiceName());
223 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
224 // Get from parent document
225 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
227 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
230 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
231 ctx.getCommonPartLabel(getItemServiceName()),
233 // FIXME - Richard and Aron think the following three lines should
234 // be in the constructor for the AuthorityItemDocumentModelHandler
235 // because all three are required fields.
236 docHandler.setInAuthority(inAuthority);
237 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
238 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
242 public String getAuthShortIdentifier(
243 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
244 throws DocumentNotFoundException, DocumentException {
245 String shortIdentifier = null;
247 AuthorityDocumentModelHandler<?> handler =
248 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
249 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
250 } catch (Exception e) {
251 if (logger.isDebugEnabled()) {
252 logger.debug("Caught exception ", e);
254 throw new DocumentException(e);
256 return shortIdentifier;
259 protected String buildAuthorityRefNameBase(
260 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
261 RefName.Authority authority = RefName.Authority.buildAuthority(ctx.getTenantName(),
262 ctx.getServiceName(),
263 null, // Only use shortId form!!!
264 shortIdentifier, null);
265 return authority.toString();
268 public static class CsidAndShortIdentifier {
271 String shortIdentifier;
274 protected String lookupParentCSID(String parentspecifier, String method,
275 String op, UriInfo uriInfo) throws Exception {
276 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(
277 parentspecifier, method, op, uriInfo);
278 return tempResult.CSID;
281 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(
282 String parentspecifier,
287 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
288 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
289 // Note that we have to create the service context for the Items, not the main service
291 String parentShortIdentifier;
292 if (parentSpec.form == SpecifierForm.CSID) {
293 parentShortIdentifier = null;
294 parentcsid = parentSpec.value;
295 // Uncomment when app layer is ready to integrate
296 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
297 parentShortIdentifier = FETCH_SHORT_ID;
299 parentShortIdentifier = parentSpec.value;
300 String whereClause = buildWhereForAuthByName(parentSpec.value);
301 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getServiceName(), uriInfo);
302 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
304 result.CSID = parentcsid;
305 result.shortIdentifier = parentShortIdentifier;
309 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx)
310 throws DocumentException {
312 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
313 if (itemSpec.form == SpecifierForm.CSID) {
314 itemcsid = itemSpec.value;
316 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
317 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
323 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
324 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
325 * Resource. They then call this method on that resource.
328 public DocumentModel getDocModelForAuthorityItem(CoreSessionInterface repoSession, RefName.AuthorityItem item)
329 throws Exception, DocumentNotFoundException {
333 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
334 // Ensure we have the right context.
335 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(item.inAuthority.resource);
337 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
338 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
339 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
341 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
342 ctx = createServiceContext(getItemServiceName());
343 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
344 DocumentModel docModel = docWrapper.getWrappedObject();
349 @POST //FIXME: REM - 5/1/2012 - We can probably remove this method.
350 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.
352 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
353 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
354 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
355 String csid = getRepositoryClient(ctx).create(ctx, handler);
356 UriBuilder path = UriBuilder.fromResource(resourceClass);
357 path.path("" + csid);
358 Response response = Response.created(path.build()).build();
360 } catch (Exception e) {
361 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
365 protected String buildWhereForAuthByName(String name) {
366 return authorityCommonSchemaName
367 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
371 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
372 return authorityItemCommonSchemaName
373 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
374 + "='" + name + "' AND "
375 + authorityItemCommonSchemaName + ":"
376 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
377 + "'" + parentcsid + "'";
381 * Gets the authority.
383 * @param specifier either a CSID or one of the urn forms
385 * @return the authority
391 @Context Request request,
393 @PathParam("csid") String specifier) {
394 PoxPayloadOut result = null;
396 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
397 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
399 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
400 if (spec.form == SpecifierForm.CSID) {
401 if (logger.isDebugEnabled()) {
402 logger.debug("getAuthority with csid=" + spec.value);
404 getRepositoryClient(ctx).get(ctx, spec.value, handler);
406 String whereClause = buildWhereForAuthByName(spec.value);
407 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
408 handler.setDocumentFilter(myFilter);
409 getRepositoryClient(ctx).get(ctx, handler);
411 result = ctx.getOutput();
413 } catch (Exception e) {
414 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
417 if (result == null) {
418 Response response = Response.status(Response.Status.NOT_FOUND).entity(
419 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
420 "text/plain").build();
421 throw new CSWebApplicationException(response);
424 return result.getBytes();
428 * Finds and populates the authority list.
432 * @return the authority list
435 @Produces("application/xml")
436 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.
437 AbstractCommonList result = null;
440 MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
441 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(uriInfo);
443 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
444 DocumentFilter myFilter = handler.getDocumentFilter();
445 // Need to make the default sort order for authority items
446 // be on the displayName field
447 String sortBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
448 if (sortBy == null || sortBy.isEmpty()) {
449 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
450 + AuthorityItemJAXBSchema.DISPLAY_NAME;
451 myFilter.setOrderByClause(qualifiedDisplayNameField);
453 String nameQ = queryParams.getFirst("refName");
455 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
457 getRepositoryClient(ctx).getFiltered(ctx, handler);
458 result = handler.getCommonPartList();
459 } catch (Exception e) {
460 throw bigReThrow(e, ServiceMessages.GET_FAILED);
469 * @param specifier the csid or id
471 * @return the multipart output
475 public byte[] updateAuthority(
476 @PathParam("csid") String specifier,
478 PoxPayloadOut result = null;
480 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
481 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
482 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
483 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
485 if (spec.form == SpecifierForm.CSID) {
488 String whereClause = buildWhereForAuthByName(spec.value);
489 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
491 getRepositoryClient(ctx).update(ctx, csid, handler);
492 result = ctx.getOutput();
493 } catch (Exception e) {
494 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
496 return result.getBytes();
502 * @param csid the csid
504 * @return the response
508 public Response deleteAuthority(@PathParam("csid") String csid) {
509 if (logger.isDebugEnabled()) {
510 logger.debug("deleteAuthority with csid=" + csid);
513 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
514 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
515 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
516 getRepositoryClient(ctx).delete(ctx, csid, handler);
517 return Response.status(HttpResponseCodes.SC_OK).build();
518 } catch (Exception e) {
519 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
523 /*************************************************************************
524 * Create an AuthorityItem - this is a sub-resource of Authority
525 * @param specifier either a CSID or one of the urn forms
526 * @return Authority item response
527 *************************************************************************/
529 @Path("{csid}/items")
530 public Response createAuthorityItem(
531 @Context ResourceMap resourceMap,
532 @Context UriInfo uriInfo,
533 @PathParam("csid") String parentspecifier,
535 Response result = null;
538 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
539 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
541 // Note: must have the parentShortId, to do the create.
542 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(parentspecifier, "createAuthorityItem", "CREATE_ITEM", null);
543 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
544 createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
545 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
546 UriBuilder path = UriBuilder.fromResource(resourceClass);
547 path.path(parent.CSID + "/items/" + itemcsid);
548 result = Response.created(path.build()).build();
549 } catch (Exception e) {
550 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
557 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
558 public byte[] getItemWorkflow(
559 @PathParam("csid") String csid,
560 @PathParam("itemcsid") String itemcsid) {
561 PoxPayloadOut result = null;
564 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
565 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
567 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
568 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
569 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
570 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
571 result = ctx.getOutput();
572 } catch (Exception e) {
573 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
575 return result.getBytes();
578 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
579 // they should be consolidated -be DRY (don't repeat yourself).
581 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
582 public byte[] updateItemWorkflowWithTransition(
583 @PathParam("csid") String csid,
584 @PathParam("itemcsid") String itemcsid,
585 @PathParam("transition") String transition) {
586 PoxPayloadOut result = null;
590 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
591 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
592 WorkflowClient.SERVICE_COMMONPART_NAME);
593 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
595 // Create a service context and document handler for the parent resource.
596 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
597 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
598 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
600 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
601 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
602 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
604 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
605 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
606 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
608 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
609 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
610 result = ctx.getOutput();
611 } catch (Exception e) {
612 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
615 return result.getBytes();
619 * Gets the authority item.
621 * @param parentspecifier either a CSID or one of the urn forms
622 * @param itemspecifier either a CSID or one of the urn forms
624 * @return the authority item
627 @Path("{csid}/items/{itemcsid}")
628 public byte[] getAuthorityItem(
629 @Context Request request,
630 @Context UriInfo uriInfo,
631 @Context ResourceMap resourceMap,
632 @PathParam("csid") String parentspecifier,
633 @PathParam("itemcsid") String itemspecifier) {
634 PoxPayloadOut result = null;
636 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", uriInfo);
638 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx =
639 (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), resourceMap, uriInfo);
641 JaxRsContext jaxRsContext = new JaxRsContext(request, uriInfo); // REM - Why are we setting this? Who is using the getter?
642 ctx.setJaxRsContext(jaxRsContext);
644 // We omit the parentShortId, only needed when doing a create...
645 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
647 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
648 if (itemSpec.form == SpecifierForm.CSID) {
649 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
651 String itemWhereClause =
652 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
653 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
654 handler.setDocumentFilter(myFilter);
655 getRepositoryClient(ctx).get(ctx, handler);
657 // TODO should we assert that the item is in the passed vocab?
658 result = ctx.getOutput();
659 } catch (Exception e) {
660 throw bigReThrow(e, ServiceMessages.GET_FAILED);
663 if (result == null) {
664 Response response = Response.status(Response.Status.NOT_FOUND).entity(
665 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
666 "text/plain").build();
667 throw new CSWebApplicationException(response);
670 return result.getBytes();
674 * Most of the authority child classes will/should use this implementation. However, the Vocabulary service's item schema is
675 * different enough that it will have to override this method in it's resource class.
678 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
679 String result = null;
681 result = NuxeoUtils.getPrimaryElPathPropertyName(
682 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
683 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
689 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
690 String result = null;
692 result = NuxeoUtils.getMultiElPathPropertyName(
693 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
694 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
700 * Gets the authorityItem list for the specified authority
701 * If partialPerm is specified, keywords will be ignored.
703 * @param specifier either a CSID or one of the urn forms
704 * @param partialTerm if non-null, matches partial terms
705 * @param keywords if non-null, matches terms in the keyword index for items
706 * @param ui passed to include additional parameters, like pagination controls
708 * @return the authorityItem list
711 @Path("{csid}/items")
712 @Produces("application/xml")
713 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
714 @Context UriInfo uriInfo) {
715 AbstractCommonList result = null;
718 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
719 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
721 String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
722 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
723 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
724 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
725 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
727 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
728 // We omit the parentShortId, only needed when doing a create...
729 String parentcsid = PARENT_WILDCARD.equals(specifier) ? null :
730 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", uriInfo);
731 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
732 createItemDocumentHandler(ctx, parentcsid, null);
734 DocumentFilter myFilter = handler.getDocumentFilter();
735 // If we are not wildcarding the parent, add a restriction
736 if (parentcsid != null) {
737 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
738 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
739 + "'" + parentcsid + "'",
740 IQueryManager.SEARCH_QUALIFIER_AND);
743 if (Tools.notBlank(termStatus)) {
744 // Start with the qualified termStatus field
745 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
746 + AuthorityItemJAXBSchema.TERM_STATUS;
747 String[] filterTerms = termStatus.trim().split("\\|");
748 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
749 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
752 result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm);
753 } catch (Exception e) {
754 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
761 * @return the name of the property used to specify references for items in this type of
762 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
763 * Some types (like Vocabulary) use a separate property.
765 protected String getRefPropName() {
766 return ServiceBindingUtils.AUTH_REF_PROP;
770 * Gets the entities referencing this Authority item instance. The service type
771 * can be passed as a query param "type", and must match a configured type
772 * for the service bindings. If not set, the type defaults to
773 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
775 * @param parentspecifier either a CSID or one of the urn forms
776 * @param itemspecifier either a CSID or one of the urn forms
779 * @return the info for the referencing objects
782 @Path("{csid}/items/{itemcsid}/refObjs")
783 @Produces("application/xml")
784 public AuthorityRefDocList getReferencingObjects(
785 @PathParam("csid") String parentspecifier,
786 @PathParam("itemcsid") String itemspecifier,
787 @Context UriTemplateRegistry uriTemplateRegistry,
788 @Context UriInfo uriInfo) {
789 AuthorityRefDocList authRefDocList = null;
791 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
792 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
794 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", uriInfo);
795 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
797 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
798 if(serviceTypes == null || serviceTypes.isEmpty()) {
799 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
802 // Note that we have to create the service context for the Items, not the main service
803 // We omit the parentShortId, only needed when doing a create...
804 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
805 createItemDocumentHandler(ctx, parentcsid, null);
807 authRefDocList = handler.getReferencingObjects(ctx, uriTemplateRegistry, serviceTypes, getRefPropName(), itemcsid);
808 } catch (Exception e) {
809 throw bigReThrow(e, ServiceMessages.GET_FAILED);
811 if (authRefDocList == null) {
812 Response response = Response.status(Response.Status.NOT_FOUND).entity(
813 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
814 "text/plain").build();
815 throw new CSWebApplicationException(response);
817 return authRefDocList;
821 * Gets the authority terms used in the indicated Authority item.
823 * @param parentspecifier either a CSID or one of the urn forms
824 * @param itemspecifier either a CSID or one of the urn forms
825 * @param ui passed to include additional parameters, like pagination controls
827 * @return the authority refs for the Authority item.
830 @Path("{csid}/items/{itemcsid}/authorityrefs")
831 @Produces("application/xml")
832 public AuthorityRefList getAuthorityItemAuthorityRefs(
833 @PathParam("csid") String parentspecifier,
834 @PathParam("itemcsid") String itemspecifier,
835 @Context UriInfo uriInfo) {
836 AuthorityRefList authRefList = null;
838 // Note that we have to create the service context for the Items, not the main service
839 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
840 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
841 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", uriInfo);
842 // We omit the parentShortId, only needed when doing a create...
843 DocumentModelHandler<?, AbstractCommonList> handler =
844 (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null /*no parent short ID*/);
846 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
848 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
849 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
850 } catch (Exception e) {
851 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
857 * Update authorityItem.
859 * @param parentspecifier either a CSID or one of the urn forms
860 * @param itemspecifier either a CSID or one of the urn forms
862 * @return the multipart output
865 @Path("{csid}/items/{itemcsid}")
866 public byte[] updateAuthorityItem(
867 @Context ResourceMap resourceMap,
868 @Context UriInfo uriInfo,
869 @PathParam("csid") String parentspecifier,
870 @PathParam("itemcsid") String itemspecifier,
872 PoxPayloadOut result = null;
874 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
875 // Note that we have to create the service context for the Items, not the main service
876 // 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
877 CsidAndShortIdentifier csidAndShortId = lookupParentCSIDAndShortIdentifer(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
878 String parentcsid = csidAndShortId.CSID;
879 String parentShortId = csidAndShortId.shortIdentifier;
881 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
882 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
884 // We omit the parentShortId, only needed when doing a create...
885 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, parentShortId);
886 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
887 result = ctx.getOutput();
889 } catch (Exception e) {
890 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
892 return result.getBytes();
896 * Delete authorityItem.
898 * @param parentcsid the parentcsid
899 * @param itemcsid the itemcsid
901 * @return the response
904 @Path("{csid}/items/{itemcsid}")
905 public Response deleteAuthorityItem(
906 @PathParam("csid") String parentcsid,
907 @PathParam("itemcsid") String itemcsid) {
909 if (logger.isDebugEnabled()) {
910 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
913 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
914 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
915 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
916 // }catch (Throwable t){
917 // System.out.println("ERROR in setting up DELETE: "+t);
920 // Note that we have to create the service context for the Items, not the main service
921 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
922 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
923 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
924 return Response.status(HttpResponseCodes.SC_OK).build();
925 } catch (Exception e) {
926 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
929 public final static String hierarchy = "hierarchy";
932 @Path("{csid}/items/{itemcsid}/" + hierarchy)
933 @Produces("application/xml")
934 public String getHierarchy(@PathParam("csid") String csid,
935 @PathParam("itemcsid") String itemcsid,
936 @Context UriInfo ui) throws Exception {
938 // 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...?
939 String calledUri = ui.getPath();
940 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
941 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), ui);
943 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
944 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
945 return Hierarchy.surface(ctx, itemcsid, uri);
947 return Hierarchy.dive(ctx, itemcsid, uri);
949 } catch (Exception e) {
950 throw bigReThrow(e, "Error showing hierarchy", itemcsid);
954 protected String getItemDocType(String tenantId) {
955 return getDocType(tenantId, getItemServiceName());
959 * Returns a UriRegistry entry: a map of tenant-qualified URI templates
960 * for the current resource, for all tenants
962 * @return a map of URI templates for the current resource, for all tenants
965 public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
966 Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
967 super.getUriRegistryEntries();
968 List<String> tenantIds = getTenantBindingsReader().getTenantIds();
969 for (String tenantId : tenantIds) {
970 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getItemDocType(tenantId), UriTemplateFactory.ITEM));
972 return uriRegistryEntriesMap;