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.RefNameServiceUtils;
55 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
56 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
57 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
58 import org.collectionspace.services.jaxb.AbstractCommonList;
59 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
60 import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl;
61 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
62 import org.collectionspace.services.relation.RelationResource;
63 import org.collectionspace.services.relation.RelationsCommonList;
64 import org.collectionspace.services.relation.RelationshipType;
65 import org.jboss.resteasy.util.HttpResponseCodes;
66 import org.nuxeo.ecm.core.api.DocumentModel;
67 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 import javax.ws.rs.Consumes;
72 import javax.ws.rs.DELETE;
73 import javax.ws.rs.GET;
74 import javax.ws.rs.POST;
75 import javax.ws.rs.PUT;
76 import javax.ws.rs.Path;
77 import javax.ws.rs.PathParam;
78 import javax.ws.rs.Produces;
79 import javax.ws.rs.QueryParam;
80 import javax.ws.rs.WebApplicationException;
81 import javax.ws.rs.core.Context;
82 import javax.ws.rs.core.MultivaluedMap;
83 import javax.ws.rs.core.Request;
84 import javax.ws.rs.core.Response;
85 import javax.ws.rs.core.UriBuilder;
86 import javax.ws.rs.core.UriInfo;
88 import java.util.ArrayList;
89 import java.util.List;
92 * The Class AuthorityResource.
98 * @param <AuthItemHandler>
103 * @param <AuthCommon>
104 * @param <AuthItemHandler>
106 @Consumes("application/xml")
107 @Produces("application/xml")
108 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
109 extends ResourceBase {
111 final static String SEARCH_TYPE_TERMSTATUS = "ts";
113 protected Class<AuthCommon> authCommonClass;
114 protected Class<?> resourceClass;
115 protected String authorityCommonSchemaName;
116 protected String authorityItemCommonSchemaName;
117 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType();
118 final static String URN_PREFIX = "urn:cspace:";
119 final static int URN_PREFIX_LEN = URN_PREFIX.length();
120 final static String URN_PREFIX_NAME = "name(";
121 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
122 final static String URN_PREFIX_ID = "id(";
123 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
124 final static String FETCH_SHORT_ID = "_fetch_";
125 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
127 public enum SpecifierForm {
132 public class Specifier {
134 public SpecifierForm form;
137 Specifier(SpecifierForm form, String value) {
143 protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException {
144 if (logger.isDebugEnabled()) {
145 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
147 if (specifierIn != null) {
148 if (!specifierIn.startsWith(URN_PREFIX)) {
149 // We'll assume it is a CSID and complain if it does not match
150 return new Specifier(SpecifierForm.CSID, specifierIn);
152 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
153 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
154 if (closeParen >= 0) {
155 return new Specifier(SpecifierForm.URN_NAME,
156 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
158 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
159 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
160 if (closeParen >= 0) {
161 return new Specifier(SpecifierForm.CSID,
162 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
167 logger.error(method + ": bad or missing specifier!");
168 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
169 op + " failed on bad or missing Authority specifier").type(
170 "text/plain").build();
171 throw new WebApplicationException(response);
175 * Instantiates a new Authority resource.
177 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
178 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
179 this.authCommonClass = authCommonClass;
180 this.resourceClass = resourceClass;
181 this.authorityCommonSchemaName = authorityCommonSchemaName;
182 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
185 public abstract String getItemServiceName();
188 protected String getVersionString() {
189 return "$LastChangedRevision: 2617 $";
193 public Class<AuthCommon> getCommonPartClass() {
194 return authCommonClass;
198 * Creates the item document handler.
201 * @param inAuthority the in vocabulary
203 * @return the document handler
205 * @throws Exception the exception
207 protected DocumentHandler createItemDocumentHandler(
208 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
209 String inAuthority, String parentShortIdentifier)
211 String authorityRefNameBase;
212 AuthorityItemDocumentModelHandler<?> docHandler;
214 if (parentShortIdentifier == null) {
215 authorityRefNameBase = null;
217 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
218 createServiceContext(getServiceName());
219 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
220 // Get from parent document
221 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
223 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
226 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
227 ctx.getCommonPartLabel(getItemServiceName()),
229 docHandler.setInAuthority(inAuthority);
230 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
235 public String getAuthShortIdentifier(
236 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
237 throws DocumentNotFoundException, DocumentException {
238 String shortIdentifier = null;
240 AuthorityDocumentModelHandler<?> handler =
241 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
242 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
243 } catch (Exception e) {
244 if (logger.isDebugEnabled()) {
245 logger.debug("Caught exception ", e);
247 throw new DocumentException(e);
249 return shortIdentifier;
252 protected String buildAuthorityRefNameBase(
253 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
254 RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(),
255 ctx.getServiceName(), shortIdentifier, null);
256 return authority.toString();
259 public static class CsidAndShortIdentifier {
262 String shortIdentifier;
265 protected String lookupParentCSID(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
267 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams);
268 return tempResult.CSID;
271 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
273 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
274 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
275 // Note that we have to create the service context for the Items, not the main service
277 String parentShortIdentifier;
278 if (parentSpec.form == SpecifierForm.CSID) {
279 parentShortIdentifier = null;
280 parentcsid = parentSpec.value;
281 // Uncomment when app layer is ready to integrate
282 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
283 parentShortIdentifier = FETCH_SHORT_ID;
285 parentShortIdentifier = parentSpec.value;
286 String whereClause = buildWhereForAuthByName(parentSpec.value);
287 ServiceContext ctx = createServiceContext(getServiceName(), queryParams);
288 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
290 result.CSID = parentcsid;
291 result.shortIdentifier = parentShortIdentifier;
295 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext ctx)
296 throws DocumentException {
298 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
299 if (itemSpec.form == SpecifierForm.CSID) {
300 itemcsid = itemSpec.value;
302 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
303 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
309 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
310 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
311 * Resource. They then call this method on that resource.
314 public DocumentModel getDocModelForAuthorityItem(RepositoryInstance repoSession, RefName.AuthorityItem item)
315 throws Exception, DocumentNotFoundException {
319 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
320 // Ensure we have the right context.
321 ServiceContext ctx = createServiceContext(item.inAuthority.resource);
323 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
324 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
325 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
327 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
328 ctx = createServiceContext(getItemServiceName());
329 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
330 DocumentModel docModel = docWrapper.getWrappedObject();
336 public Response createAuthority(String xmlPayload) {
338 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
339 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
340 DocumentHandler handler = createDocumentHandler(ctx);
341 String csid = getRepositoryClient(ctx).create(ctx, handler);
342 UriBuilder path = UriBuilder.fromResource(resourceClass);
343 path.path("" + csid);
344 Response response = Response.created(path.build()).build();
346 } catch (Exception e) {
347 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
351 protected String buildWhereForAuthByName(String name) {
352 return authorityCommonSchemaName
353 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
357 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
358 return authorityItemCommonSchemaName
359 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
360 + "='" + name + "' AND "
361 + authorityItemCommonSchemaName + ":"
362 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
363 + "'" + parentcsid + "'";
367 * Gets the authority.
369 * @param specifier either a CSID or one of the urn forms
371 * @return the authority
376 public byte[] get( // getAuthority(
378 @PathParam("csid") String specifier) {
379 PoxPayloadOut result = null;
381 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
382 DocumentHandler handler = createDocumentHandler(ctx);
384 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
385 if (spec.form == SpecifierForm.CSID) {
386 if (logger.isDebugEnabled()) {
387 logger.debug("getAuthority with csid=" + spec.value);
389 getRepositoryClient(ctx).get(ctx, spec.value, handler);
391 String whereClause = buildWhereForAuthByName(spec.value);
392 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
393 handler.setDocumentFilter(myFilter);
394 getRepositoryClient(ctx).get(ctx, handler);
396 result = ctx.getOutput();
398 } catch (Exception e) {
399 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
402 if (result == null) {
403 Response response = Response.status(Response.Status.NOT_FOUND).entity(
404 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
405 "text/plain").build();
406 throw new WebApplicationException(response);
409 return result.getBytes();
413 * Finds and populates the authority list.
417 * @return the authority list
420 @Produces("application/xml")
421 public AbstractCommonList getAuthorityList(@Context UriInfo ui) {
423 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
424 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
425 DocumentHandler handler = createDocumentHandler(ctx);
426 DocumentFilter myFilter = handler.getDocumentFilter();
427 // Need to make the default sort order for authority items
428 // be on the displayName field
429 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
430 if (sortBy == null || sortBy.isEmpty()) {
431 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
432 + AuthorityItemJAXBSchema.DISPLAY_NAME;
433 myFilter.setOrderByClause(qualifiedDisplayNameField);
435 String nameQ = queryParams.getFirst("refName");
437 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
439 getRepositoryClient(ctx).getFiltered(ctx, handler);
440 return (AbstractCommonList) handler.getCommonPartList();
441 } catch (Exception e) {
442 throw bigReThrow(e, ServiceMessages.GET_FAILED);
449 * @param specifier the csid or id
451 * @return the multipart output
455 public byte[] updateAuthority(
456 @PathParam("csid") String specifier,
458 PoxPayloadOut result = null;
460 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
461 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
462 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
463 DocumentHandler handler = createDocumentHandler(ctx);
465 if (spec.form == SpecifierForm.CSID) {
468 String whereClause = buildWhereForAuthByName(spec.value);
469 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
471 getRepositoryClient(ctx).update(ctx, csid, handler);
472 result = ctx.getOutput();
473 } catch (Exception e) {
474 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
476 return result.getBytes();
482 * @param csid the csid
484 * @return the response
488 public Response deleteAuthority(@PathParam("csid") String csid) {
489 if (logger.isDebugEnabled()) {
490 logger.debug("deleteAuthority with csid=" + csid);
493 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
494 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
495 getRepositoryClient(ctx).delete(ctx, csid);
496 return Response.status(HttpResponseCodes.SC_OK).build();
497 } catch (Exception e) {
498 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
502 /*************************************************************************
503 * Create an AuthorityItem - this is a sub-resource of Authority
504 * @param specifier either a CSID or one of the urn forms
505 * @return Authority item response
506 *************************************************************************/
508 @Path("{csid}/items")
509 public Response createAuthorityItem(@Context ResourceMap resourceMap, @Context UriInfo ui,
510 @PathParam("csid") String specifier, String xmlPayload) {
512 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
513 ServiceContext ctx = createServiceContext(getItemServiceName(), input);
514 ctx.setResourceMap(resourceMap);
515 ctx.setUriInfo(ui); //Laramie
517 // Note: must have the parentShortId, to do the create.
518 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
519 DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
520 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
521 UriBuilder path = UriBuilder.fromResource(resourceClass);
522 path.path(parent.CSID + "/items/" + itemcsid);
523 Response response = Response.created(path.build()).build();
525 } catch (Exception e) {
526 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
531 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
532 public byte[] getItemWorkflow(
533 @PathParam("csid") String csid,
534 @PathParam("itemcsid") String itemcsid) {
535 PoxPayloadOut result = null;
538 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
539 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
541 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
542 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
543 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
544 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
545 result = ctx.getOutput();
546 } catch (Exception e) {
547 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
549 return result.getBytes();
553 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
554 public byte[] updateWorkflow(
555 @PathParam("csid") String csid,
556 @PathParam("itemcsid") String itemcsid,
558 PoxPayloadOut result = null;
560 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
561 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
563 PoxPayloadIn workflowUpdate = new PoxPayloadIn(xmlPayload);
564 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, workflowUpdate);
565 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
566 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
567 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
568 result = ctx.getOutput();
569 } catch (Exception e) {
570 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
572 return result.getBytes();
576 * Gets the authority item.
578 * @param parentspecifier either a CSID or one of the urn forms
579 * @param itemspecifier either a CSID or one of the urn forms
581 * @return the authority item
584 @Path("{csid}/items/{itemcsid}")
585 public byte[] getAuthorityItem(
586 @Context Request request,
588 @PathParam("csid") String parentspecifier,
589 @PathParam("itemcsid") String itemspecifier) {
590 PoxPayloadOut result = null;
592 JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
593 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
594 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
596 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
597 ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
598 ctx.setJaxRsContext(jaxRsContext);
600 ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui.
602 // We omit the parentShortId, only needed when doing a create...
603 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
605 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
606 if (itemSpec.form == SpecifierForm.CSID) {
607 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
609 String itemWhereClause =
610 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
611 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
612 handler.setDocumentFilter(myFilter);
613 getRepositoryClient(ctx).get(ctx, handler);
615 // TODO should we assert that the item is in the passed vocab?
616 result = ctx.getOutput();
617 } catch (Exception e) {
618 throw bigReThrow(e, ServiceMessages.GET_FAILED);
620 if (result == null) {
621 Response response = Response.status(Response.Status.NOT_FOUND).entity(
622 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
623 "text/plain").build();
624 throw new WebApplicationException(response);
626 return result.getBytes();
630 * Gets the authorityItem list for the specified authority
631 * If partialPerm is specified, keywords will be ignored.
633 * @param specifier either a CSID or one of the urn forms
634 * @param partialTerm if non-null, matches partial terms
635 * @param keywords if non-null, matches terms in the keyword index for items
636 * @param ui passed to include additional parameters, like pagination controls
638 * @return the authorityItem list
641 @Path("{csid}/items")
642 @Produces("application/xml")
643 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
644 @Context UriInfo ui) {
646 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
647 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
648 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
649 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
650 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
652 String qualifiedDisplayNameField = authorityItemCommonSchemaName + ":"
653 + AuthorityItemJAXBSchema.DISPLAY_NAME;
655 // Note that docType defaults to the ServiceName, so we're fine with that.
656 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
658 String parentcsid = lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
660 ctx = createServiceContext(getItemServiceName(), queryParams);
661 // We omit the parentShortId, only needed when doing a create...
662 DocumentHandler handler = createItemDocumentHandler(ctx,
664 DocumentFilter myFilter = handler.getDocumentFilter();
665 // Need to make the default sort order for authority items
666 // be on the displayName field
667 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
668 if (sortBy == null || sortBy.isEmpty()) {
669 myFilter.setOrderByClause(qualifiedDisplayNameField);
672 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
673 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
674 + "'" + parentcsid + "'",
675 IQueryManager.SEARCH_QUALIFIER_AND);
677 if (Tools.notBlank(termStatus)) {
678 // Start with the qualified termStatus field
679 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
680 + AuthorityItemJAXBSchema.TERM_STATUS;
681 String[] filterTerms = termStatus.trim().split("\\|");
682 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
683 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
686 // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
687 // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
688 // the PT query param trumps the KW and AS query params.
689 if (partialTerm != null && !partialTerm.isEmpty()) {
690 String ptClause = QueryManager.createWhereClauseForPartialMatch(
691 qualifiedDisplayNameField, partialTerm);
692 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
693 } else if (keywords != null || advancedSearch != null) {
694 // String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
695 // myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
696 return search(ctx, handler, queryParams, keywords, advancedSearch);
698 if (logger.isDebugEnabled()) {
699 logger.debug("getAuthorityItemList filtered WHERE clause: "
700 + myFilter.getWhereClause());
702 getRepositoryClient(ctx).getFiltered(ctx, handler);
703 return (AbstractCommonList) handler.getCommonPartList();
704 } catch (Exception e) {
705 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
710 * @return the name of the property used to specify references for items in this type of
711 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
712 * Some types (like Vocabulary) use a separate property.
714 protected String getRefPropName() {
715 return ServiceBindingUtils.AUTH_REF_PROP;
719 * Gets the entities referencing this Authority item instance. The service type
720 * can be passed as a query param "type", and must match a configured type
721 * for the service bindings. If not set, the type defaults to
722 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
724 * @param parentspecifier either a CSID or one of the urn forms
725 * @param itemspecifier either a CSID or one of the urn forms
728 * @return the info for the referencing objects
731 @Path("{csid}/items/{itemcsid}/refObjs")
732 @Produces("application/xml")
733 public AuthorityRefDocList getReferencingObjects(
734 @PathParam("csid") String parentspecifier,
735 @PathParam("itemcsid") String itemspecifier,
736 @Context UriInfo ui) {
737 AuthorityRefDocList authRefDocList = null;
739 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
741 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
743 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
744 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
746 String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE;
747 List<String> list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
749 serviceType = list.get(0);
751 // Could be smarter about using the list from above, and/or allowing multiple
752 ArrayList<String> serviceTypes = new ArrayList<String>(1);
753 serviceTypes.add(serviceType);
755 // Note that we have to create the service context for the Items, not the main service
756 // We omit the parentShortId, only needed when doing a create...
757 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
758 createItemDocumentHandler(ctx, parentcsid, null);
760 authRefDocList = handler.getReferencingObjects(ctx, serviceTypes, getRefPropName(), itemcsid);
761 } catch (Exception e) {
762 throw bigReThrow(e, ServiceMessages.GET_FAILED);
764 if (authRefDocList == null) {
765 Response response = Response.status(Response.Status.NOT_FOUND).entity(
766 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
767 "text/plain").build();
768 throw new WebApplicationException(response);
770 return authRefDocList;
774 * Gets the authority terms used in the indicated Authority item.
776 * @param parentspecifier either a CSID or one of the urn forms
777 * @param itemspecifier either a CSID or one of the urn forms
778 * @param ui passed to include additional parameters, like pagination controls
780 * @return the authority refs for the Authority item.
783 @Path("{csid}/items/{itemcsid}/authorityrefs")
784 @Produces("application/xml")
785 public AuthorityRefList getAuthorityItemAuthorityRefs(
786 @PathParam("csid") String parentspecifier,
787 @PathParam("itemcsid") String itemspecifier,
788 @Context UriInfo ui) {
789 AuthorityRefList authRefList = null;
791 // Note that we have to create the service context for the Items, not the main service
792 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
793 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
795 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
797 ctx = createServiceContext(getItemServiceName(), queryParams);
798 // We omit the parentShortId, only needed when doing a create...
799 DocumentModelHandler handler =
800 (DocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, null);
802 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
804 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
805 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
806 } catch (Exception e) {
807 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
813 * Update authorityItem.
815 * @param parentspecifier either a CSID or one of the urn forms
816 * @param itemspecifier either a CSID or one of the urn forms
818 * @return the multipart output
821 @Path("{csid}/items/{itemcsid}")
822 public byte[] updateAuthorityItem(
823 @Context ResourceMap resourceMap,
825 @PathParam("csid") String parentspecifier,
826 @PathParam("itemcsid") String itemspecifier,
828 PoxPayloadOut result = null;
830 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
831 // Note that we have to create the service context for the Items, not the main service
832 //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
833 String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
835 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
836 ctx.setResourceMap(resourceMap);
837 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
839 // We omit the parentShortId, only needed when doing a create...
840 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
842 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
843 result = ctx.getOutput();
845 } catch (Exception e) {
846 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
848 return result.getBytes();
852 * Delete authorityItem.
854 * @param parentcsid the parentcsid
855 * @param itemcsid the itemcsid
857 * @return the response
860 @Path("{csid}/items/{itemcsid}")
861 public Response deleteAuthorityItem(
862 @PathParam("csid") String parentcsid,
863 @PathParam("itemcsid") String itemcsid) {
865 if (logger.isDebugEnabled()) {
866 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
869 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
870 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
871 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
872 // }catch (Throwable t){
873 // System.out.println("ERROR in setting up DELETE: "+t);
876 // Note that we have to create the service context for the Items, not the main service
877 ServiceContext ctx = createServiceContext(getItemServiceName());
878 getRepositoryClient(ctx).delete(ctx, itemcsid);
879 return Response.status(HttpResponseCodes.SC_OK).build();
880 } catch (Exception e) {
881 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
884 public final static String hierarchy = "hierarchy";
887 @Path("{csid}/items/{itemcsid}/" + hierarchy)
888 @Produces("application/xml")
889 public String getHierarchy(@PathParam("csid") String csid,
890 @PathParam("itemcsid") String itemcsid,
891 @Context UriInfo ui) throws Exception {
893 // 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...?
894 String calledUri = ui.getPath();
895 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
896 ServiceContext ctx = createServiceContext(getItemServiceName());
898 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
899 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
900 return Hierarchy.surface(ctx, itemcsid, uri);
902 return Hierarchy.dive(ctx, itemcsid, uri);
904 } catch (Exception e) {
905 throw bigReThrow(e, "Error showing hierarchy", itemcsid);