2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
24 package org.collectionspace.services.common.vocabulary;
26 import org.collectionspace.services.client.IClientQueryParams;
27 import org.collectionspace.services.client.IQueryManager;
28 import org.collectionspace.services.client.PoxPayloadIn;
29 import org.collectionspace.services.client.PoxPayloadOut;
30 import org.collectionspace.services.client.workflow.WorkflowClient;
31 import org.collectionspace.services.common.ResourceBase;
32 import org.collectionspace.services.common.ResourceMap;
33 import org.collectionspace.services.common.ServiceMain;
34 import org.collectionspace.services.common.ServiceMessages;
35 import org.collectionspace.services.common.api.RefName;
36 import org.collectionspace.services.common.api.Tools;
37 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
38 import org.collectionspace.services.common.authorityref.AuthorityRefList;
39 import org.collectionspace.services.common.context.JaxRsContext;
40 import org.collectionspace.services.common.context.MultipartServiceContext;
41 import org.collectionspace.services.common.context.RemoteServiceContext;
42 import org.collectionspace.services.common.context.ServiceBindingUtils;
43 import org.collectionspace.services.common.context.ServiceContext;
44 import org.collectionspace.services.common.document.DocumentException;
45 import org.collectionspace.services.common.document.DocumentFilter;
46 import org.collectionspace.services.common.document.DocumentHandler;
47 import org.collectionspace.services.common.document.DocumentNotFoundException;
48 import org.collectionspace.services.common.document.DocumentWrapper;
49 import org.collectionspace.services.common.query.QueryManager;
50 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
51 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
52 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
53 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
54 import org.collectionspace.services.config.ClientType;
55 import org.collectionspace.services.jaxb.AbstractCommonList;
56 import org.collectionspace.services.lifecycle.TransitionDef;
57 import org.collectionspace.services.nuxeo.client.java.DocumentModelHandler;
58 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
59 import org.collectionspace.services.workflow.WorkflowCommon;
60 import org.jboss.resteasy.util.HttpResponseCodes;
61 import org.nuxeo.ecm.core.api.DocumentModel;
62 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 import javax.ws.rs.Consumes;
67 import javax.ws.rs.DELETE;
68 import javax.ws.rs.GET;
69 import javax.ws.rs.POST;
70 import javax.ws.rs.PUT;
71 import javax.ws.rs.Path;
72 import javax.ws.rs.PathParam;
73 import javax.ws.rs.Produces;
74 import javax.ws.rs.QueryParam;
75 import javax.ws.rs.WebApplicationException;
76 import javax.ws.rs.core.Context;
77 import javax.ws.rs.core.MultivaluedMap;
78 import javax.ws.rs.core.Request;
79 import javax.ws.rs.core.Response;
80 import javax.ws.rs.core.UriBuilder;
81 import javax.ws.rs.core.UriInfo;
83 import java.util.ArrayList;
84 import java.util.List;
85 import org.collectionspace.services.client.*;
86 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
89 * The Class AuthorityResource.
95 * @param <AuthItemHandler>
100 * @param <AuthCommon>
101 * @param <AuthItemHandler>
103 @Consumes("application/xml")
104 @Produces("application/xml")
105 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
106 extends ResourceBase {
108 final static String SEARCH_TYPE_TERMSTATUS = "ts";
110 protected Class<AuthCommon> authCommonClass;
111 protected Class<?> resourceClass;
112 protected String authorityCommonSchemaName;
113 protected String authorityItemCommonSchemaName;
114 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
115 final static String URN_PREFIX = "urn:cspace:";
116 final static int URN_PREFIX_LEN = URN_PREFIX.length();
117 final static String URN_PREFIX_NAME = "name(";
118 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
119 final static String URN_PREFIX_ID = "id(";
120 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
121 final static String FETCH_SHORT_ID = "_fetch_";
122 final static String PARENT_WILDCARD = "_ALL_";
124 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
126 public enum SpecifierForm {
131 public class Specifier {
133 public SpecifierForm form;
136 Specifier(SpecifierForm form, String value) {
142 protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException {
143 if (logger.isDebugEnabled()) {
144 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
146 if (specifierIn != null) {
147 if (!specifierIn.startsWith(URN_PREFIX)) {
148 // We'll assume it is a CSID and complain if it does not match
149 return new Specifier(SpecifierForm.CSID, specifierIn);
151 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
152 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
153 if (closeParen >= 0) {
154 return new Specifier(SpecifierForm.URN_NAME,
155 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
157 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
158 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
159 if (closeParen >= 0) {
160 return new Specifier(SpecifierForm.CSID,
161 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
166 logger.error(method + ": bad or missing specifier!");
167 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
168 op + " failed on bad or missing Authority specifier").type(
169 "text/plain").build();
170 throw new WebApplicationException(response);
174 * Instantiates a new Authority resource.
176 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
177 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
178 this.authCommonClass = authCommonClass;
179 this.resourceClass = resourceClass;
180 this.authorityCommonSchemaName = authorityCommonSchemaName;
181 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
184 public abstract String getItemServiceName();
186 public abstract String getItemTermInfoGroupXPathBase();
189 protected String getVersionString() {
190 return "$LastChangedRevision: 2617 $";
194 public Class<AuthCommon> getCommonPartClass() {
195 return authCommonClass;
199 * Creates the item document handler.
202 * @param inAuthority the in vocabulary
204 * @return the document handler
206 * @throws Exception the exception
208 protected DocumentHandler createItemDocumentHandler(
209 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
210 String inAuthority, String parentShortIdentifier)
212 String authorityRefNameBase;
213 AuthorityItemDocumentModelHandler<?> docHandler;
215 if (parentShortIdentifier == null) {
216 authorityRefNameBase = null;
218 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
219 createServiceContext(getServiceName());
220 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
221 // Get from parent document
222 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
224 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
227 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
228 ctx.getCommonPartLabel(getItemServiceName()),
230 // FIXME - Richard and Aron think the following three lines should
231 // be in the constructor for the AuthorityItemDocumentModelHandler
232 // because all three are required fields.
233 docHandler.setInAuthority(inAuthority);
234 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
235 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
239 public String getAuthShortIdentifier(
240 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
241 throws DocumentNotFoundException, DocumentException {
242 String shortIdentifier = null;
244 AuthorityDocumentModelHandler<?> handler =
245 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
246 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
247 } catch (Exception e) {
248 if (logger.isDebugEnabled()) {
249 logger.debug("Caught exception ", e);
251 throw new DocumentException(e);
253 return shortIdentifier;
256 protected String buildAuthorityRefNameBase(
257 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
258 RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(),
259 ctx.getServiceName(), shortIdentifier, null);
260 return authority.toString();
263 public static class CsidAndShortIdentifier {
266 String shortIdentifier;
269 protected String lookupParentCSID(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
271 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams);
272 return tempResult.CSID;
275 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
277 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
278 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
279 // Note that we have to create the service context for the Items, not the main service
281 String parentShortIdentifier;
282 if (parentSpec.form == SpecifierForm.CSID) {
283 parentShortIdentifier = null;
284 parentcsid = parentSpec.value;
285 // Uncomment when app layer is ready to integrate
286 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
287 parentShortIdentifier = FETCH_SHORT_ID;
289 parentShortIdentifier = parentSpec.value;
290 String whereClause = buildWhereForAuthByName(parentSpec.value);
291 ServiceContext ctx = createServiceContext(getServiceName(), queryParams);
292 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
294 result.CSID = parentcsid;
295 result.shortIdentifier = parentShortIdentifier;
299 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext ctx)
300 throws DocumentException {
302 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
303 if (itemSpec.form == SpecifierForm.CSID) {
304 itemcsid = itemSpec.value;
306 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
307 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
313 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
314 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
315 * Resource. They then call this method on that resource.
318 public DocumentModel getDocModelForAuthorityItem(RepositoryInstance repoSession, RefName.AuthorityItem item)
319 throws Exception, DocumentNotFoundException {
323 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
324 // Ensure we have the right context.
325 ServiceContext ctx = createServiceContext(item.inAuthority.resource);
327 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
328 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
329 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
331 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
332 ctx = createServiceContext(getItemServiceName());
333 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
334 DocumentModel docModel = docWrapper.getWrappedObject();
339 @POST //FIXME: REM - 5/1/2012 - We can probably remove this method.
340 public Response createAuthority(String xmlPayload) { //REM - This method is never reached by the JAX-RS client -instead the "create" method in ResourceBase.java is getting called.
342 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
343 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
344 DocumentHandler handler = createDocumentHandler(ctx);
345 String csid = getRepositoryClient(ctx).create(ctx, handler);
346 UriBuilder path = UriBuilder.fromResource(resourceClass);
347 path.path("" + csid);
348 Response response = Response.created(path.build()).build();
350 } catch (Exception e) {
351 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
355 protected String buildWhereForAuthByName(String name) {
356 return authorityCommonSchemaName
357 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
361 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
362 return authorityItemCommonSchemaName
363 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
364 + "='" + name + "' AND "
365 + authorityItemCommonSchemaName + ":"
366 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
367 + "'" + parentcsid + "'";
371 * Gets the authority.
373 * @param specifier either a CSID or one of the urn forms
375 * @return the authority
380 public byte[] get( // getAuthority(
382 @PathParam("csid") String specifier) {
383 PoxPayloadOut result = null;
385 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
386 DocumentHandler handler = createDocumentHandler(ctx);
388 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
389 if (spec.form == SpecifierForm.CSID) {
390 if (logger.isDebugEnabled()) {
391 logger.debug("getAuthority with csid=" + spec.value);
393 getRepositoryClient(ctx).get(ctx, spec.value, handler);
395 String whereClause = buildWhereForAuthByName(spec.value);
396 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
397 handler.setDocumentFilter(myFilter);
398 getRepositoryClient(ctx).get(ctx, handler);
400 result = ctx.getOutput();
402 } catch (Exception e) {
403 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
406 if (result == null) {
407 Response response = Response.status(Response.Status.NOT_FOUND).entity(
408 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
409 "text/plain").build();
410 throw new WebApplicationException(response);
413 return result.getBytes();
417 * Finds and populates the authority list.
421 * @return the authority list
424 @Produces("application/xml")
425 public AbstractCommonList getAuthorityList(@Context UriInfo ui) {
427 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
428 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
429 DocumentHandler handler = createDocumentHandler(ctx);
430 DocumentFilter myFilter = handler.getDocumentFilter();
431 // Need to make the default sort order for authority items
432 // be on the displayName field
433 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
434 if (sortBy == null || sortBy.isEmpty()) {
435 // String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
436 // + AuthorityItemJAXBSchema.DISPLAY_NAME;
437 String qualifiedDisplayNameField = getQualifiedDisplayNameField();
438 myFilter.setOrderByClause(qualifiedDisplayNameField);
440 String nameQ = queryParams.getFirst("refName");
442 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
444 getRepositoryClient(ctx).getFiltered(ctx, handler);
445 return (AbstractCommonList) handler.getCommonPartList();
446 } catch (Exception e) {
447 throw bigReThrow(e, ServiceMessages.GET_FAILED);
451 protected String getQualifiedDisplayNameField() {
452 return NuxeoUtils.getPrimaryXPathPropertyName(authorityCommonSchemaName,
453 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
459 * @param specifier the csid or id
461 * @return the multipart output
465 public byte[] updateAuthority(
466 @PathParam("csid") String specifier,
468 PoxPayloadOut result = null;
470 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
471 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
472 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
473 DocumentHandler handler = createDocumentHandler(ctx);
475 if (spec.form == SpecifierForm.CSID) {
478 String whereClause = buildWhereForAuthByName(spec.value);
479 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
481 getRepositoryClient(ctx).update(ctx, csid, handler);
482 result = ctx.getOutput();
483 } catch (Exception e) {
484 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
486 return result.getBytes();
492 * @param csid the csid
494 * @return the response
498 public Response deleteAuthority(@PathParam("csid") String csid) {
499 if (logger.isDebugEnabled()) {
500 logger.debug("deleteAuthority with csid=" + csid);
503 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
504 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
505 DocumentHandler handler = createDocumentHandler(ctx);
506 getRepositoryClient(ctx).delete(ctx, csid, handler);
507 return Response.status(HttpResponseCodes.SC_OK).build();
508 } catch (Exception e) {
509 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
513 /*************************************************************************
514 * Create an AuthorityItem - this is a sub-resource of Authority
515 * @param specifier either a CSID or one of the urn forms
516 * @return Authority item response
517 *************************************************************************/
519 @Path("{csid}/items")
520 public Response createAuthorityItem(@Context ResourceMap resourceMap, @Context UriInfo ui,
521 @PathParam("csid") String specifier, String xmlPayload) {
523 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
524 ServiceContext ctx = createServiceContext(getItemServiceName(), input);
525 ctx.setResourceMap(resourceMap);
526 ctx.setUriInfo(ui); //Laramie
528 // Note: must have the parentShortId, to do the create.
529 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
530 DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
531 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
532 UriBuilder path = UriBuilder.fromResource(resourceClass);
533 path.path(parent.CSID + "/items/" + itemcsid);
534 Response response = Response.created(path.build()).build();
536 } catch (Exception e) {
537 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
542 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
543 public byte[] getItemWorkflow(
544 @PathParam("csid") String csid,
545 @PathParam("itemcsid") String itemcsid) {
546 PoxPayloadOut result = null;
549 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
550 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
552 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
553 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
554 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
555 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
556 result = ctx.getOutput();
557 } catch (Exception e) {
558 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
560 return result.getBytes();
563 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
564 // they should be consolidated -be DRY (don't repeat yourself).
566 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
567 public byte[] updateItemWorkflowWithTransition(
568 @PathParam("csid") String csid,
569 @PathParam("itemcsid") String itemcsid,
570 @PathParam("transition") String transition) {
571 PoxPayloadOut result = null;
575 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
576 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
577 WorkflowClient.SERVICE_COMMONPART_NAME);
578 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
580 // Create a service context and document handler for the parent resource.
581 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
582 DocumentHandler parentDocHandler = this.createDocumentHandler(parentCtx);
583 ctx.setProperty(WorkflowClient.PARENT_DOCHANDLER, parentDocHandler); //added as a context param for the workflow document handler -it will call the parent's dochandler "prepareForWorkflowTranstion" method
585 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
586 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
587 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
589 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
590 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
591 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
593 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
594 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
595 result = ctx.getOutput();
596 } catch (Exception e) {
597 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
600 return result.getBytes();
604 * Gets the authority item.
606 * @param parentspecifier either a CSID or one of the urn forms
607 * @param itemspecifier either a CSID or one of the urn forms
609 * @return the authority item
612 @Path("{csid}/items/{itemcsid}")
613 public byte[] getAuthorityItem(
614 @Context Request request,
616 @PathParam("csid") String parentspecifier,
617 @PathParam("itemcsid") String itemspecifier) {
618 PoxPayloadOut result = null;
620 JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
621 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
622 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
624 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
625 ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
626 ctx.setJaxRsContext(jaxRsContext);
628 ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui.
630 // We omit the parentShortId, only needed when doing a create...
631 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
633 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
634 if (itemSpec.form == SpecifierForm.CSID) {
635 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
637 String itemWhereClause =
638 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
639 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
640 handler.setDocumentFilter(myFilter);
641 getRepositoryClient(ctx).get(ctx, handler);
643 // TODO should we assert that the item is in the passed vocab?
644 result = ctx.getOutput();
645 } catch (Exception e) {
646 throw bigReThrow(e, ServiceMessages.GET_FAILED);
648 if (result == null) {
649 Response response = Response.status(Response.Status.NOT_FOUND).entity(
650 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
651 "text/plain").build();
652 throw new WebApplicationException(response);
654 return result.getBytes();
658 * Gets the authorityItem list for the specified authority
659 * If partialPerm is specified, keywords will be ignored.
661 * @param specifier either a CSID or one of the urn forms
662 * @param partialTerm if non-null, matches partial terms
663 * @param keywords if non-null, matches terms in the keyword index for items
664 * @param ui passed to include additional parameters, like pagination controls
666 * @return the authorityItem list
669 @Path("{csid}/items")
670 @Produces("application/xml")
671 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
672 @Context UriInfo ui) {
674 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
675 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
676 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
677 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
678 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
680 String qualifiedDisplayNameField = getQualifiedDisplayNameField();
682 // Note that docType defaults to the ServiceName, so we're fine with that.
683 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
685 String parentcsid = PARENT_WILDCARD.equals(specifier)?null:
686 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
688 ctx = createServiceContext(getItemServiceName(), queryParams);
690 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
691 // We omit the parentShortId, only needed when doing a create...
692 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
694 DocumentFilter myFilter = handler.getDocumentFilter();
695 // Need to make the default sort order for authority items
696 // be on the displayName field
697 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
698 if (sortBy == null || sortBy.isEmpty()) {
699 myFilter.setOrderByClause(qualifiedDisplayNameField);
702 // If we are not wildcarding the parent, add a restriction
703 if(parentcsid!=null) {
704 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
705 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
706 + "'" + parentcsid + "'",
707 IQueryManager.SEARCH_QUALIFIER_AND);
710 if (Tools.notBlank(termStatus)) {
711 // Start with the qualified termStatus field
712 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
713 + AuthorityItemJAXBSchema.TERM_STATUS;
714 String[] filterTerms = termStatus.trim().split("\\|");
715 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
716 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
719 // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
720 // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
721 // the PT query param trumps the KW and AS query params.
722 if (partialTerm != null && !partialTerm.isEmpty()) {
723 String ptClause = QueryManager.createWhereClauseForPartialMatch(
724 qualifiedDisplayNameField, partialTerm);
725 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
726 } else if (keywords != null || advancedSearch != null) {
727 // String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
728 // myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
729 return search(ctx, handler, queryParams, keywords, advancedSearch);
731 if (logger.isDebugEnabled()) {
732 logger.debug("getAuthorityItemList filtered WHERE clause: "
733 + myFilter.getWhereClause());
735 getRepositoryClient(ctx).getFiltered(ctx, handler);
736 return (AbstractCommonList) handler.getCommonPartList();
737 } catch (Exception e) {
738 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
743 * @return the name of the property used to specify references for items in this type of
744 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
745 * Some types (like Vocabulary) use a separate property.
747 protected String getRefPropName() {
748 return ServiceBindingUtils.AUTH_REF_PROP;
752 * Gets the entities referencing this Authority item instance. The service type
753 * can be passed as a query param "type", and must match a configured type
754 * for the service bindings. If not set, the type defaults to
755 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
757 * @param parentspecifier either a CSID or one of the urn forms
758 * @param itemspecifier either a CSID or one of the urn forms
761 * @return the info for the referencing objects
764 @Path("{csid}/items/{itemcsid}/refObjs")
765 @Produces("application/xml")
766 public AuthorityRefDocList getReferencingObjects(
767 @PathParam("csid") String parentspecifier,
768 @PathParam("itemcsid") String itemspecifier,
769 @Context UriInfo ui) {
770 AuthorityRefDocList authRefDocList = null;
772 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
774 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
776 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
777 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
779 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
780 if(serviceTypes == null || serviceTypes.isEmpty()) {
781 // Temporary workaround for CSPACE-4983
782 // serviceTypes = ServiceBindingUtils.getCommonServiceTypes();
783 serviceTypes = ServiceBindingUtils.getCommonProcedureServiceTypes();
786 // Note that we have to create the service context for the Items, not the main service
787 // We omit the parentShortId, only needed when doing a create...
788 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
789 createItemDocumentHandler(ctx, parentcsid, null);
791 authRefDocList = handler.getReferencingObjects(ctx, serviceTypes, getRefPropName(), itemcsid);
792 } catch (Exception e) {
793 throw bigReThrow(e, ServiceMessages.GET_FAILED);
795 if (authRefDocList == null) {
796 Response response = Response.status(Response.Status.NOT_FOUND).entity(
797 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
798 "text/plain").build();
799 throw new WebApplicationException(response);
801 return authRefDocList;
805 * Gets the authority terms used in the indicated Authority item.
807 * @param parentspecifier either a CSID or one of the urn forms
808 * @param itemspecifier either a CSID or one of the urn forms
809 * @param ui passed to include additional parameters, like pagination controls
811 * @return the authority refs for the Authority item.
814 @Path("{csid}/items/{itemcsid}/authorityrefs")
815 @Produces("application/xml")
816 public AuthorityRefList getAuthorityItemAuthorityRefs(
817 @PathParam("csid") String parentspecifier,
818 @PathParam("itemcsid") String itemspecifier,
819 @Context UriInfo ui) {
820 AuthorityRefList authRefList = null;
822 // Note that we have to create the service context for the Items, not the main service
823 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
824 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
826 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
828 ctx = createServiceContext(getItemServiceName(), queryParams);
829 // We omit the parentShortId, only needed when doing a create...
830 DocumentModelHandler handler =
831 (DocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, null);
833 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
835 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
836 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
837 } catch (Exception e) {
838 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
844 * Update authorityItem.
846 * @param parentspecifier either a CSID or one of the urn forms
847 * @param itemspecifier either a CSID or one of the urn forms
849 * @return the multipart output
852 @Path("{csid}/items/{itemcsid}")
853 public byte[] updateAuthorityItem(
854 @Context ResourceMap resourceMap,
856 @PathParam("csid") String parentspecifier,
857 @PathParam("itemcsid") String itemspecifier,
859 PoxPayloadOut result = null;
861 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
862 // Note that we have to create the service context for the Items, not the main service
863 //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
864 String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
866 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
867 ctx.setResourceMap(resourceMap);
868 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
870 // We omit the parentShortId, only needed when doing a create...
871 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
873 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
874 result = ctx.getOutput();
876 } catch (Exception e) {
877 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
879 return result.getBytes();
883 * Delete authorityItem.
885 * @param parentcsid the parentcsid
886 * @param itemcsid the itemcsid
888 * @return the response
891 @Path("{csid}/items/{itemcsid}")
892 public Response deleteAuthorityItem(
893 @PathParam("csid") String parentcsid,
894 @PathParam("itemcsid") String itemcsid) {
896 if (logger.isDebugEnabled()) {
897 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
900 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
901 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
902 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
903 // }catch (Throwable t){
904 // System.out.println("ERROR in setting up DELETE: "+t);
907 // Note that we have to create the service context for the Items, not the main service
908 ServiceContext ctx = createServiceContext(getItemServiceName());
909 DocumentHandler handler = createDocumentHandler(ctx);
910 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
911 return Response.status(HttpResponseCodes.SC_OK).build();
912 } catch (Exception e) {
913 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
916 public final static String hierarchy = "hierarchy";
919 @Path("{csid}/items/{itemcsid}/" + hierarchy)
920 @Produces("application/xml")
921 public String getHierarchy(@PathParam("csid") String csid,
922 @PathParam("itemcsid") String itemcsid,
923 @Context UriInfo ui) throws Exception {
925 // 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...?
926 String calledUri = ui.getPath();
927 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
928 ServiceContext ctx = createServiceContext(getItemServiceName());
930 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
931 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
932 return Hierarchy.surface(ctx, itemcsid, uri);
934 return Hierarchy.dive(ctx, itemcsid, uri);
936 } catch (Exception e) {
937 throw bigReThrow(e, "Error showing hierarchy", itemcsid);