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.ClientType;
32 import org.collectionspace.services.common.ResourceBase;
33 import org.collectionspace.services.common.ResourceMap;
34 import org.collectionspace.services.common.ServiceMain;
35 import org.collectionspace.services.common.ServiceMessages;
36 import org.collectionspace.services.common.XmlTools;
37 import org.collectionspace.services.common.api.RefName;
38 import org.collectionspace.services.common.api.Tools;
39 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
40 import org.collectionspace.services.common.authorityref.AuthorityRefList;
41 import org.collectionspace.services.common.context.JaxRsContext;
42 import org.collectionspace.services.common.context.MultipartServiceContext;
43 import org.collectionspace.services.common.context.MultipartServiceContextImpl;
44 import org.collectionspace.services.common.context.RemoteServiceContext;
45 import org.collectionspace.services.common.context.ServiceBindingUtils;
46 import org.collectionspace.services.common.context.ServiceContext;
47 import org.collectionspace.services.common.document.DocumentException;
48 import org.collectionspace.services.common.document.DocumentFilter;
49 import org.collectionspace.services.common.document.DocumentHandler;
50 import org.collectionspace.services.common.document.DocumentNotFoundException;
51 import org.collectionspace.services.common.document.DocumentWrapper;
52 import org.collectionspace.services.common.query.QueryManager;
53 import org.collectionspace.services.common.repository.RepositoryClient;
54 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
55 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
56 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
57 import org.collectionspace.services.jaxb.AbstractCommonList;
58 import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl;
59 import org.collectionspace.services.relation.RelationResource;
60 import org.collectionspace.services.relation.RelationsCommonList;
61 import org.collectionspace.services.relation.RelationshipType;
62 import org.jboss.resteasy.util.HttpResponseCodes;
63 import org.nuxeo.ecm.core.api.DocumentModel;
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.QueryParam;
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.ArrayList;
85 import java.util.List;
88 * The Class AuthorityResource.
94 * @param <AuthItemHandler>
100 * @param <AuthItemHandler>
102 @Consumes("application/xml")
103 @Produces("application/xml")
104 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
105 extends ResourceBase {
107 protected Class<AuthCommon> authCommonClass;
108 protected Class<?> resourceClass;
109 protected String authorityCommonSchemaName;
110 protected String authorityItemCommonSchemaName;
111 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType();
112 final static String URN_PREFIX = "urn:cspace:";
113 final static int URN_PREFIX_LEN = URN_PREFIX.length();
114 final static String URN_PREFIX_NAME = "name(";
115 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
116 final static String URN_PREFIX_ID = "id(";
117 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
118 final static String FETCH_SHORT_ID = "_fetch_";
119 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
121 public enum SpecifierForm {
126 public class Specifier {
128 public SpecifierForm form;
131 Specifier(SpecifierForm form, String value) {
137 protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException {
138 if (logger.isDebugEnabled()) {
139 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
141 if (specifierIn != null) {
142 if (!specifierIn.startsWith(URN_PREFIX)) {
143 // We'll assume it is a CSID and complain if it does not match
144 return new Specifier(SpecifierForm.CSID, specifierIn);
146 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
147 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
148 if (closeParen >= 0) {
149 return new Specifier(SpecifierForm.URN_NAME,
150 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
152 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
153 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
154 if (closeParen >= 0) {
155 return new Specifier(SpecifierForm.CSID,
156 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
161 logger.error(method + ": bad or missing specifier!");
162 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
163 op + " failed on bad or missing Authority specifier").type(
164 "text/plain").build();
165 throw new WebApplicationException(response);
169 * Instantiates a new Authority resource.
171 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
172 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
173 this.authCommonClass = authCommonClass;
174 this.resourceClass = resourceClass;
175 this.authorityCommonSchemaName = authorityCommonSchemaName;
176 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
179 public abstract String getItemServiceName();
182 protected String getVersionString() {
183 return "$LastChangedRevision: 2617 $";
187 public Class<AuthCommon> getCommonPartClass() {
188 return authCommonClass;
192 * Creates the item document handler.
195 * @param inAuthority the in vocabulary
197 * @return the document handler
199 * @throws Exception the exception
201 protected DocumentHandler createItemDocumentHandler(
202 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
203 String inAuthority, String parentShortIdentifier)
205 String authorityRefNameBase;
206 AuthorityItemDocumentModelHandler<?> docHandler;
208 if (parentShortIdentifier == null) {
209 authorityRefNameBase = null;
211 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
212 createServiceContext(getServiceName());
213 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
214 // Get from parent document
215 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
217 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
220 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
221 ctx.getCommonPartLabel(getItemServiceName()),
223 docHandler.setInAuthority(inAuthority);
224 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
229 public String getAuthShortIdentifier(
230 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
231 throws DocumentNotFoundException, DocumentException {
232 String shortIdentifier = null;
234 DocumentWrapper<DocumentModel> wrapDoc = getRepositoryClient(ctx).getDocFromCsid(ctx, authCSID);
235 AuthorityDocumentModelHandler<?> handler =
236 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
237 shortIdentifier = handler.getShortIdentifier(wrapDoc, authorityCommonSchemaName);
238 } catch (Exception e) {
239 if (logger.isDebugEnabled()) {
240 logger.debug("Caught exception ", e);
242 throw new DocumentException(e);
244 return shortIdentifier;
247 protected String buildAuthorityRefNameBase(
248 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
249 RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(),
250 ctx.getServiceName(), shortIdentifier, null);
251 return authority.toString();
254 public static class CsidAndShortIdentifier {
257 String shortIdentifier;
260 public String lookupParentCSID(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
262 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams);
263 return tempResult.CSID;
266 public CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
268 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
269 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
270 // Note that we have to create the service context for the Items, not the main service
272 String parentShortIdentifier;
273 if (parentSpec.form == SpecifierForm.CSID) {
274 parentShortIdentifier = null;
275 parentcsid = parentSpec.value;
276 // Uncomment when app layer is ready to integrate
277 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
278 parentShortIdentifier = FETCH_SHORT_ID;
280 parentShortIdentifier = parentSpec.value;
281 String whereClause = buildWhereForAuthByName(parentSpec.value);
282 ServiceContext ctx = createServiceContext(getServiceName(), queryParams);
283 parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
285 result.CSID = parentcsid;
286 result.shortIdentifier = parentShortIdentifier;
290 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext ctx)
291 throws DocumentException {
293 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
294 if (itemSpec.form == SpecifierForm.CSID) {
295 itemcsid = itemSpec.value;
297 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
298 itemcsid = getRepositoryClient(ctx).findDocCSID(ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
304 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
305 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
306 * Resource. They then call this method on that resource.
309 public DocumentModel getDocModelForAuthorityItem(RefName.AuthorityItem item)
310 throws Exception, DocumentNotFoundException {
314 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
315 // Ensure we have the right context.
316 ServiceContext ctx = createServiceContext(item.inAuthority.resource);
318 String parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
320 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
321 ctx = createServiceContext(getItemServiceName());
322 DocumentWrapper<DocumentModel> docWrapper = getRepositoryClient(ctx).findDoc(ctx, itemWhereClause);
323 DocumentModel docModel = docWrapper.getWrappedObject();
329 public Response createAuthority(String xmlPayload) {
331 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
332 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
333 DocumentHandler handler = createDocumentHandler(ctx);
334 String csid = getRepositoryClient(ctx).create(ctx, handler);
335 UriBuilder path = UriBuilder.fromResource(resourceClass);
336 path.path("" + csid);
337 Response response = Response.created(path.build()).build();
339 } catch (Exception e) {
340 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
344 protected String buildWhereForAuthByName(String name) {
345 return authorityCommonSchemaName
346 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
350 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
351 return authorityItemCommonSchemaName
352 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
353 + "='" + name + "' AND "
354 + authorityItemCommonSchemaName + ":"
355 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
356 + "'" + parentcsid + "'";
360 * Gets the authority.
362 * @param specifier either a CSID or one of the urn forms
364 * @return the authority
369 public byte[] get( // getAuthority(
371 @PathParam("csid") String specifier) {
372 PoxPayloadOut result = null;
374 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
375 DocumentHandler handler = createDocumentHandler(ctx);
377 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
378 if (spec.form == SpecifierForm.CSID) {
379 if (logger.isDebugEnabled()) {
380 logger.debug("getAuthority with csid=" + spec.value);
382 getRepositoryClient(ctx).get(ctx, spec.value, handler);
384 String whereClause = buildWhereForAuthByName(spec.value);
385 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
386 handler.setDocumentFilter(myFilter);
387 getRepositoryClient(ctx).get(ctx, handler);
389 result = ctx.getOutput();
391 } catch (Exception e) {
392 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
395 if (result == null) {
396 Response response = Response.status(Response.Status.NOT_FOUND).entity(
397 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
398 "text/plain").build();
399 throw new WebApplicationException(response);
402 return result.getBytes();
406 * Finds and populates the authority list.
410 * @return the authority list
413 @Produces("application/xml")
414 public AbstractCommonList getAuthorityList(@Context UriInfo ui) {
416 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
417 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
418 DocumentHandler handler = createDocumentHandler(ctx);
419 DocumentFilter myFilter = handler.getDocumentFilter();
420 // Need to make the default sort order for authority items
421 // be on the displayName field
422 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
423 if (sortBy == null || sortBy.isEmpty()) {
424 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
425 + AuthorityItemJAXBSchema.DISPLAY_NAME;
426 myFilter.setOrderByClause(qualifiedDisplayNameField);
428 String nameQ = queryParams.getFirst("refName");
430 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
432 getRepositoryClient(ctx).getFiltered(ctx, handler);
433 return (AbstractCommonList) handler.getCommonPartList();
434 } catch (Exception e) {
435 throw bigReThrow(e, ServiceMessages.GET_FAILED);
442 * @param specifier the csid or id
444 * @return the multipart output
448 public byte[] updateAuthority(
449 @PathParam("csid") String specifier,
451 PoxPayloadOut result = null;
453 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
454 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
455 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
456 DocumentHandler handler = createDocumentHandler(ctx);
458 if (spec.form == SpecifierForm.CSID) {
461 String whereClause = buildWhereForAuthByName(spec.value);
462 csid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
464 getRepositoryClient(ctx).update(ctx, csid, handler);
465 result = ctx.getOutput();
466 } catch (Exception e) {
467 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
469 return result.getBytes();
475 * @param csid the csid
477 * @return the response
481 public Response deleteAuthority(@PathParam("csid") String csid) {
482 if (logger.isDebugEnabled()) {
483 logger.debug("deleteAuthority with csid=" + csid);
486 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
487 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
488 getRepositoryClient(ctx).delete(ctx, csid);
489 return Response.status(HttpResponseCodes.SC_OK).build();
490 } catch (Exception e) {
491 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
495 /*************************************************************************
496 * Create an AuthorityItem - this is a sub-resource of Authority
497 * @param specifier either a CSID or one of the urn forms
498 * @return Authority item response
499 *************************************************************************/
501 @Path("{csid}/items")
502 public Response createAuthorityItem(@Context ResourceMap resourceMap, @Context UriInfo ui,
503 @PathParam("csid") String specifier, String xmlPayload) {
505 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
506 ServiceContext ctx = createServiceContext(getItemServiceName(), input);
507 ctx.setResourceMap(resourceMap);
508 ctx.setUriInfo(ui); //Laramie
510 // Note: must have the parentShortId, to do the create.
511 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
512 DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
513 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
514 UriBuilder path = UriBuilder.fromResource(resourceClass);
515 path.path(parent.CSID + "/items/" + itemcsid);
516 Response response = Response.created(path.build()).build();
518 } catch (Exception e) {
519 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
524 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
525 public byte[] getItemWorkflow(
526 @PathParam("csid") String csid,
527 @PathParam("itemcsid") String itemcsid) {
528 PoxPayloadOut result = null;
531 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
532 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
534 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
535 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
536 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
537 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
538 result = ctx.getOutput();
539 } catch (Exception e) {
540 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
542 return result.getBytes();
546 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
547 public byte[] updateWorkflow(
548 @PathParam("csid") String csid,
549 @PathParam("itemcsid") String itemcsid,
551 PoxPayloadOut result = null;
553 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
554 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
556 PoxPayloadIn workflowUpdate = new PoxPayloadIn(xmlPayload);
557 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, workflowUpdate);
558 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
559 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
560 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
561 result = ctx.getOutput();
562 } catch (Exception e) {
563 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
565 return result.getBytes();
569 * Gets the authority item.
571 * @param parentspecifier either a CSID or one of the urn forms
572 * @param itemspecifier either a CSID or one of the urn forms
574 * @return the authority item
577 @Path("{csid}/items/{itemcsid}")
578 public byte[] getAuthorityItem(
579 @Context Request request,
581 @PathParam("csid") String parentspecifier,
582 @PathParam("itemcsid") String itemspecifier) {
583 PoxPayloadOut result = null;
585 JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
586 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
587 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
589 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
590 ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
591 ctx.setJaxRsContext(jaxRsContext);
593 ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui.
595 // We omit the parentShortId, only needed when doing a create...
596 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
598 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
599 if (itemSpec.form == SpecifierForm.CSID) {
600 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
602 String itemWhereClause =
603 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
604 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
605 handler.setDocumentFilter(myFilter);
606 getRepositoryClient(ctx).get(ctx, handler);
608 // TODO should we assert that the item is in the passed vocab?
609 result = ctx.getOutput();
610 } catch (Exception e) {
611 throw bigReThrow(e, ServiceMessages.GET_FAILED);
613 if (result == null) {
614 Response response = Response.status(Response.Status.NOT_FOUND).entity(
615 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
616 "text/plain").build();
617 throw new WebApplicationException(response);
619 return result.getBytes();
623 * Gets the authorityItem list for the specified authority
624 * If partialPerm is specified, keywords will be ignored.
626 * @param specifier either a CSID or one of the urn forms
627 * @param partialTerm if non-null, matches partial terms
628 * @param keywords if non-null, matches terms in the keyword index for items
629 * @param ui passed to include additional parameters, like pagination controls
631 * @return the authorityItem list
634 @Path("{csid}/items")
635 @Produces("application/xml")
636 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
637 @Context UriInfo ui) {
639 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
640 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
641 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
642 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
644 String qualifiedDisplayNameField = authorityItemCommonSchemaName + ":"
645 + AuthorityItemJAXBSchema.DISPLAY_NAME;
647 // Note that docType defaults to the ServiceName, so we're fine with that.
648 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
650 String parentcsid = lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
652 ctx = createServiceContext(getItemServiceName(), queryParams);
653 // We omit the parentShortId, only needed when doing a create...
654 DocumentHandler handler = createItemDocumentHandler(ctx,
656 DocumentFilter myFilter = handler.getDocumentFilter();
657 // Need to make the default sort order for authority items
658 // be on the displayName field
659 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
660 if (sortBy == null || sortBy.isEmpty()) {
661 myFilter.setOrderByClause(qualifiedDisplayNameField);
664 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
665 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
666 + "'" + parentcsid + "'",
667 IQueryManager.SEARCH_QUALIFIER_AND);
669 // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
670 // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
671 // the PT query param trumps the KW and AS query params.
672 if (partialTerm != null && !partialTerm.isEmpty()) {
673 String ptClause = QueryManager.createWhereClauseForPartialMatch(
674 qualifiedDisplayNameField, partialTerm);
675 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
676 } else if (keywords != null || advancedSearch != null) {
677 // String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
678 // myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
679 return search(ctx, handler, queryParams, keywords, advancedSearch);
681 if (logger.isDebugEnabled()) {
682 logger.debug("getAuthorityItemList filtered WHERE clause: "
683 + myFilter.getWhereClause());
685 getRepositoryClient(ctx).getFiltered(ctx, handler);
686 return (AbstractCommonList) handler.getCommonPartList();
687 } catch (Exception e) {
688 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
693 * @return the name of the property used to specify references for items in this type of
694 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
695 * Some types (like Vocabulary) use a separate property.
697 protected String getRefPropName() {
698 return ServiceBindingUtils.AUTH_REF_PROP;
702 * Gets the entities referencing this Authority item instance. The service type
703 * can be passed as a query param "type", and must match a configured type
704 * for the service bindings. If not set, the type defaults to
705 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
707 * @param parentspecifier either a CSID or one of the urn forms
708 * @param itemspecifier either a CSID or one of the urn forms
711 * @return the info for the referencing objects
714 @Path("{csid}/items/{itemcsid}/refObjs")
715 @Produces("application/xml")
716 public AuthorityRefDocList getReferencingObjects(
717 @PathParam("csid") String parentspecifier,
718 @PathParam("itemcsid") String itemspecifier,
719 @Context UriInfo ui) {
720 AuthorityRefDocList authRefDocList = null;
722 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
724 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
726 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
727 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
729 // Note that we have to create the service context for the Items, not the main service
730 // We omit the parentShortId, only needed when doing a create...
731 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
732 RepositoryClient repoClient = getRepositoryClient(ctx);
733 DocumentFilter myFilter = handler.getDocumentFilter();
734 String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE;
735 List<String> list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
737 serviceType = list.get(0);
739 DocumentWrapper<DocumentModel> docWrapper = repoClient.getDoc(ctx, itemcsid);
740 DocumentModel docModel = docWrapper.getWrappedObject();
741 String refName = (String) docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
743 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(ctx,
748 myFilter.getPageSize(), myFilter.getStartPage(), true /*computeTotal*/);
749 } catch (Exception e) {
750 throw bigReThrow(e, ServiceMessages.GET_FAILED);
752 if (authRefDocList == null) {
753 Response response = Response.status(Response.Status.NOT_FOUND).entity(
754 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
755 "text/plain").build();
756 throw new WebApplicationException(response);
758 return authRefDocList;
762 * Gets the authority terms used in the indicated Authority item.
764 * @param parentspecifier either a CSID or one of the urn forms
765 * @param itemspecifier either a CSID or one of the urn forms
766 * @param ui passed to include additional parameters, like pagination controls
768 * @return the authority refs for the Authority item.
771 @Path("{csid}/items/{itemcsid}/authorityrefs")
772 @Produces("application/xml")
773 public AuthorityRefList getAuthorityItemAuthorityRefs(
774 @PathParam("csid") String parentspecifier,
775 @PathParam("itemcsid") String itemspecifier,
776 @Context UriInfo ui) {
777 AuthorityRefList authRefList = null;
779 // Note that we have to create the service context for the Items, not the main service
780 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
781 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
783 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
785 ctx = createServiceContext(getItemServiceName(), queryParams);
786 // We omit the parentShortId, only needed when doing a create...
787 RemoteDocumentModelHandlerImpl handler =
788 (RemoteDocumentModelHandlerImpl) createItemDocumentHandler(ctx, parentcsid, null);
790 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
792 DocumentWrapper<DocumentModel> docWrapper = getRepositoryClient(ctx).getDoc(ctx, itemcsid);
793 List<String> authRefFields =
794 ((MultipartServiceContextImpl) ctx).getCommonPartPropertyValues(
795 ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
796 authRefList = handler.getAuthorityRefs(docWrapper, authRefFields);
797 } catch (Exception e) {
798 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
804 * Update authorityItem.
806 * @param parentspecifier either a CSID or one of the urn forms
807 * @param itemspecifier either a CSID or one of the urn forms
809 * @return the multipart output
812 @Path("{csid}/items/{itemcsid}")
813 public byte[] updateAuthorityItem(
814 @Context ResourceMap resourceMap,
816 @PathParam("csid") String parentspecifier,
817 @PathParam("itemcsid") String itemspecifier,
819 PoxPayloadOut result = null;
821 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
822 // Note that we have to create the service context for the Items, not the main service
823 //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
824 String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
826 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
827 ctx.setResourceMap(resourceMap);
828 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
830 // We omit the parentShortId, only needed when doing a create...
831 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
833 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
834 result = ctx.getOutput();
836 } catch (Exception e) {
837 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
839 return result.getBytes();
843 * Delete authorityItem.
845 * @param parentcsid the parentcsid
846 * @param itemcsid the itemcsid
848 * @return the response
851 @Path("{csid}/items/{itemcsid}")
852 public Response deleteAuthorityItem(
853 @PathParam("csid") String parentcsid,
854 @PathParam("itemcsid") String itemcsid) {
856 if (logger.isDebugEnabled()) {
857 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
860 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
861 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
862 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
863 // }catch (Throwable t){
864 // System.out.println("ERROR in setting up DELETE: "+t);
867 // Note that we have to create the service context for the Items, not the main service
868 ServiceContext ctx = createServiceContext(getItemServiceName());
869 getRepositoryClient(ctx).delete(ctx, itemcsid);
870 return Response.status(HttpResponseCodes.SC_OK).build();
871 } catch (Exception e) {
872 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
875 public final static String hierarchy = "hierarchy";
878 @Path("{csid}/items/{itemcsid}/" + hierarchy)
879 @Produces("application/xml")
880 public String getHierarchy(@PathParam("csid") String csid,
881 @PathParam("itemcsid") String itemcsid,
882 @Context UriInfo ui) throws Exception {
884 // 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...?
885 String calledUri = ui.getPath();
886 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
887 ServiceContext ctx = createServiceContext(getItemServiceName());
889 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
890 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
891 return Hierarchy.surface(ctx, itemcsid, uri);
893 return Hierarchy.dive(ctx, itemcsid, uri);
895 } catch (Exception e) {
896 throw bigReThrow(e, "Error showing hierarchy", itemcsid);