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.query.QueryManager;
50 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
51 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
52 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
53 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
54 import org.collectionspace.services.config.ClientType;
55 import org.collectionspace.services.jaxb.AbstractCommonList;
56 import org.collectionspace.services.lifecycle.TransitionDef;
57 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
58 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
59 import org.collectionspace.services.workflow.WorkflowCommon;
60 import org.jboss.resteasy.util.HttpResponseCodes;
61 import org.nuxeo.ecm.core.api.DocumentModel;
62 import org.nuxeo.ecm.core.api.DocumentModelList;
63 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
67 import javax.ws.rs.Consumes;
68 import javax.ws.rs.DELETE;
69 import javax.ws.rs.GET;
70 import javax.ws.rs.POST;
71 import javax.ws.rs.PUT;
72 import javax.ws.rs.Path;
73 import javax.ws.rs.PathParam;
74 import javax.ws.rs.Produces;
75 import javax.ws.rs.WebApplicationException;
76 import javax.ws.rs.core.Context;
77 import javax.ws.rs.core.MultivaluedMap;
78 import javax.ws.rs.core.Request;
79 import javax.ws.rs.core.Response;
80 import javax.ws.rs.core.UriBuilder;
81 import javax.ws.rs.core.UriInfo;
83 import java.util.HashMap;
84 import java.util.List;
86 import org.collectionspace.services.common.*;
88 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
89 import org.collectionspace.services.config.service.ServiceBindingType;
91 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
94 * The Class AuthorityResource.
100 * @param <AuthItemHandler>
105 * @param <AuthCommon>
106 * @param <AuthItemHandler>
108 @Consumes("application/xml")
109 @Produces("application/xml")
110 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
111 extends ResourceBase {
113 final static String SEARCH_TYPE_TERMSTATUS = "ts";
115 protected Class<AuthCommon> authCommonClass;
116 protected Class<?> resourceClass;
117 protected String authorityCommonSchemaName;
118 protected String authorityItemCommonSchemaName;
119 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
120 final static String URN_PREFIX = "urn:cspace:";
121 final static int URN_PREFIX_LEN = URN_PREFIX.length();
122 final static String URN_PREFIX_NAME = "name(";
123 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
124 final static String URN_PREFIX_ID = "id(";
125 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
126 final static String FETCH_SHORT_ID = "_fetch_";
127 final static String PARENT_WILDCARD = "_ALL_";
129 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
131 public enum SpecifierForm {
136 public class Specifier {
138 public SpecifierForm form;
141 Specifier(SpecifierForm form, String value) {
147 protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException {
148 if (logger.isDebugEnabled()) {
149 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
151 if (specifierIn != null) {
152 if (!specifierIn.startsWith(URN_PREFIX)) {
153 // We'll assume it is a CSID and complain if it does not match
154 return new Specifier(SpecifierForm.CSID, specifierIn);
156 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
157 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
158 if (closeParen >= 0) {
159 return new Specifier(SpecifierForm.URN_NAME,
160 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
162 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
163 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
164 if (closeParen >= 0) {
165 return new Specifier(SpecifierForm.CSID,
166 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
171 logger.error(method + ": bad or missing specifier!");
172 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
173 op + " failed on bad or missing Authority specifier").type(
174 "text/plain").build();
175 throw new WebApplicationException(response);
179 * Instantiates a new Authority resource.
181 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
182 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
183 this.authCommonClass = authCommonClass;
184 this.resourceClass = resourceClass;
185 this.authorityCommonSchemaName = authorityCommonSchemaName;
186 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
189 public abstract String getItemServiceName();
191 public abstract String getItemTermInfoGroupXPathBase();
194 protected String getVersionString() {
195 return "$LastChangedRevision: 2617 $";
199 public Class<AuthCommon> getCommonPartClass() {
200 return authCommonClass;
204 * Creates the item document handler.
207 * @param inAuthority the in vocabulary
209 * @return the document handler
211 * @throws Exception the exception
213 protected DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> createItemDocumentHandler(
214 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
215 String inAuthority, String parentShortIdentifier)
217 String authorityRefNameBase;
218 AuthorityItemDocumentModelHandler<?> docHandler;
220 if (parentShortIdentifier == null) {
221 authorityRefNameBase = null;
223 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
224 createServiceContext(getServiceName());
225 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
226 // Get from parent document
227 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
229 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
232 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
233 ctx.getCommonPartLabel(getItemServiceName()),
235 // FIXME - Richard and Aron think the following three lines should
236 // be in the constructor for the AuthorityItemDocumentModelHandler
237 // because all three are required fields.
238 docHandler.setInAuthority(inAuthority);
239 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
240 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
244 public String getAuthShortIdentifier(
245 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
246 throws DocumentNotFoundException, DocumentException {
247 String shortIdentifier = null;
249 AuthorityDocumentModelHandler<?> handler =
250 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
251 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
252 } catch (Exception e) {
253 if (logger.isDebugEnabled()) {
254 logger.debug("Caught exception ", e);
256 throw new DocumentException(e);
258 return shortIdentifier;
261 protected String buildAuthorityRefNameBase(
262 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
263 RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(),
264 ctx.getServiceName(), shortIdentifier, null);
265 return authority.toString();
268 public static class CsidAndShortIdentifier {
271 String shortIdentifier;
274 protected String lookupParentCSID(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
276 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams);
277 return tempResult.CSID;
280 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
282 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
283 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
284 // Note that we have to create the service context for the Items, not the main service
286 String parentShortIdentifier;
287 if (parentSpec.form == SpecifierForm.CSID) {
288 parentShortIdentifier = null;
289 parentcsid = parentSpec.value;
290 // Uncomment when app layer is ready to integrate
291 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
292 parentShortIdentifier = FETCH_SHORT_ID;
294 parentShortIdentifier = parentSpec.value;
295 String whereClause = buildWhereForAuthByName(parentSpec.value);
296 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getServiceName(), queryParams);
297 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
299 result.CSID = parentcsid;
300 result.shortIdentifier = parentShortIdentifier;
304 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx)
305 throws DocumentException {
307 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
308 if (itemSpec.form == SpecifierForm.CSID) {
309 itemcsid = itemSpec.value;
311 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
312 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
318 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
319 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
320 * Resource. They then call this method on that resource.
323 public DocumentModel getDocModelForAuthorityItem(RepositoryInstance repoSession, RefName.AuthorityItem item)
324 throws Exception, DocumentNotFoundException {
328 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
329 // Ensure we have the right context.
330 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(item.inAuthority.resource);
332 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
333 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
334 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
336 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
337 ctx = createServiceContext(getItemServiceName());
338 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
339 DocumentModel docModel = docWrapper.getWrappedObject();
344 @POST //FIXME: REM - 5/1/2012 - We can probably remove this method.
345 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.
347 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
348 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
349 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
350 String csid = getRepositoryClient(ctx).create(ctx, handler);
351 UriBuilder path = UriBuilder.fromResource(resourceClass);
352 path.path("" + csid);
353 Response response = Response.created(path.build()).build();
355 } catch (Exception e) {
356 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
360 protected String buildWhereForAuthByName(String name) {
361 return authorityCommonSchemaName
362 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
366 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
367 return authorityItemCommonSchemaName
368 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
369 + "='" + name + "' AND "
370 + authorityItemCommonSchemaName + ":"
371 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
372 + "'" + parentcsid + "'";
376 * Gets the authority.
378 * @param specifier either a CSID or one of the urn forms
380 * @return the authority
385 public byte[] get( // getAuthority(
387 @PathParam("csid") String specifier) {
388 PoxPayloadOut result = null;
390 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
391 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
393 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
394 if (spec.form == SpecifierForm.CSID) {
395 if (logger.isDebugEnabled()) {
396 logger.debug("getAuthority with csid=" + spec.value);
398 getRepositoryClient(ctx).get(ctx, spec.value, handler);
400 String whereClause = buildWhereForAuthByName(spec.value);
401 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
402 handler.setDocumentFilter(myFilter);
403 getRepositoryClient(ctx).get(ctx, handler);
405 result = ctx.getOutput();
407 } catch (Exception e) {
408 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
411 if (result == null) {
412 Response response = Response.status(Response.Status.NOT_FOUND).entity(
413 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
414 "text/plain").build();
415 throw new WebApplicationException(response);
418 return result.getBytes();
422 * Finds and populates the authority list.
426 * @return the authority list
429 @Produces("application/xml")
430 public AbstractCommonList getAuthorityList(@Context UriInfo ui) { //FIXME - REM 5/3/2012 - This is not reachable from the JAX-RS dispatcher. Instead the equivalent method in ResourceBase is getting called.
432 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
433 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
434 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
435 DocumentFilter myFilter = handler.getDocumentFilter();
436 // Need to make the default sort order for authority items
437 // be on the displayName field
438 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
439 if (sortBy == null || sortBy.isEmpty()) {
440 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
441 + AuthorityItemJAXBSchema.DISPLAY_NAME;
442 myFilter.setOrderByClause(qualifiedDisplayNameField);
444 String nameQ = queryParams.getFirst("refName");
446 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
448 getRepositoryClient(ctx).getFiltered(ctx, handler);
449 return handler.getCommonPartList();
450 } catch (Exception e) {
451 throw bigReThrow(e, ServiceMessages.GET_FAILED);
459 * @param specifier the csid or id
461 * @return the multipart output
465 public byte[] updateAuthority(
466 @PathParam("csid") String specifier,
468 PoxPayloadOut result = null;
470 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
471 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
472 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
473 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
475 if (spec.form == SpecifierForm.CSID) {
478 String whereClause = buildWhereForAuthByName(spec.value);
479 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
481 getRepositoryClient(ctx).update(ctx, csid, handler);
482 result = ctx.getOutput();
483 } catch (Exception e) {
484 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
486 return result.getBytes();
492 * @param csid the csid
494 * @return the response
498 public Response deleteAuthority(@PathParam("csid") String csid) {
499 if (logger.isDebugEnabled()) {
500 logger.debug("deleteAuthority with csid=" + csid);
503 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
504 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
505 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
506 getRepositoryClient(ctx).delete(ctx, csid, handler);
507 return Response.status(HttpResponseCodes.SC_OK).build();
508 } catch (Exception e) {
509 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
513 /*************************************************************************
514 * Create an AuthorityItem - this is a sub-resource of Authority
515 * @param specifier either a CSID or one of the urn forms
516 * @return Authority item response
517 *************************************************************************/
519 @Path("{csid}/items")
520 public Response createAuthorityItem(@Context ResourceMap resourceMap, @Context UriInfo ui,
521 @PathParam("csid") String specifier, String xmlPayload) {
523 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
524 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), input);
525 ctx.setResourceMap(resourceMap);
526 ctx.setUriInfo(ui); //Laramie
528 // Note: must have the parentShortId, to do the create.
529 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
530 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
531 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
532 UriBuilder path = UriBuilder.fromResource(resourceClass);
533 path.path(parent.CSID + "/items/" + itemcsid);
534 Response response = Response.created(path.build()).build();
536 } catch (Exception e) {
537 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
542 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
543 public byte[] getItemWorkflow(
544 @PathParam("csid") String csid,
545 @PathParam("itemcsid") String itemcsid) {
546 PoxPayloadOut result = null;
549 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
550 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
552 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
553 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
554 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
555 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
556 result = ctx.getOutput();
557 } catch (Exception e) {
558 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
560 return result.getBytes();
563 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
564 // they should be consolidated -be DRY (don't repeat yourself).
566 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
567 public byte[] updateItemWorkflowWithTransition(
568 @PathParam("csid") String csid,
569 @PathParam("itemcsid") String itemcsid,
570 @PathParam("transition") String transition) {
571 PoxPayloadOut result = null;
575 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
576 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
577 WorkflowClient.SERVICE_COMMONPART_NAME);
578 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
580 // Create a service context and document handler for the parent resource.
581 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
582 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> parentDocHandler = this.createDocumentHandler(parentCtx);
583 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
585 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
586 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
587 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
589 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
590 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
591 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
593 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
594 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
595 result = ctx.getOutput();
596 } catch (Exception e) {
597 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
600 return result.getBytes();
604 * Gets the authority item.
606 * @param parentspecifier either a CSID or one of the urn forms
607 * @param itemspecifier either a CSID or one of the urn forms
609 * @return the authority item
612 @Path("{csid}/items/{itemcsid}")
613 public byte[] getAuthorityItem(
614 @Context Request request,
616 @PathParam("csid") String parentspecifier,
617 @PathParam("itemcsid") String itemspecifier) {
618 PoxPayloadOut result = null;
620 JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
621 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
622 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
624 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
625 ctx = (RemoteServiceContext<PoxPayloadIn, PoxPayloadOut>) createServiceContext(getItemServiceName(), queryParams);
626 ctx.setJaxRsContext(jaxRsContext);
628 ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui.
630 // We omit the parentShortId, only needed when doing a create...
631 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
633 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
634 if (itemSpec.form == SpecifierForm.CSID) {
635 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
637 String itemWhereClause =
638 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
639 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
640 handler.setDocumentFilter(myFilter);
641 getRepositoryClient(ctx).get(ctx, handler);
643 // TODO should we assert that the item is in the passed vocab?
644 result = ctx.getOutput();
645 } catch (Exception e) {
646 throw bigReThrow(e, ServiceMessages.GET_FAILED);
648 if (result == null) {
649 Response response = Response.status(Response.Status.NOT_FOUND).entity(
650 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
651 "text/plain").build();
652 throw new WebApplicationException(response);
654 return result.getBytes();
658 * Most of the authority child classes will/should use this implementation. However, the Vocabulary service's item schema is
659 * different enough that it will have to override this method in it's resource class.
661 protected String getOrderByField() {
662 String result = null;
664 result = NuxeoUtils.getPrimaryElPathPropertyName(
665 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
666 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
671 protected String getPartialTermMatchField() {
672 String result = null;
674 result = NuxeoUtils.getMultiElPathPropertyName(
675 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
676 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
682 * Gets the authorityItem list for the specified authority
683 * If partialPerm is specified, keywords will be ignored.
685 * @param specifier either a CSID or one of the urn forms
686 * @param partialTerm if non-null, matches partial terms
687 * @param keywords if non-null, matches terms in the keyword index for items
688 * @param ui passed to include additional parameters, like pagination controls
690 * @return the authorityItem list
693 @Path("{csid}/items")
694 @Produces("application/xml")
695 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
696 @Context UriInfo ui) {
698 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
699 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
700 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
701 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
702 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
704 // Note that docType defaults to the ServiceName, so we're fine with that.
705 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
707 String parentcsid = PARENT_WILDCARD.equals(specifier)?null:
708 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
710 ctx = createServiceContext(getItemServiceName(), queryParams);
712 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
713 // We omit the parentShortId, only needed when doing a create...
714 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
716 DocumentFilter myFilter = handler.getDocumentFilter();
717 // Need to make the default sort order for authority items
718 // be on the displayName field
719 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
720 if (sortBy == null || sortBy.isEmpty()) {
721 String orderByField = getOrderByField();
722 myFilter.setOrderByClause(orderByField);
725 // If we are not wildcarding the parent, add a restriction
726 if(parentcsid!=null) {
727 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
728 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
729 + "'" + parentcsid + "'",
730 IQueryManager.SEARCH_QUALIFIER_AND);
733 if (Tools.notBlank(termStatus)) {
734 // Start with the qualified termStatus field
735 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
736 + AuthorityItemJAXBSchema.TERM_STATUS;
737 String[] filterTerms = termStatus.trim().split("\\|");
738 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
739 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
742 // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
743 // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
744 // the PT query param trumps the KW and AS query params.
745 if (partialTerm != null && !partialTerm.isEmpty()) {
746 String partialTermMatchField = getPartialTermMatchField();
747 String ptClause = QueryManager.createWhereClauseForPartialMatch(
748 partialTermMatchField, partialTerm);
749 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
750 } else if (keywords != null || advancedSearch != null) {
751 // String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
752 // myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
753 return search(ctx, handler, queryParams, keywords, advancedSearch);
755 if (logger.isDebugEnabled()) {
756 logger.debug("getAuthorityItemList filtered WHERE clause: "
757 + myFilter.getWhereClause()
758 + " and ORDER BY clause: " + myFilter.getOrderByClause());
760 getRepositoryClient(ctx).getFiltered(ctx, handler);
761 return handler.getCommonPartList();
762 } catch (Exception e) {
763 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
768 * @return the name of the property used to specify references for items in this type of
769 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
770 * Some types (like Vocabulary) use a separate property.
772 protected String getRefPropName() {
773 return ServiceBindingUtils.AUTH_REF_PROP;
777 * Gets the entities referencing this Authority item instance. The service type
778 * can be passed as a query param "type", and must match a configured type
779 * for the service bindings. If not set, the type defaults to
780 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
782 * @param parentspecifier either a CSID or one of the urn forms
783 * @param itemspecifier either a CSID or one of the urn forms
786 * @return the info for the referencing objects
789 @Path("{csid}/items/{itemcsid}/refObjs")
790 @Produces("application/xml")
791 public AuthorityRefDocList getReferencingObjects(
792 @PathParam("csid") String parentspecifier,
793 @PathParam("itemcsid") String itemspecifier,
794 @Context UriInfo ui) {
795 AuthorityRefDocList authRefDocList = null;
797 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
799 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
801 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
802 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
804 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
805 if(serviceTypes == null || serviceTypes.isEmpty()) {
806 serviceTypes = ServiceBindingUtils.getCommonServiceTypes(true); //CSPACE-5359: Should now include objects, procedures, and authorities
809 // Note that we have to create the service context for the Items, not the main service
810 // We omit the parentShortId, only needed when doing a create...
811 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
812 createItemDocumentHandler(ctx, parentcsid, null);
814 authRefDocList = handler.getReferencingObjects(ctx, serviceTypes, getRefPropName(), itemcsid);
815 } catch (Exception e) {
816 throw bigReThrow(e, ServiceMessages.GET_FAILED);
818 if (authRefDocList == null) {
819 Response response = Response.status(Response.Status.NOT_FOUND).entity(
820 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
821 "text/plain").build();
822 throw new WebApplicationException(response);
824 return authRefDocList;
828 * Gets the authority terms used in the indicated Authority item.
830 * @param parentspecifier either a CSID or one of the urn forms
831 * @param itemspecifier either a CSID or one of the urn forms
832 * @param ui passed to include additional parameters, like pagination controls
834 * @return the authority refs for the Authority item.
837 @Path("{csid}/items/{itemcsid}/authorityrefs")
838 @Produces("application/xml")
839 public AuthorityRefList getAuthorityItemAuthorityRefs(
840 @PathParam("csid") String parentspecifier,
841 @PathParam("itemcsid") String itemspecifier,
842 @Context UriInfo ui) {
843 AuthorityRefList authRefList = null;
845 // Note that we have to create the service context for the Items, not the main service
846 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
847 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
849 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
851 ctx = createServiceContext(getItemServiceName(), queryParams);
852 // We omit the parentShortId, only needed when doing a create...
853 DocumentModelHandler<?, AbstractCommonList> handler =
854 (DocumentModelHandler<?, AbstractCommonList>)createItemDocumentHandler(ctx, parentcsid, null);
856 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
858 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
859 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
860 } catch (Exception e) {
861 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
867 * Update authorityItem.
869 * @param parentspecifier either a CSID or one of the urn forms
870 * @param itemspecifier either a CSID or one of the urn forms
872 * @return the multipart output
875 @Path("{csid}/items/{itemcsid}")
876 public byte[] updateAuthorityItem(
877 @Context ResourceMap resourceMap,
879 @PathParam("csid") String parentspecifier,
880 @PathParam("itemcsid") String itemspecifier,
882 PoxPayloadOut result = null;
884 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
885 // Note that we have to create the service context for the Items, not the main service
886 //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
887 String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
889 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
890 ctx.setResourceMap(resourceMap);
891 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
893 // We omit the parentShortId, only needed when doing a create...
894 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createItemDocumentHandler(ctx, parentcsid, null);
896 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
897 result = ctx.getOutput();
899 } catch (Exception e) {
900 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
902 return result.getBytes();
906 * Delete authorityItem.
908 * @param parentcsid the parentcsid
909 * @param itemcsid the itemcsid
911 * @return the response
914 @Path("{csid}/items/{itemcsid}")
915 public Response deleteAuthorityItem(
916 @PathParam("csid") String parentcsid,
917 @PathParam("itemcsid") String itemcsid) {
919 if (logger.isDebugEnabled()) {
920 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
923 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
924 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
925 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
926 // }catch (Throwable t){
927 // System.out.println("ERROR in setting up DELETE: "+t);
930 // Note that we have to create the service context for the Items, not the main service
931 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
932 DocumentHandler<?, AbstractCommonList, DocumentModel, DocumentModelList> handler = createDocumentHandler(ctx);
933 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
934 return Response.status(HttpResponseCodes.SC_OK).build();
935 } catch (Exception e) {
936 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
939 public final static String hierarchy = "hierarchy";
942 @Path("{csid}/items/{itemcsid}/" + hierarchy)
943 @Produces("application/xml")
944 public String getHierarchy(@PathParam("csid") String csid,
945 @PathParam("itemcsid") String itemcsid,
946 @Context UriInfo ui) throws Exception {
948 // 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...?
949 String calledUri = ui.getPath();
950 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
951 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName());
953 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
954 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
955 return Hierarchy.surface(ctx, itemcsid, uri);
957 return Hierarchy.dive(ctx, itemcsid, uri);
959 } catch (Exception e) {
960 throw bigReThrow(e, "Error showing hierarchy", itemcsid);
964 protected String getItemDocType(String tenantId) {
965 return super.getDocType(tenantId, getItemServiceName());
969 * Constructs and returns a map of URI templates for the current resource,
970 * for the specified tenant
972 * @param tenantId a tenant ID
973 * @return a map of URI templates for the current resource, for the specified tenant
976 protected Map<String,StoredValuesUriTemplate> getUriTemplateMap(String tenantId) {
977 // Get the resource URI template from the superclass
978 Map<String,StoredValuesUriTemplate> uriTemplateMap = super.getUriTemplateMap(tenantId);
979 // Add the item URI template here, and return both templates in the map
980 String itemDocType = getItemDocType(tenantId);
981 if (itemDocType == null) {
982 return uriTemplateMap; // return map as obtained from superclass
984 StoredValuesUriTemplate itemUriTemplate = getUriTemplate(UriTemplateFactory.ITEM);
985 if (itemUriTemplate == null) {
986 return uriTemplateMap; // return map as obtained from superclass
988 uriTemplateMap.put(itemDocType, itemUriTemplate);
989 return uriTemplateMap;