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.XmlTools;
36 import org.collectionspace.services.common.api.RefName;
37 import org.collectionspace.services.common.api.Tools;
38 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
39 import org.collectionspace.services.common.authorityref.AuthorityRefList;
40 import org.collectionspace.services.common.context.JaxRsContext;
41 import org.collectionspace.services.common.context.MultipartServiceContext;
42 import org.collectionspace.services.common.context.MultipartServiceContextImpl;
43 import org.collectionspace.services.common.context.RemoteServiceContext;
44 import org.collectionspace.services.common.context.ServiceBindingUtils;
45 import org.collectionspace.services.common.context.ServiceContext;
46 import org.collectionspace.services.common.document.DocumentException;
47 import org.collectionspace.services.common.document.DocumentFilter;
48 import org.collectionspace.services.common.document.DocumentHandler;
49 import org.collectionspace.services.common.document.DocumentNotFoundException;
50 import org.collectionspace.services.common.document.DocumentWrapper;
51 import org.collectionspace.services.common.query.QueryManager;
52 import org.collectionspace.services.common.repository.RepositoryClient;
53 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
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.config.ClientType;
58 import org.collectionspace.services.jaxb.AbstractCommonList;
59 import org.collectionspace.services.lifecycle.TransitionDef;
60 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
61 import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl;
62 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
63 import org.collectionspace.services.relation.RelationResource;
64 import org.collectionspace.services.relation.RelationsCommonList;
65 import org.collectionspace.services.relation.RelationshipType;
66 import org.collectionspace.services.workflow.WorkflowCommon;
67 import org.jboss.resteasy.util.HttpResponseCodes;
68 import org.nuxeo.ecm.core.api.DocumentModel;
69 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
73 import javax.ws.rs.Consumes;
74 import javax.ws.rs.DELETE;
75 import javax.ws.rs.GET;
76 import javax.ws.rs.POST;
77 import javax.ws.rs.PUT;
78 import javax.ws.rs.Path;
79 import javax.ws.rs.PathParam;
80 import javax.ws.rs.Produces;
81 import javax.ws.rs.QueryParam;
82 import javax.ws.rs.WebApplicationException;
83 import javax.ws.rs.core.Context;
84 import javax.ws.rs.core.MultivaluedMap;
85 import javax.ws.rs.core.Request;
86 import javax.ws.rs.core.Response;
87 import javax.ws.rs.core.UriBuilder;
88 import javax.ws.rs.core.UriInfo;
90 import java.util.ArrayList;
91 import java.util.List;
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 Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
129 public enum SpecifierForm {
134 public class Specifier {
136 public SpecifierForm form;
139 Specifier(SpecifierForm form, String value) {
145 protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException {
146 if (logger.isDebugEnabled()) {
147 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
149 if (specifierIn != null) {
150 if (!specifierIn.startsWith(URN_PREFIX)) {
151 // We'll assume it is a CSID and complain if it does not match
152 return new Specifier(SpecifierForm.CSID, specifierIn);
154 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
155 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
156 if (closeParen >= 0) {
157 return new Specifier(SpecifierForm.URN_NAME,
158 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
160 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
161 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
162 if (closeParen >= 0) {
163 return new Specifier(SpecifierForm.CSID,
164 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
169 logger.error(method + ": bad or missing specifier!");
170 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
171 op + " failed on bad or missing Authority specifier").type(
172 "text/plain").build();
173 throw new WebApplicationException(response);
177 * Instantiates a new Authority resource.
179 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
180 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
181 this.authCommonClass = authCommonClass;
182 this.resourceClass = resourceClass;
183 this.authorityCommonSchemaName = authorityCommonSchemaName;
184 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
187 public abstract String getItemServiceName();
190 protected String getVersionString() {
191 return "$LastChangedRevision: 2617 $";
195 public Class<AuthCommon> getCommonPartClass() {
196 return authCommonClass;
200 * Creates the item document handler.
203 * @param inAuthority the in vocabulary
205 * @return the document handler
207 * @throws Exception the exception
209 protected DocumentHandler createItemDocumentHandler(
210 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
211 String inAuthority, String parentShortIdentifier)
213 String authorityRefNameBase;
214 AuthorityItemDocumentModelHandler<?> docHandler;
216 if (parentShortIdentifier == null) {
217 authorityRefNameBase = null;
219 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
220 createServiceContext(getServiceName());
221 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
222 // Get from parent document
223 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
225 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
228 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
229 ctx.getCommonPartLabel(getItemServiceName()),
231 docHandler.setInAuthority(inAuthority);
232 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
237 public String getAuthShortIdentifier(
238 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
239 throws DocumentNotFoundException, DocumentException {
240 String shortIdentifier = null;
242 AuthorityDocumentModelHandler<?> handler =
243 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
244 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
245 } catch (Exception e) {
246 if (logger.isDebugEnabled()) {
247 logger.debug("Caught exception ", e);
249 throw new DocumentException(e);
251 return shortIdentifier;
254 protected String buildAuthorityRefNameBase(
255 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
256 RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(),
257 ctx.getServiceName(), shortIdentifier, null);
258 return authority.toString();
261 public static class CsidAndShortIdentifier {
264 String shortIdentifier;
267 protected String lookupParentCSID(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
269 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams);
270 return tempResult.CSID;
273 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
275 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
276 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
277 // Note that we have to create the service context for the Items, not the main service
279 String parentShortIdentifier;
280 if (parentSpec.form == SpecifierForm.CSID) {
281 parentShortIdentifier = null;
282 parentcsid = parentSpec.value;
283 // Uncomment when app layer is ready to integrate
284 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
285 parentShortIdentifier = FETCH_SHORT_ID;
287 parentShortIdentifier = parentSpec.value;
288 String whereClause = buildWhereForAuthByName(parentSpec.value);
289 ServiceContext ctx = createServiceContext(getServiceName(), queryParams);
290 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
292 result.CSID = parentcsid;
293 result.shortIdentifier = parentShortIdentifier;
297 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext ctx)
298 throws DocumentException {
300 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
301 if (itemSpec.form == SpecifierForm.CSID) {
302 itemcsid = itemSpec.value;
304 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
305 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
311 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
312 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
313 * Resource. They then call this method on that resource.
316 public DocumentModel getDocModelForAuthorityItem(RepositoryInstance repoSession, RefName.AuthorityItem item)
317 throws Exception, DocumentNotFoundException {
321 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
322 // Ensure we have the right context.
323 ServiceContext ctx = createServiceContext(item.inAuthority.resource);
325 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
326 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
327 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
329 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
330 ctx = createServiceContext(getItemServiceName());
331 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
332 DocumentModel docModel = docWrapper.getWrappedObject();
338 public Response createAuthority(String xmlPayload) {
340 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
341 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
342 DocumentHandler handler = createDocumentHandler(ctx);
343 String csid = getRepositoryClient(ctx).create(ctx, handler);
344 UriBuilder path = UriBuilder.fromResource(resourceClass);
345 path.path("" + csid);
346 Response response = Response.created(path.build()).build();
348 } catch (Exception e) {
349 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
353 protected String buildWhereForAuthByName(String name) {
354 return authorityCommonSchemaName
355 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
359 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
360 return authorityItemCommonSchemaName
361 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
362 + "='" + name + "' AND "
363 + authorityItemCommonSchemaName + ":"
364 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
365 + "'" + parentcsid + "'";
369 * Gets the authority.
371 * @param specifier either a CSID or one of the urn forms
373 * @return the authority
378 public byte[] get( // getAuthority(
380 @PathParam("csid") String specifier) {
381 PoxPayloadOut result = null;
383 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
384 DocumentHandler handler = createDocumentHandler(ctx);
386 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
387 if (spec.form == SpecifierForm.CSID) {
388 if (logger.isDebugEnabled()) {
389 logger.debug("getAuthority with csid=" + spec.value);
391 getRepositoryClient(ctx).get(ctx, spec.value, handler);
393 String whereClause = buildWhereForAuthByName(spec.value);
394 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
395 handler.setDocumentFilter(myFilter);
396 getRepositoryClient(ctx).get(ctx, handler);
398 result = ctx.getOutput();
400 } catch (Exception e) {
401 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
404 if (result == null) {
405 Response response = Response.status(Response.Status.NOT_FOUND).entity(
406 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
407 "text/plain").build();
408 throw new WebApplicationException(response);
411 return result.getBytes();
415 * Finds and populates the authority list.
419 * @return the authority list
422 @Produces("application/xml")
423 public AbstractCommonList getAuthorityList(@Context UriInfo ui) {
425 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
426 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
427 DocumentHandler handler = createDocumentHandler(ctx);
428 DocumentFilter myFilter = handler.getDocumentFilter();
429 // Need to make the default sort order for authority items
430 // be on the displayName field
431 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
432 if (sortBy == null || sortBy.isEmpty()) {
433 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
434 + AuthorityItemJAXBSchema.DISPLAY_NAME;
435 myFilter.setOrderByClause(qualifiedDisplayNameField);
437 String nameQ = queryParams.getFirst("refName");
439 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
441 getRepositoryClient(ctx).getFiltered(ctx, handler);
442 return (AbstractCommonList) handler.getCommonPartList();
443 } catch (Exception e) {
444 throw bigReThrow(e, ServiceMessages.GET_FAILED);
451 * @param specifier the csid or id
453 * @return the multipart output
457 public byte[] updateAuthority(
458 @PathParam("csid") String specifier,
460 PoxPayloadOut result = null;
462 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
463 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
464 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
465 DocumentHandler handler = createDocumentHandler(ctx);
467 if (spec.form == SpecifierForm.CSID) {
470 String whereClause = buildWhereForAuthByName(spec.value);
471 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
473 getRepositoryClient(ctx).update(ctx, csid, handler);
474 result = ctx.getOutput();
475 } catch (Exception e) {
476 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
478 return result.getBytes();
484 * @param csid the csid
486 * @return the response
490 public Response deleteAuthority(@PathParam("csid") String csid) {
491 if (logger.isDebugEnabled()) {
492 logger.debug("deleteAuthority with csid=" + csid);
495 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
496 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
497 getRepositoryClient(ctx).delete(ctx, csid);
498 return Response.status(HttpResponseCodes.SC_OK).build();
499 } catch (Exception e) {
500 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
504 /*************************************************************************
505 * Create an AuthorityItem - this is a sub-resource of Authority
506 * @param specifier either a CSID or one of the urn forms
507 * @return Authority item response
508 *************************************************************************/
510 @Path("{csid}/items")
511 public Response createAuthorityItem(@Context ResourceMap resourceMap, @Context UriInfo ui,
512 @PathParam("csid") String specifier, String xmlPayload) {
514 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
515 ServiceContext ctx = createServiceContext(getItemServiceName(), input);
516 ctx.setResourceMap(resourceMap);
517 ctx.setUriInfo(ui); //Laramie
519 // Note: must have the parentShortId, to do the create.
520 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
521 DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
522 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
523 UriBuilder path = UriBuilder.fromResource(resourceClass);
524 path.path(parent.CSID + "/items/" + itemcsid);
525 Response response = Response.created(path.build()).build();
527 } catch (Exception e) {
528 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
533 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
534 public byte[] getItemWorkflow(
535 @PathParam("csid") String csid,
536 @PathParam("itemcsid") String itemcsid) {
537 PoxPayloadOut result = null;
540 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
541 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
543 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
544 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
545 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
546 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
547 result = ctx.getOutput();
548 } catch (Exception e) {
549 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
551 return result.getBytes();
555 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
556 public byte[] updateItemWorkflowWithTransition(
557 @PathParam("csid") String csid,
558 @PathParam("itemcsid") String itemcsid,
559 @PathParam("transition") String transition) {
560 PoxPayloadOut result = null;
562 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
563 WorkflowClient.SERVICE_COMMONPART_NAME);
565 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
566 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
568 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
569 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
570 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
571 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
572 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
573 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
574 result = ctx.getOutput();
575 } catch (Exception e) {
576 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
578 return result.getBytes();
582 * Gets the authority item.
584 * @param parentspecifier either a CSID or one of the urn forms
585 * @param itemspecifier either a CSID or one of the urn forms
587 * @return the authority item
590 @Path("{csid}/items/{itemcsid}")
591 public byte[] getAuthorityItem(
592 @Context Request request,
594 @PathParam("csid") String parentspecifier,
595 @PathParam("itemcsid") String itemspecifier) {
596 PoxPayloadOut result = null;
598 JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
599 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
600 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
602 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
603 ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
604 ctx.setJaxRsContext(jaxRsContext);
606 ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui.
608 // We omit the parentShortId, only needed when doing a create...
609 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
611 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
612 if (itemSpec.form == SpecifierForm.CSID) {
613 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
615 String itemWhereClause =
616 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
617 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
618 handler.setDocumentFilter(myFilter);
619 getRepositoryClient(ctx).get(ctx, handler);
621 // TODO should we assert that the item is in the passed vocab?
622 result = ctx.getOutput();
623 } catch (Exception e) {
624 throw bigReThrow(e, ServiceMessages.GET_FAILED);
626 if (result == null) {
627 Response response = Response.status(Response.Status.NOT_FOUND).entity(
628 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
629 "text/plain").build();
630 throw new WebApplicationException(response);
632 return result.getBytes();
636 * Gets the authorityItem list for the specified authority
637 * If partialPerm is specified, keywords will be ignored.
639 * @param specifier either a CSID or one of the urn forms
640 * @param partialTerm if non-null, matches partial terms
641 * @param keywords if non-null, matches terms in the keyword index for items
642 * @param ui passed to include additional parameters, like pagination controls
644 * @return the authorityItem list
647 @Path("{csid}/items")
648 @Produces("application/xml")
649 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
650 @Context UriInfo ui) {
652 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
653 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
654 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
655 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
656 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
658 String qualifiedDisplayNameField = authorityItemCommonSchemaName + ":"
659 + AuthorityItemJAXBSchema.DISPLAY_NAME;
661 // Note that docType defaults to the ServiceName, so we're fine with that.
662 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
664 String parentcsid = lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
666 ctx = createServiceContext(getItemServiceName(), queryParams);
667 // We omit the parentShortId, only needed when doing a create...
668 DocumentHandler handler = createItemDocumentHandler(ctx,
670 DocumentFilter myFilter = handler.getDocumentFilter();
671 // Need to make the default sort order for authority items
672 // be on the displayName field
673 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
674 if (sortBy == null || sortBy.isEmpty()) {
675 myFilter.setOrderByClause(qualifiedDisplayNameField);
678 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
679 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
680 + "'" + parentcsid + "'",
681 IQueryManager.SEARCH_QUALIFIER_AND);
683 if (Tools.notBlank(termStatus)) {
684 // Start with the qualified termStatus field
685 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
686 + AuthorityItemJAXBSchema.TERM_STATUS;
687 String[] filterTerms = termStatus.trim().split("\\|");
688 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
689 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
692 // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
693 // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
694 // the PT query param trumps the KW and AS query params.
695 if (partialTerm != null && !partialTerm.isEmpty()) {
696 String ptClause = QueryManager.createWhereClauseForPartialMatch(
697 qualifiedDisplayNameField, partialTerm);
698 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
699 } else if (keywords != null || advancedSearch != null) {
700 // String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
701 // myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
702 return search(ctx, handler, queryParams, keywords, advancedSearch);
704 if (logger.isDebugEnabled()) {
705 logger.debug("getAuthorityItemList filtered WHERE clause: "
706 + myFilter.getWhereClause());
708 getRepositoryClient(ctx).getFiltered(ctx, handler);
709 return (AbstractCommonList) handler.getCommonPartList();
710 } catch (Exception e) {
711 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
716 * @return the name of the property used to specify references for items in this type of
717 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
718 * Some types (like Vocabulary) use a separate property.
720 protected String getRefPropName() {
721 return ServiceBindingUtils.AUTH_REF_PROP;
725 * Gets the entities referencing this Authority item instance. The service type
726 * can be passed as a query param "type", and must match a configured type
727 * for the service bindings. If not set, the type defaults to
728 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
730 * @param parentspecifier either a CSID or one of the urn forms
731 * @param itemspecifier either a CSID or one of the urn forms
734 * @return the info for the referencing objects
737 @Path("{csid}/items/{itemcsid}/refObjs")
738 @Produces("application/xml")
739 public AuthorityRefDocList getReferencingObjects(
740 @PathParam("csid") String parentspecifier,
741 @PathParam("itemcsid") String itemspecifier,
742 @Context UriInfo ui) {
743 AuthorityRefDocList authRefDocList = null;
745 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
747 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
749 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
750 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
752 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
753 if(serviceTypes == null || serviceTypes.isEmpty()) {
754 // Temporary workaround for CSPACE-4983
755 // serviceTypes = ServiceBindingUtils.getCommonServiceTypes();
756 serviceTypes = ServiceBindingUtils.getCommonProcedureServiceTypes();
759 // Note that we have to create the service context for the Items, not the main service
760 // We omit the parentShortId, only needed when doing a create...
761 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
762 createItemDocumentHandler(ctx, parentcsid, null);
764 authRefDocList = handler.getReferencingObjects(ctx, serviceTypes, getRefPropName(), itemcsid);
765 } catch (Exception e) {
766 throw bigReThrow(e, ServiceMessages.GET_FAILED);
768 if (authRefDocList == null) {
769 Response response = Response.status(Response.Status.NOT_FOUND).entity(
770 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
771 "text/plain").build();
772 throw new WebApplicationException(response);
774 return authRefDocList;
778 * Gets the authority terms used in the indicated Authority item.
780 * @param parentspecifier either a CSID or one of the urn forms
781 * @param itemspecifier either a CSID or one of the urn forms
782 * @param ui passed to include additional parameters, like pagination controls
784 * @return the authority refs for the Authority item.
787 @Path("{csid}/items/{itemcsid}/authorityrefs")
788 @Produces("application/xml")
789 public AuthorityRefList getAuthorityItemAuthorityRefs(
790 @PathParam("csid") String parentspecifier,
791 @PathParam("itemcsid") String itemspecifier,
792 @Context UriInfo ui) {
793 AuthorityRefList authRefList = null;
795 // Note that we have to create the service context for the Items, not the main service
796 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
797 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
799 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
801 ctx = createServiceContext(getItemServiceName(), queryParams);
802 // We omit the parentShortId, only needed when doing a create...
803 DocumentModelHandler handler =
804 (DocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, null);
806 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
808 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
809 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
810 } catch (Exception e) {
811 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
817 * Update authorityItem.
819 * @param parentspecifier either a CSID or one of the urn forms
820 * @param itemspecifier either a CSID or one of the urn forms
822 * @return the multipart output
825 @Path("{csid}/items/{itemcsid}")
826 public byte[] updateAuthorityItem(
827 @Context ResourceMap resourceMap,
829 @PathParam("csid") String parentspecifier,
830 @PathParam("itemcsid") String itemspecifier,
832 PoxPayloadOut result = null;
834 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
835 // Note that we have to create the service context for the Items, not the main service
836 //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
837 String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
839 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
840 ctx.setResourceMap(resourceMap);
841 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
843 // We omit the parentShortId, only needed when doing a create...
844 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
846 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
847 result = ctx.getOutput();
849 } catch (Exception e) {
850 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
852 return result.getBytes();
856 * Delete authorityItem.
858 * @param parentcsid the parentcsid
859 * @param itemcsid the itemcsid
861 * @return the response
864 @Path("{csid}/items/{itemcsid}")
865 public Response deleteAuthorityItem(
866 @PathParam("csid") String parentcsid,
867 @PathParam("itemcsid") String itemcsid) {
869 if (logger.isDebugEnabled()) {
870 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
873 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
874 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
875 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
876 // }catch (Throwable t){
877 // System.out.println("ERROR in setting up DELETE: "+t);
880 // Note that we have to create the service context for the Items, not the main service
881 ServiceContext ctx = createServiceContext(getItemServiceName());
882 getRepositoryClient(ctx).delete(ctx, itemcsid);
883 return Response.status(HttpResponseCodes.SC_OK).build();
884 } catch (Exception e) {
885 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
888 public final static String hierarchy = "hierarchy";
891 @Path("{csid}/items/{itemcsid}/" + hierarchy)
892 @Produces("application/xml")
893 public String getHierarchy(@PathParam("csid") String csid,
894 @PathParam("itemcsid") String itemcsid,
895 @Context UriInfo ui) throws Exception {
897 // 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...?
898 String calledUri = ui.getPath();
899 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
900 ServiceContext ctx = createServiceContext(getItemServiceName());
902 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
903 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
904 return Hierarchy.surface(ctx, itemcsid, uri);
906 return Hierarchy.dive(ctx, itemcsid, uri);
908 } catch (Exception e) {
909 throw bigReThrow(e, "Error showing hierarchy", itemcsid);