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 org.collectionspace.services.client.IClientQueryParams;
27 import org.collectionspace.services.client.IQueryManager;
28 import org.collectionspace.services.client.PoxPayloadIn;
29 import org.collectionspace.services.client.PoxPayloadOut;
30 import org.collectionspace.services.client.workflow.WorkflowClient;
31 import org.collectionspace.services.common.ResourceBase;
32 import org.collectionspace.services.common.ResourceMap;
33 import org.collectionspace.services.common.ServiceMain;
34 import org.collectionspace.services.common.ServiceMessages;
35 import org.collectionspace.services.common.api.RefName;
36 import org.collectionspace.services.common.api.Tools;
37 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
38 import org.collectionspace.services.common.authorityref.AuthorityRefList;
39 import org.collectionspace.services.common.context.JaxRsContext;
40 import org.collectionspace.services.common.context.MultipartServiceContext;
41 import org.collectionspace.services.common.context.RemoteServiceContext;
42 import org.collectionspace.services.common.context.ServiceBindingUtils;
43 import org.collectionspace.services.common.context.ServiceContext;
44 import org.collectionspace.services.common.document.DocumentException;
45 import org.collectionspace.services.common.document.DocumentFilter;
46 import org.collectionspace.services.common.document.DocumentHandler;
47 import org.collectionspace.services.common.document.DocumentNotFoundException;
48 import org.collectionspace.services.common.document.DocumentWrapper;
49 import org.collectionspace.services.common.document.Hierarchy;
50 import org.collectionspace.services.common.query.QueryManager;
51 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
52 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
53 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
54 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
55 import org.collectionspace.services.config.ClientType;
56 import org.collectionspace.services.jaxb.AbstractCommonList;
57 import org.collectionspace.services.lifecycle.TransitionDef;
58 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
59 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
60 import org.collectionspace.services.workflow.WorkflowCommon;
61 import org.jboss.resteasy.util.HttpResponseCodes;
62 import org.nuxeo.ecm.core.api.DocumentModel;
63 import org.nuxeo.ecm.core.api.DocumentModelList;
64 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 import javax.ws.rs.Consumes;
69 import javax.ws.rs.DELETE;
70 import javax.ws.rs.GET;
71 import javax.ws.rs.POST;
72 import javax.ws.rs.PUT;
73 import javax.ws.rs.Path;
74 import javax.ws.rs.PathParam;
75 import javax.ws.rs.Produces;
76 import javax.ws.rs.WebApplicationException;
77 import javax.ws.rs.core.Context;
78 import javax.ws.rs.core.MultivaluedMap;
79 import javax.ws.rs.core.Request;
80 import javax.ws.rs.core.Response;
81 import javax.ws.rs.core.UriBuilder;
82 import javax.ws.rs.core.UriInfo;
84 import java.util.HashMap;
85 import java.util.List;
87 import org.collectionspace.services.common.*;
89 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
90 import org.collectionspace.services.config.service.ServiceBindingType;
92 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
95 * The Class AuthorityResource.
100 * @param <AuthCommon>
101 * @param <AuthItemHandler>
106 * @param <AuthCommon>
107 * @param <AuthItemHandler>
109 @Consumes("application/xml")
110 @Produces("application/xml")
111 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
112 extends ResourceBase {
114 final static String SEARCH_TYPE_TERMSTATUS = "ts";
116 protected Class<AuthCommon> authCommonClass;
117 protected Class<?> resourceClass;
118 protected String authorityCommonSchemaName;
119 protected String authorityItemCommonSchemaName;
120 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
121 final static String URN_PREFIX = "urn:cspace:";
122 final static int URN_PREFIX_LEN = URN_PREFIX.length();
123 final static String URN_PREFIX_NAME = "name(";
124 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
125 final static String URN_PREFIX_ID = "id(";
126 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
127 final static String FETCH_SHORT_ID = "_fetch_";
128 final static String PARENT_WILDCARD = "_ALL_";
130 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
132 public enum SpecifierForm {
137 public class Specifier {
139 public SpecifierForm form;
142 Specifier(SpecifierForm form, String value) {
148 protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException {
149 if (logger.isDebugEnabled()) {
150 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
152 if (specifierIn != null) {
153 if (!specifierIn.startsWith(URN_PREFIX)) {
154 // We'll assume it is a CSID and complain if it does not match
155 return new Specifier(SpecifierForm.CSID, specifierIn);
157 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
158 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
159 if (closeParen >= 0) {
160 return new Specifier(SpecifierForm.URN_NAME,
161 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
163 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
164 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
165 if (closeParen >= 0) {
166 return new Specifier(SpecifierForm.CSID,
167 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
172 logger.error(method + ": bad or missing specifier!");
173 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
174 op + " failed on bad or missing Authority specifier").type(
175 "text/plain").build();
176 throw new WebApplicationException(response);
180 * Instantiates a new Authority resource.
182 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
183 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
184 this.authCommonClass = authCommonClass;
185 this.resourceClass = resourceClass;
186 this.authorityCommonSchemaName = authorityCommonSchemaName;
187 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
190 public abstract String getItemServiceName();
192 public abstract String getItemTermInfoGroupXPathBase();
195 protected String getVersionString() {
196 return "$LastChangedRevision: 2617 $";
200 public Class<AuthCommon> getCommonPartClass() {
201 return authCommonClass;
205 * Creates the item document handler.
208 * @param inAuthority the in vocabulary
210 * @return the document handler
212 * @throws Exception the exception
214 protected DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> createItemDocumentHandler(
215 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
216 String inAuthority, String parentShortIdentifier)
218 String authorityRefNameBase;
219 AuthorityItemDocumentModelHandler<?> docHandler;
221 if (parentShortIdentifier == null) {
222 authorityRefNameBase = null;
224 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
225 createServiceContext(getServiceName());
226 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
227 // Get from parent document
228 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
230 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
233 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
234 ctx.getCommonPartLabel(getItemServiceName()),
236 // FIXME - Richard and Aron think the following three lines should
237 // be in the constructor for the AuthorityItemDocumentModelHandler
238 // because all three are required fields.
239 docHandler.setInAuthority(inAuthority);
240 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
241 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
245 public String getAuthShortIdentifier(
246 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
247 throws DocumentNotFoundException, DocumentException {
248 String shortIdentifier = null;
250 AuthorityDocumentModelHandler<?> handler =
251 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
252 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
253 } catch (Exception e) {
254 if (logger.isDebugEnabled()) {
255 logger.debug("Caught exception ", e);
257 throw new DocumentException(e);
259 return shortIdentifier;
262 protected String buildAuthorityRefNameBase(
263 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
264 RefName.Authority authority = RefName.Authority.buildAuthority(ctx.getTenantName(),
265 ctx.getServiceName(), 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(String parentspecifier,
283 String method, String op,
286 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
287 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
288 // Note that we have to create the service context for the Items, not the main service
290 String parentShortIdentifier;
291 if (parentSpec.form == SpecifierForm.CSID) {
292 parentShortIdentifier = null;
293 parentcsid = parentSpec.value;
294 // Uncomment when app layer is ready to integrate
295 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
296 parentShortIdentifier = FETCH_SHORT_ID;
298 parentShortIdentifier = parentSpec.value;
299 String whereClause = buildWhereForAuthByName(parentSpec.value);
300 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getServiceName(), uriInfo);
301 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
303 result.CSID = parentcsid;
304 result.shortIdentifier = parentShortIdentifier;
308 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx)
309 throws DocumentException {
311 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
312 if (itemSpec.form == SpecifierForm.CSID) {
313 itemcsid = itemSpec.value;
315 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
316 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
322 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
323 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
324 * Resource. They then call this method on that resource.
327 public DocumentModel getDocModelForAuthorityItem(RepositoryInstance repoSession, RefName.AuthorityItem item)
328 throws Exception, DocumentNotFoundException {
332 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
333 // Ensure we have the right context.
334 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(item.inAuthority.resource);
336 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
337 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
338 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
340 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
341 ctx = createServiceContext(getItemServiceName());
342 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
343 DocumentModel docModel = docWrapper.getWrappedObject();
348 @POST //FIXME: REM - 5/1/2012 - We can probably remove this method.
349 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.
351 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
352 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
353 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
354 String csid = getRepositoryClient(ctx).create(ctx, handler);
355 UriBuilder path = UriBuilder.fromResource(resourceClass);
356 path.path("" + csid);
357 Response response = Response.created(path.build()).build();
359 } catch (Exception e) {
360 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
364 protected String buildWhereForAuthByName(String name) {
365 return authorityCommonSchemaName
366 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
370 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
371 return authorityItemCommonSchemaName
372 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
373 + "='" + name + "' AND "
374 + authorityItemCommonSchemaName + ":"
375 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
376 + "'" + parentcsid + "'";
380 * Gets the authority.
382 * @param specifier either a CSID or one of the urn forms
384 * @return the authority
390 @Context Request request,
392 @PathParam("csid") String specifier) {
393 PoxPayloadOut result = null;
395 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
396 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
398 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
399 if (spec.form == SpecifierForm.CSID) {
400 if (logger.isDebugEnabled()) {
401 logger.debug("getAuthority with csid=" + spec.value);
403 getRepositoryClient(ctx).get(ctx, spec.value, handler);
405 String whereClause = buildWhereForAuthByName(spec.value);
406 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
407 handler.setDocumentFilter(myFilter);
408 getRepositoryClient(ctx).get(ctx, handler);
410 result = ctx.getOutput();
412 } catch (Exception e) {
413 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
416 if (result == null) {
417 Response response = Response.status(Response.Status.NOT_FOUND).entity(
418 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
419 "text/plain").build();
420 throw new WebApplicationException(response);
423 return result.getBytes();
427 * Finds and populates the authority list.
431 * @return the authority list
434 @Produces("application/xml")
435 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.
436 AbstractCommonList result = null;
439 MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
440 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(uriInfo);
442 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
443 DocumentFilter myFilter = handler.getDocumentFilter();
444 // Need to make the default sort order for authority items
445 // be on the displayName field
446 String sortBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
447 if (sortBy == null || sortBy.isEmpty()) {
448 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
449 + AuthorityItemJAXBSchema.DISPLAY_NAME;
450 myFilter.setOrderByClause(qualifiedDisplayNameField);
452 String nameQ = queryParams.getFirst("refName");
454 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
456 getRepositoryClient(ctx).getFiltered(ctx, handler);
457 result = handler.getCommonPartList();
458 } catch (Exception e) {
459 throw bigReThrow(e, ServiceMessages.GET_FAILED);
468 * @param specifier the csid or id
470 * @return the multipart output
474 public byte[] updateAuthority(
475 @PathParam("csid") String specifier,
477 PoxPayloadOut result = null;
479 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
480 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
481 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
482 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
484 if (spec.form == SpecifierForm.CSID) {
487 String whereClause = buildWhereForAuthByName(spec.value);
488 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
490 getRepositoryClient(ctx).update(ctx, csid, handler);
491 result = ctx.getOutput();
492 } catch (Exception e) {
493 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
495 return result.getBytes();
501 * @param csid the csid
503 * @return the response
507 public Response deleteAuthority(@PathParam("csid") String csid) {
508 if (logger.isDebugEnabled()) {
509 logger.debug("deleteAuthority with csid=" + csid);
512 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
513 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
514 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
515 getRepositoryClient(ctx).delete(ctx, csid, handler);
516 return Response.status(HttpResponseCodes.SC_OK).build();
517 } catch (Exception e) {
518 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
522 /*************************************************************************
523 * Create an AuthorityItem - this is a sub-resource of Authority
524 * @param specifier either a CSID or one of the urn forms
525 * @return Authority item response
526 *************************************************************************/
528 @Path("{csid}/items")
529 public Response createAuthorityItem(
530 @Context ResourceMap resourceMap,
531 @Context UriInfo uriInfo,
532 @PathParam("csid") String specifier,
534 Response result = null;
537 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
538 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input, resourceMap, uriInfo);
540 // Note: must have the parentShortId, to do the create.
541 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
542 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
543 createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
544 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
545 UriBuilder path = UriBuilder.fromResource(resourceClass);
546 path.path(parent.CSID + "/items/" + itemcsid);
547 result = Response.created(path.build()).build();
548 } catch (Exception e) {
549 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
556 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
557 public byte[] getItemWorkflow(
558 @PathParam("csid") String csid,
559 @PathParam("itemcsid") String itemcsid) {
560 PoxPayloadOut result = null;
563 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
564 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
566 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
567 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
568 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
569 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
570 result = ctx.getOutput();
571 } catch (Exception e) {
572 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
574 return result.getBytes();
577 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
578 // they should be consolidated -be DRY (don't repeat yourself).
580 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
581 public byte[] updateItemWorkflowWithTransition(
582 @PathParam("csid") String csid,
583 @PathParam("itemcsid") String itemcsid,
584 @PathParam("transition") String transition) {
585 PoxPayloadOut result = null;
589 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
590 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
591 WorkflowClient.SERVICE_COMMONPART_NAME);
592 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
594 // Create a service context and document handler for the parent resource.
595 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
596 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
597 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
599 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
600 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
601 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
603 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
604 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
605 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
607 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
608 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
609 result = ctx.getOutput();
610 } catch (Exception e) {
611 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
614 return result.getBytes();
618 * Gets the authority item.
620 * @param parentspecifier either a CSID or one of the urn forms
621 * @param itemspecifier either a CSID or one of the urn forms
623 * @return the authority item
626 @Path("{csid}/items/{itemcsid}")
627 public byte[] getAuthorityItem(
628 @Context Request request,
629 @Context UriInfo uriInfo,
630 @Context ResourceMap resourceMap,
631 @PathParam("csid") String parentspecifier,
632 @PathParam("itemcsid") String itemspecifier) {
633 PoxPayloadOut result = null;
635 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", uriInfo);
637 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx =
638 (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), resourceMap, uriInfo);
640 JaxRsContext jaxRsContext = new JaxRsContext(request, uriInfo); // REM - Why are we setting this? Who is using the getter?
641 ctx.setJaxRsContext(jaxRsContext);
643 // We omit the parentShortId, only needed when doing a create...
644 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
646 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
647 if (itemSpec.form == SpecifierForm.CSID) {
648 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
650 String itemWhereClause =
651 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
652 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
653 handler.setDocumentFilter(myFilter);
654 getRepositoryClient(ctx).get(ctx, handler);
656 // TODO should we assert that the item is in the passed vocab?
657 result = ctx.getOutput();
658 } catch (Exception e) {
659 throw bigReThrow(e, ServiceMessages.GET_FAILED);
661 if (result == null) {
662 Response response = Response.status(Response.Status.NOT_FOUND).entity(
663 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
664 "text/plain").build();
665 throw new WebApplicationException(response);
667 return result.getBytes();
671 * Most of the authority child classes will/should use this implementation. However, the Vocabulary service's item schema is
672 * different enough that it will have to override this method in it's resource class.
675 protected String getOrderByField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
676 String result = null;
678 result = NuxeoUtils.getPrimaryElPathPropertyName(
679 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
680 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
686 protected String getPartialTermMatchField(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
687 String result = null;
689 result = NuxeoUtils.getMultiElPathPropertyName(
690 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
691 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
697 * Gets the authorityItem list for the specified authority
698 * If partialPerm is specified, keywords will be ignored.
700 * @param specifier either a CSID or one of the urn forms
701 * @param partialTerm if non-null, matches partial terms
702 * @param keywords if non-null, matches terms in the keyword index for items
703 * @param ui passed to include additional parameters, like pagination controls
705 * @return the authorityItem list
708 @Path("{csid}/items")
709 @Produces("application/xml")
710 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
711 @Context UriInfo uriInfo) {
712 AbstractCommonList result = null;
715 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
716 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
718 String orderBy = queryParams.getFirst(IClientQueryParams.ORDER_BY_PARAM);
719 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
720 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
721 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
722 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
724 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
725 // We omit the parentShortId, only needed when doing a create...
726 String parentcsid = PARENT_WILDCARD.equals(specifier) ? null :
727 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", uriInfo);
728 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler =
729 createItemDocumentHandler(ctx, parentcsid, null);
731 DocumentFilter myFilter = handler.getDocumentFilter();
732 // If we are not wildcarding the parent, add a restriction
733 if (parentcsid != null) {
734 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
735 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
736 + "'" + parentcsid + "'",
737 IQueryManager.SEARCH_QUALIFIER_AND);
740 if (Tools.notBlank(termStatus)) {
741 // Start with the qualified termStatus field
742 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
743 + AuthorityItemJAXBSchema.TERM_STATUS;
744 String[] filterTerms = termStatus.trim().split("\\|");
745 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
746 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
749 result = search(ctx, handler, uriInfo, orderBy, keywords, advancedSearch, partialTerm);
750 } catch (Exception e) {
751 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
758 * @return the name of the property used to specify references for items in this type of
759 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
760 * Some types (like Vocabulary) use a separate property.
762 protected String getRefPropName() {
763 return ServiceBindingUtils.AUTH_REF_PROP;
767 * Gets the entities referencing this Authority item instance. The service type
768 * can be passed as a query param "type", and must match a configured type
769 * for the service bindings. If not set, the type defaults to
770 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
772 * @param parentspecifier either a CSID or one of the urn forms
773 * @param itemspecifier either a CSID or one of the urn forms
776 * @return the info for the referencing objects
779 @Path("{csid}/items/{itemcsid}/refObjs")
780 @Produces("application/xml")
781 public AuthorityRefDocList getReferencingObjects(
782 @PathParam("csid") String parentspecifier,
783 @PathParam("itemcsid") String itemspecifier,
784 @Context UriTemplateRegistry uriTemplateRegistry,
785 @Context UriInfo uriInfo) {
786 AuthorityRefDocList authRefDocList = null;
788 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
789 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
791 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", uriInfo);
792 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
794 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
795 if(serviceTypes == null || serviceTypes.isEmpty()) {
796 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
799 // Note that we have to create the service context for the Items, not the main service
800 // We omit the parentShortId, only needed when doing a create...
801 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
802 createItemDocumentHandler(ctx, parentcsid, null);
804 authRefDocList = handler.getReferencingObjects(ctx, uriTemplateRegistry, serviceTypes, getRefPropName(), itemcsid);
805 } catch (Exception e) {
806 throw bigReThrow(e, ServiceMessages.GET_FAILED);
808 if (authRefDocList == null) {
809 Response response = Response.status(Response.Status.NOT_FOUND).entity(
810 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
811 "text/plain").build();
812 throw new WebApplicationException(response);
814 return authRefDocList;
818 * Gets the authority terms used in the indicated Authority item.
820 * @param parentspecifier either a CSID or one of the urn forms
821 * @param itemspecifier either a CSID or one of the urn forms
822 * @param ui passed to include additional parameters, like pagination controls
824 * @return the authority refs for the Authority item.
827 @Path("{csid}/items/{itemcsid}/authorityrefs")
828 @Produces("application/xml")
829 public AuthorityRefList getAuthorityItemAuthorityRefs(
830 @PathParam("csid") String parentspecifier,
831 @PathParam("itemcsid") String itemspecifier,
832 @Context UriInfo uriInfo) {
833 AuthorityRefList authRefList = null;
835 // Note that we have to create the service context for the Items, not the main service
836 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), uriInfo);
837 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
838 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", uriInfo);
839 // We omit the parentShortId, only needed when doing a create...
840 DocumentModelHandler<?, AbstractCommonList> handler =
841 (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null /*no parent short ID*/);
843 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
845 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
846 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
847 } catch (Exception e) {
848 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
854 * Update authorityItem.
856 * @param parentspecifier either a CSID or one of the urn forms
857 * @param itemspecifier either a CSID or one of the urn forms
859 * @return the multipart output
862 @Path("{csid}/items/{itemcsid}")
863 public byte[] updateAuthorityItem(
864 @Context ResourceMap resourceMap,
866 @PathParam("csid") String parentspecifier,
867 @PathParam("itemcsid") String itemspecifier,
869 PoxPayloadOut result = null;
871 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
872 // Note that we have to create the service context for the Items, not the main service
873 //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
874 String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
876 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
877 ctx.setResourceMap(resourceMap);
878 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
880 // We omit the parentShortId, only needed when doing a create...
881 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
883 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
884 result = ctx.getOutput();
886 } catch (Exception e) {
887 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
889 return result.getBytes();
893 * Delete authorityItem.
895 * @param parentcsid the parentcsid
896 * @param itemcsid the itemcsid
898 * @return the response
901 @Path("{csid}/items/{itemcsid}")
902 public Response deleteAuthorityItem(
903 @PathParam("csid") String parentcsid,
904 @PathParam("itemcsid") String itemcsid) {
906 if (logger.isDebugEnabled()) {
907 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
910 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
911 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
912 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
913 // }catch (Throwable t){
914 // System.out.println("ERROR in setting up DELETE: "+t);
917 // Note that we have to create the service context for the Items, not the main service
918 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
919 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
920 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
921 return Response.status(HttpResponseCodes.SC_OK).build();
922 } catch (Exception e) {
923 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
926 public final static String hierarchy = "hierarchy";
929 @Path("{csid}/items/{itemcsid}/" + hierarchy)
930 @Produces("application/xml")
931 public String getHierarchy(@PathParam("csid") String csid,
932 @PathParam("itemcsid") String itemcsid,
933 @Context UriInfo ui) throws Exception {
935 // 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...?
936 String calledUri = ui.getPath();
937 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
938 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), ui);
940 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
941 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
942 return Hierarchy.surface(ctx, itemcsid, uri);
944 return Hierarchy.dive(ctx, itemcsid, uri);
946 } catch (Exception e) {
947 throw bigReThrow(e, "Error showing hierarchy", itemcsid);
951 protected String getItemDocType(String tenantId) {
952 return getDocType(tenantId, getItemServiceName());
956 * Returns a UriRegistry entry: a map of tenant-qualified URI templates
957 * for the current resource, for all tenants
959 * @return a map of URI templates for the current resource, for all tenants
962 public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
963 Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
964 super.getUriRegistryEntries();
965 List<String> tenantIds = getTenantBindingsReader().getTenantIds();
966 for (String tenantId : tenantIds) {
967 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getItemDocType(tenantId), UriTemplateFactory.ITEM));
969 return uriRegistryEntriesMap;