2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
24 package org.collectionspace.services.common.vocabulary;
26 import java.util.List;
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.DELETE;
31 import javax.ws.rs.GET;
32 import javax.ws.rs.POST;
33 import javax.ws.rs.PUT;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.PathParam;
36 import javax.ws.rs.Produces;
37 import javax.ws.rs.core.Context;
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Request;
40 import javax.ws.rs.core.Response;
41 import javax.ws.rs.core.UriBuilder;
42 import javax.ws.rs.core.UriInfo;
44 import org.collectionspace.services.client.IClientQueryParams;
45 import org.collectionspace.services.client.IQueryManager;
46 import org.collectionspace.services.client.PoxPayloadIn;
47 import org.collectionspace.services.client.PoxPayloadOut;
48 import org.collectionspace.services.client.workflow.WorkflowClient;
49 import org.collectionspace.services.common.CSWebApplicationException;
50 import org.collectionspace.services.common.NuxeoBasedResource;
51 import org.collectionspace.services.common.ResourceMap;
52 import org.collectionspace.services.common.ServiceMain;
53 import org.collectionspace.services.common.ServiceMessages;
54 import org.collectionspace.services.common.StoredValuesUriTemplate;
55 import org.collectionspace.services.common.UriTemplateFactory;
56 import org.collectionspace.services.common.UriTemplateRegistry;
57 import org.collectionspace.services.common.UriTemplateRegistryKey;
58 import org.collectionspace.services.common.api.RefName;
59 import org.collectionspace.services.common.api.Tools;
60 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
61 import org.collectionspace.services.common.authorityref.AuthorityRefList;
62 import org.collectionspace.services.common.context.JaxRsContext;
63 import org.collectionspace.services.common.context.MultipartServiceContext;
64 import org.collectionspace.services.common.context.RemoteServiceContext;
65 import org.collectionspace.services.common.context.ServiceBindingUtils;
66 import org.collectionspace.services.common.context.ServiceContext;
67 import org.collectionspace.services.common.document.DocumentException;
68 import org.collectionspace.services.common.document.DocumentFilter;
69 import org.collectionspace.services.common.document.DocumentHandler;
70 import org.collectionspace.services.common.document.DocumentNotFoundException;
71 import org.collectionspace.services.common.document.DocumentWrapper;
72 import org.collectionspace.services.common.document.Hierarchy;
73 import org.collectionspace.services.common.query.QueryManager;
74 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
75 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
76 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
77 import org.collectionspace.services.config.ClientType;
78 import org.collectionspace.services.jaxb.AbstractCommonList;
79 import org.collectionspace.services.lifecycle.TransitionDef;
80 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
81 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
82 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentFilter;
83 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
84 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
85 import org.collectionspace.services.workflow.WorkflowCommon;
86 import org.jboss.resteasy.util.HttpResponseCodes;
87 import org.nuxeo.ecm.core.api.DocumentModel;
88 import org.nuxeo.ecm.core.api.DocumentModelList;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 * The Class AuthorityResource.
99 * @param <AuthItemHandler>
104 * @param <AuthCommon>
105 * @param <AuthItemHandler>
107 @Consumes("application/xml")
108 @Produces("application/xml")
109 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
110 extends NuxeoBasedResource {
112 final static String SEARCH_TYPE_TERMSTATUS = "ts";
114 protected Class<AuthCommon> authCommonClass;
115 protected Class<?> resourceClass;
116 protected String authorityCommonSchemaName;
117 protected String authorityItemCommonSchemaName;
118 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
119 final static String URN_PREFIX = "urn:cspace:";
120 final static int URN_PREFIX_LEN = URN_PREFIX.length();
121 final static String URN_PREFIX_NAME = "name(";
122 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
123 final static String URN_PREFIX_ID = "id(";
124 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
125 final static String FETCH_SHORT_ID = "_fetch_";
126 public final static String PARENT_WILDCARD = "_ALL_";
128 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
130 public enum SpecifierForm {
135 public class Specifier {
137 public SpecifierForm form;
140 Specifier(SpecifierForm form, String value) {
146 protected Specifier getSpecifier(String specifierIn, String method, String op) throws CSWebApplicationException {
147 if (logger.isDebugEnabled()) {
148 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
150 if (specifierIn != null) {
151 if (!specifierIn.startsWith(URN_PREFIX)) {
152 // We'll assume it is a CSID and complain if it does not match
153 return new Specifier(SpecifierForm.CSID, specifierIn);
155 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
156 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
157 if (closeParen >= 0) {
158 return new Specifier(SpecifierForm.URN_NAME,
159 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
161 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
162 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
163 if (closeParen >= 0) {
164 return new Specifier(SpecifierForm.CSID,
165 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
170 logger.error(method + ": bad or missing specifier!");
171 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
172 op + " failed on bad or missing Authority specifier").type(
173 "text/plain").build();
174 throw new CSWebApplicationException(response);
178 * Instantiates a new Authority resource.
180 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
181 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
182 this.authCommonClass = authCommonClass;
183 this.resourceClass = resourceClass;
184 this.authorityCommonSchemaName = authorityCommonSchemaName;
185 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
188 public abstract String getItemServiceName();
190 public abstract String getItemTermInfoGroupXPathBase();
193 protected String getVersionString() {
194 return "$LastChangedRevision: 2617 $";
198 public Class<AuthCommon> getCommonPartClass() {
199 return authCommonClass;
203 * Creates the item document handler.
206 * @param inAuthority the in vocabulary
208 * @return the document handler
210 * @throws Exception the exception
212 protected DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> createItemDocumentHandler(
213 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
214 String inAuthority, String parentShortIdentifier)
216 String authorityRefNameBase;
217 AuthorityItemDocumentModelHandler<?> docHandler;
219 if (parentShortIdentifier == null) {
220 authorityRefNameBase = null;
222 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
223 createServiceContext(getServiceName());
224 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
225 // Get from parent document
226 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
228 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
231 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
232 ctx.getCommonPartLabel(getItemServiceName()),
234 // FIXME - Richard and Aron think the following three lines should
235 // be in the constructor for the AuthorityItemDocumentModelHandler
236 // because all three are required fields.
237 docHandler.setInAuthority(inAuthority);
238 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
239 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
243 public String getAuthShortIdentifier(
244 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
245 throws DocumentNotFoundException, DocumentException {
246 String shortIdentifier = null;
248 AuthorityDocumentModelHandler<?> handler =
249 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
250 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
251 } catch (Exception e) {
252 if (logger.isDebugEnabled()) {
253 logger.debug("Caught exception ", e);
255 throw new DocumentException(e);
257 return shortIdentifier;
260 protected String buildAuthorityRefNameBase(
261 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
262 RefName.Authority authority = RefName.Authority.buildAuthority(ctx.getTenantName(),
263 ctx.getServiceName(),
264 null, // Only use shortId form!!!
265 shortIdentifier, null);
266 return authority.toString();
269 public static class CsidAndShortIdentifier {
272 String shortIdentifier;
275 protected String lookupParentCSID(String parentspecifier, String method,
276 String op, UriInfo uriInfo) throws Exception {
277 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(
278 parentspecifier, method, op, uriInfo);
279 return tempResult.CSID;
282 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(
283 String parentspecifier,
288 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
289 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
290 // Note that we have to create the service context for the Items, not the main service
292 String parentShortIdentifier;
293 if (parentSpec.form == SpecifierForm.CSID) {
294 parentShortIdentifier = null;
295 parentcsid = parentSpec.value;
296 // Uncomment when app layer is ready to integrate
297 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
298 parentShortIdentifier = FETCH_SHORT_ID;
300 parentShortIdentifier = parentSpec.value;
301 String whereClause = buildWhereForAuthByName(parentSpec.value);
302 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getServiceName(), uriInfo);
303 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
305 result.CSID = parentcsid;
306 result.shortIdentifier = parentShortIdentifier;
310 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx)
311 throws DocumentException {
313 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
314 if (itemSpec.form == SpecifierForm.CSID) {
315 itemcsid = itemSpec.value;
317 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
318 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
324 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
325 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
326 * Resource. They then call this method on that resource.
329 public DocumentModel getDocModelForAuthorityItem(CoreSessionInterface repoSession, RefName.AuthorityItem item)
330 throws Exception, DocumentNotFoundException {
334 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
335 // Ensure we have the right context.
336 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(item.inAuthority.resource);
338 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
339 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
340 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
342 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
343 ctx = createServiceContext(getItemServiceName());
344 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
345 DocumentModel docModel = docWrapper.getWrappedObject();
350 @POST //FIXME: REM - 5/1/2012 - We can probably remove this method.
351 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.
353 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
354 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
355 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
356 String csid = getRepositoryClient(ctx).create(ctx, handler);
357 UriBuilder path = UriBuilder.fromResource(resourceClass);
358 path.path("" + csid);
359 Response response = Response.created(path.build()).build();
361 } catch (Exception e) {
362 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
366 protected String buildWhereForAuthByName(String name) {
367 return authorityCommonSchemaName
368 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
372 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
373 return authorityItemCommonSchemaName
374 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
375 + "='" + name + "' AND "
376 + authorityItemCommonSchemaName + ":"
377 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
378 + "'" + parentcsid + "'";
382 * Gets the authority.
384 * @param specifier either a CSID or one of the urn forms
386 * @return the authority
392 @Context Request request,
394 @PathParam("csid") String specifier) {
395 PoxPayloadOut result = null;
397 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
398 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
400 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
401 if (spec.form == SpecifierForm.CSID) {
402 if (logger.isDebugEnabled()) {
403 logger.debug("getAuthority with csid=" + spec.value);
405 getRepositoryClient(ctx).get(ctx, spec.value, handler);
407 String whereClause = buildWhereForAuthByName(spec.value);
408 DocumentFilter myFilter = new NuxeoDocumentFilter(whereClause, 0, 1);
409 handler.setDocumentFilter(myFilter);
410 getRepositoryClient(ctx).get(ctx, handler);
412 result = ctx.getOutput();
414 } catch (Exception e) {
415 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
418 if (result == null) {
419 Response response = Response.status(Response.Status.NOT_FOUND).entity(
420 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
421 "text/plain").build();
422 throw new CSWebApplicationException(response);
425 return result.getBytes();
429 * Finds and populates the authority list.
433 * @return the authority list
436 @Produces("application/xml")
437 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.
438 AbstractCommonList result = null;
441 MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
442 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(uriInfo);
444 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
445 DocumentFilter myFilter = handler.getDocumentFilter();
446 // Need to make the default sort order for authority items
447 // be on the displayName field
448 String sortBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
449 if (sortBy == null || sortBy.isEmpty()) {
450 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
451 + AuthorityItemJAXBSchema.DISPLAY_NAME;
452 myFilter.setOrderByClause(qualifiedDisplayNameField);
454 String nameQ = queryParams.getFirst("refName");
456 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
458 getRepositoryClient(ctx).getFiltered(ctx, handler);
459 result = handler.getCommonPartList();
460 } catch (Exception e) {
461 throw bigReThrow(e, ServiceMessages.GET_FAILED);
470 * @param specifier the csid or id
472 * @return the multipart output
476 public byte[] updateAuthority(
477 @PathParam("csid") String specifier,
479 PoxPayloadOut result = null;
481 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
482 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
483 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
484 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
486 if (spec.form == SpecifierForm.CSID) {
489 String whereClause = buildWhereForAuthByName(spec.value);
490 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
492 getRepositoryClient(ctx).update(ctx, csid, handler);
493 result = ctx.getOutput();
494 } catch (Exception e) {
495 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
497 return result.getBytes();
503 * @param csid the csid
505 * @return the response
509 public Response deleteAuthority(@PathParam("csid") String csid) {
510 if (logger.isDebugEnabled()) {
511 logger.debug("deleteAuthority with csid=" + csid);
514 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
515 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
516 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
517 getRepositoryClient(ctx).delete(ctx, csid, handler);
518 return Response.status(HttpResponseCodes.SC_OK).build();
519 } catch (Exception e) {
520 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
524 /*************************************************************************
525 * Create an AuthorityItem - this is a sub-resource of Authority
526 * @param specifier either a CSID or one of the urn forms
527 * @return Authority item response
528 *************************************************************************/
530 @Path("{csid}/items")
531 public Response createAuthorityItem(
532 @Context ResourceMap resourceMap,
533 @Context UriInfo uriInfo,
534 @PathParam("csid") String parentspecifier,
536 Response result = null;
539 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
540 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
542 // Note: must have the parentShortId, to do the create.
543 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(parentspecifier, "createAuthorityItem", "CREATE_ITEM", null);
544 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
545 createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
546 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
547 UriBuilder path = UriBuilder.fromResource(resourceClass);
548 path.path(parent.CSID + "/items/" + itemcsid);
549 result = Response.created(path.build()).build();
550 } catch (Exception e) {
551 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
558 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
559 public byte[] getItemWorkflow(
560 @PathParam("csid") String csid,
561 @PathParam("itemcsid") String itemcsid) {
562 PoxPayloadOut result = null;
565 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
566 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
568 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
569 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
570 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
571 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
572 result = ctx.getOutput();
573 } catch (Exception e) {
574 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
576 return result.getBytes();
579 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
580 // they should be consolidated -be DRY (don't repeat yourself).
582 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
583 public byte[] updateItemWorkflowWithTransition(
584 @PathParam("csid") String csid,
585 @PathParam("itemcsid") String itemcsid,
586 @PathParam("transition") String transition) {
587 PoxPayloadOut result = null;
591 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
592 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
593 WorkflowClient.SERVICE_COMMONPART_NAME);
594 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
596 // Create a service context and document handler for the parent resource.
597 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
598 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
599 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
601 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
602 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
603 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
605 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
606 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
607 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
609 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
610 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
611 result = ctx.getOutput();
612 } catch (Exception e) {
613 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
616 return result.getBytes();
620 * Gets the authority item.
622 * @param parentspecifier either a CSID or one of the urn forms
623 * @param itemspecifier either a CSID or one of the urn forms
625 * @return the authority item
628 @Path("{csid}/items/{itemcsid}")
629 public byte[] getAuthorityItem(
630 @Context Request request,
631 @Context UriInfo uriInfo,
632 @Context ResourceMap resourceMap,
633 @PathParam("csid") String parentspecifier,
634 @PathParam("itemcsid") String itemspecifier) {
635 PoxPayloadOut result = null;
637 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", uriInfo);
639 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx =
640 (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), resourceMap, uriInfo);
642 JaxRsContext jaxRsContext = new JaxRsContext(request, uriInfo); // REM - Why are we setting this? Who is using the getter?
643 ctx.setJaxRsContext(jaxRsContext);
645 // We omit the parentShortId, only needed when doing a create...
646 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
648 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
649 if (itemSpec.form == SpecifierForm.CSID) {
650 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
652 String itemWhereClause =
653 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
654 DocumentFilter myFilter = new NuxeoDocumentFilter(itemWhereClause, 0, 1); // start at page 0 and get 1 item
655 handler.setDocumentFilter(myFilter);
656 getRepositoryClient(ctx).get(ctx, handler);
658 // TODO should we assert that the item is in the passed vocab?
659 result = ctx.getOutput();
660 } catch (Exception e) {
661 throw bigReThrow(e, ServiceMessages.GET_FAILED);
664 if (result == null) {
665 Response response = Response.status(Response.Status.NOT_FOUND).entity(
666 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
667 "text/plain").build();
668 throw new CSWebApplicationException(response);
671 return result.getBytes();
675 * Most of the authority child classes will/should use this implementation. However, the Vocabulary service's item schema is
676 * different enough that it will have to override this method in it's resource class.
679 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
680 String result = null;
682 result = NuxeoUtils.getPrimaryElPathPropertyName(
683 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
684 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
690 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
691 String result = null;
693 result = NuxeoUtils.getMultiElPathPropertyName(
694 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
695 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
701 * Gets the authorityItem list for the specified authority
702 * If partialPerm is specified, keywords will be ignored.
704 * @param specifier either a CSID or one of the urn forms
705 * @param partialTerm if non-null, matches partial terms
706 * @param keywords if non-null, matches terms in the keyword index for items
707 * @param ui passed to include additional parameters, like pagination controls
709 * @return the authorityItem list
712 @Path("{csid}/items")
713 @Produces("application/xml")
714 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
715 @Context UriInfo uriInfo) {
716 AbstractCommonList result = null;
719 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
720 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
722 String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
723 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
724 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
725 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
726 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
728 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
729 // We omit the parentShortId, only needed when doing a create...
730 String parentcsid = PARENT_WILDCARD.equals(specifier) ? null :
731 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", uriInfo);
732 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
733 createItemDocumentHandler(ctx, parentcsid, null);
735 DocumentFilter myFilter = handler.getDocumentFilter();
736 // If we are not wildcarding the parent, add a restriction
737 if (parentcsid != null) {
738 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
739 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
740 + "'" + parentcsid + "'",
741 IQueryManager.SEARCH_QUALIFIER_AND);
744 if (Tools.notBlank(termStatus)) {
745 // Start with the qualified termStatus field
746 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
747 + AuthorityItemJAXBSchema.TERM_STATUS;
748 String[] filterTerms = termStatus.trim().split("\\|");
749 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
750 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
753 result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm);
754 } catch (Exception e) {
755 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
762 * @return the name of the property used to specify references for items in this type of
763 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
764 * Some types (like Vocabulary) use a separate property.
766 protected String getRefPropName() {
767 return ServiceBindingUtils.AUTH_REF_PROP;
771 * Gets the entities referencing this Authority item instance. The service type
772 * can be passed as a query param "type", and must match a configured type
773 * for the service bindings. If not set, the type defaults to
774 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
776 * @param parentspecifier either a CSID or one of the urn forms
777 * @param itemspecifier either a CSID or one of the urn forms
780 * @return the info for the referencing objects
783 @Path("{csid}/items/{itemcsid}/refObjs")
784 @Produces("application/xml")
785 public AuthorityRefDocList getReferencingObjects(
786 @PathParam("csid") String parentspecifier,
787 @PathParam("itemcsid") String itemspecifier,
788 @Context UriTemplateRegistry uriTemplateRegistry,
789 @Context UriInfo uriInfo) {
790 AuthorityRefDocList authRefDocList = null;
792 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
793 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
795 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", uriInfo);
796 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
798 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
799 if(serviceTypes == null || serviceTypes.isEmpty()) {
800 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
803 // Note that we have to create the service context for the Items, not the main service
804 // We omit the parentShortId, only needed when doing a create...
805 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
806 createItemDocumentHandler(ctx, parentcsid, null);
808 authRefDocList = handler.getReferencingObjects(ctx, uriTemplateRegistry, serviceTypes, getRefPropName(), itemcsid);
809 } catch (Exception e) {
810 throw bigReThrow(e, ServiceMessages.GET_FAILED);
812 if (authRefDocList == null) {
813 Response response = Response.status(Response.Status.NOT_FOUND).entity(
814 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
815 "text/plain").build();
816 throw new CSWebApplicationException(response);
818 return authRefDocList;
822 * Gets the authority terms used in the indicated Authority item.
824 * @param parentspecifier either a CSID or one of the urn forms
825 * @param itemspecifier either a CSID or one of the urn forms
826 * @param ui passed to include additional parameters, like pagination controls
828 * @return the authority refs for the Authority item.
831 @Path("{csid}/items/{itemcsid}/authorityrefs")
832 @Produces("application/xml")
833 public AuthorityRefList getAuthorityItemAuthorityRefs(
834 @PathParam("csid") String parentspecifier,
835 @PathParam("itemcsid") String itemspecifier,
836 @Context UriInfo uriInfo) {
837 AuthorityRefList authRefList = null;
839 // Note that we have to create the service context for the Items, not the main service
840 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
841 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
842 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", uriInfo);
843 // We omit the parentShortId, only needed when doing a create...
844 DocumentModelHandler<?, AbstractCommonList> handler =
845 (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null /*no parent short ID*/);
847 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
849 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
850 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
851 } catch (Exception e) {
852 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
858 * Update authorityItem.
860 * @param parentspecifier either a CSID or one of the urn forms
861 * @param itemspecifier either a CSID or one of the urn forms
863 * @return the multipart output
866 @Path("{csid}/items/{itemcsid}")
867 public byte[] updateAuthorityItem(
868 @Context ResourceMap resourceMap,
869 @Context UriInfo uriInfo,
870 @PathParam("csid") String parentspecifier,
871 @PathParam("itemcsid") String itemspecifier,
873 PoxPayloadOut result = null;
875 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
876 // Note that we have to create the service context for the Items, not the main service
877 // 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
878 CsidAndShortIdentifier csidAndShortId = lookupParentCSIDAndShortIdentifer(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
879 String parentcsid = csidAndShortId.CSID;
880 String parentShortId = csidAndShortId.shortIdentifier;
882 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate, resourceMap, uriInfo);
883 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
885 // We omit the parentShortId, only needed when doing a create...
886 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, parentShortId);
887 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
888 result = ctx.getOutput();
890 } catch (Exception e) {
891 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
893 return result.getBytes();
897 * Delete authorityItem.
899 * @param parentcsid the parentcsid
900 * @param itemcsid the itemcsid
902 * @return the response
905 @Path("{csid}/items/{itemcsid}")
906 public Response deleteAuthorityItem(
907 @PathParam("csid") String parentcsid,
908 @PathParam("itemcsid") String itemcsid) {
910 if (logger.isDebugEnabled()) {
911 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
914 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
915 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
916 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
917 // }catch (Throwable t){
918 // System.out.println("ERROR in setting up DELETE: "+t);
921 // Note that we have to create the service context for the Items, not the main service
922 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
923 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
924 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
925 return Response.status(HttpResponseCodes.SC_OK).build();
926 } catch (Exception e) {
927 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
930 public final static String hierarchy = "hierarchy";
933 @Path("{csid}/items/{itemcsid}/" + hierarchy)
934 @Produces("application/xml")
935 public String getHierarchy(@PathParam("csid") String csid,
936 @PathParam("itemcsid") String itemcsid,
937 @Context UriInfo ui) throws Exception {
939 // 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...?
940 String calledUri = ui.getPath();
941 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
942 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), ui);
944 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
945 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
946 return Hierarchy.surface(ctx, itemcsid, uri);
948 return Hierarchy.dive(ctx, itemcsid, uri);
950 } catch (Exception e) {
951 throw bigReThrow(e, "Error showing hierarchy", itemcsid);
955 protected String getItemDocType(String tenantId) {
956 return getDocType(tenantId, getItemServiceName());
960 * Returns a UriRegistry entry: a map of tenant-qualified URI templates
961 * for the current resource, for all tenants
963 * @return a map of URI templates for the current resource, for all tenants
966 public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
967 Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
968 super.getUriRegistryEntries();
969 List<String> tenantIds = getTenantBindingsReader().getTenantIds();
970 for (String tenantId : tenantIds) {
971 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getItemDocType(tenantId), UriTemplateFactory.ITEM));
973 return uriRegistryEntriesMap;