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;
87 * The Class AuthorityResource.
93 * @param <AuthItemHandler>
99 * @param <AuthItemHandler>
101 @Consumes("application/xml")
102 @Produces("application/xml")
103 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
104 extends ResourceBase {
106 final static String SEARCH_TYPE_TERMSTATUS = "ts";
108 protected Class<AuthCommon> authCommonClass;
109 protected Class<?> resourceClass;
110 protected String authorityCommonSchemaName;
111 protected String authorityItemCommonSchemaName;
112 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
113 final static String URN_PREFIX = "urn:cspace:";
114 final static int URN_PREFIX_LEN = URN_PREFIX.length();
115 final static String URN_PREFIX_NAME = "name(";
116 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
117 final static String URN_PREFIX_ID = "id(";
118 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
119 final static String FETCH_SHORT_ID = "_fetch_";
120 final static String PARENT_WILDCARD = "_ALL_";
122 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
124 public enum SpecifierForm {
129 public class Specifier {
131 public SpecifierForm form;
134 Specifier(SpecifierForm form, String value) {
140 protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException {
141 if (logger.isDebugEnabled()) {
142 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
144 if (specifierIn != null) {
145 if (!specifierIn.startsWith(URN_PREFIX)) {
146 // We'll assume it is a CSID and complain if it does not match
147 return new Specifier(SpecifierForm.CSID, specifierIn);
149 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
150 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
151 if (closeParen >= 0) {
152 return new Specifier(SpecifierForm.URN_NAME,
153 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
155 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
156 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
157 if (closeParen >= 0) {
158 return new Specifier(SpecifierForm.CSID,
159 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
164 logger.error(method + ": bad or missing specifier!");
165 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
166 op + " failed on bad or missing Authority specifier").type(
167 "text/plain").build();
168 throw new WebApplicationException(response);
172 * Instantiates a new Authority resource.
174 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
175 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
176 this.authCommonClass = authCommonClass;
177 this.resourceClass = resourceClass;
178 this.authorityCommonSchemaName = authorityCommonSchemaName;
179 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
182 public abstract String getItemServiceName();
185 protected String getVersionString() {
186 return "$LastChangedRevision: 2617 $";
190 public Class<AuthCommon> getCommonPartClass() {
191 return authCommonClass;
195 * Creates the item document handler.
198 * @param inAuthority the in vocabulary
200 * @return the document handler
202 * @throws Exception the exception
204 protected DocumentHandler createItemDocumentHandler(
205 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
206 String inAuthority, String parentShortIdentifier)
208 String authorityRefNameBase;
209 AuthorityItemDocumentModelHandler<?> docHandler;
211 if (parentShortIdentifier == null) {
212 authorityRefNameBase = null;
214 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
215 createServiceContext(getServiceName());
216 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
217 // Get from parent document
218 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
220 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
223 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
224 ctx.getCommonPartLabel(getItemServiceName()),
226 docHandler.setInAuthority(inAuthority);
227 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
232 public String getAuthShortIdentifier(
233 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
234 throws DocumentNotFoundException, DocumentException {
235 String shortIdentifier = null;
237 AuthorityDocumentModelHandler<?> handler =
238 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
239 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
240 } catch (Exception e) {
241 if (logger.isDebugEnabled()) {
242 logger.debug("Caught exception ", e);
244 throw new DocumentException(e);
246 return shortIdentifier;
249 protected String buildAuthorityRefNameBase(
250 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
251 RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(),
252 ctx.getServiceName(), shortIdentifier, null);
253 return authority.toString();
256 public static class CsidAndShortIdentifier {
259 String shortIdentifier;
262 protected String lookupParentCSID(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
264 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams);
265 return tempResult.CSID;
268 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
270 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
271 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
272 // Note that we have to create the service context for the Items, not the main service
274 String parentShortIdentifier;
275 if (parentSpec.form == SpecifierForm.CSID) {
276 parentShortIdentifier = null;
277 parentcsid = parentSpec.value;
278 // Uncomment when app layer is ready to integrate
279 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
280 parentShortIdentifier = FETCH_SHORT_ID;
282 parentShortIdentifier = parentSpec.value;
283 String whereClause = buildWhereForAuthByName(parentSpec.value);
284 ServiceContext ctx = createServiceContext(getServiceName(), queryParams);
285 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
287 result.CSID = parentcsid;
288 result.shortIdentifier = parentShortIdentifier;
292 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext ctx)
293 throws DocumentException {
295 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
296 if (itemSpec.form == SpecifierForm.CSID) {
297 itemcsid = itemSpec.value;
299 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
300 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
306 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
307 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
308 * Resource. They then call this method on that resource.
311 public DocumentModel getDocModelForAuthorityItem(RepositoryInstance repoSession, RefName.AuthorityItem item)
312 throws Exception, DocumentNotFoundException {
316 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
317 // Ensure we have the right context.
318 ServiceContext ctx = createServiceContext(item.inAuthority.resource);
320 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
321 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
322 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
324 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
325 ctx = createServiceContext(getItemServiceName());
326 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
327 DocumentModel docModel = docWrapper.getWrappedObject();
332 @POST //FIXME: REM - 5/1/2012 - We can probably remove this method.
333 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.
335 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
336 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
337 DocumentHandler handler = createDocumentHandler(ctx);
338 String csid = getRepositoryClient(ctx).create(ctx, handler);
339 UriBuilder path = UriBuilder.fromResource(resourceClass);
340 path.path("" + csid);
341 Response response = Response.created(path.build()).build();
343 } catch (Exception e) {
344 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
348 protected String buildWhereForAuthByName(String name) {
349 return authorityCommonSchemaName
350 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
354 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
355 return authorityItemCommonSchemaName
356 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
357 + "='" + name + "' AND "
358 + authorityItemCommonSchemaName + ":"
359 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
360 + "'" + parentcsid + "'";
364 * Gets the authority.
366 * @param specifier either a CSID or one of the urn forms
368 * @return the authority
373 public byte[] get( // getAuthority(
375 @PathParam("csid") String specifier) {
376 PoxPayloadOut result = null;
378 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
379 DocumentHandler handler = createDocumentHandler(ctx);
381 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
382 if (spec.form == SpecifierForm.CSID) {
383 if (logger.isDebugEnabled()) {
384 logger.debug("getAuthority with csid=" + spec.value);
386 getRepositoryClient(ctx).get(ctx, spec.value, handler);
388 String whereClause = buildWhereForAuthByName(spec.value);
389 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
390 handler.setDocumentFilter(myFilter);
391 getRepositoryClient(ctx).get(ctx, handler);
393 result = ctx.getOutput();
395 } catch (Exception e) {
396 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
399 if (result == null) {
400 Response response = Response.status(Response.Status.NOT_FOUND).entity(
401 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
402 "text/plain").build();
403 throw new WebApplicationException(response);
406 return result.getBytes();
410 * Finds and populates the authority list.
414 * @return the authority list
417 @Produces("application/xml")
418 public AbstractCommonList getAuthorityList(@Context UriInfo ui) {
420 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
421 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
422 DocumentHandler handler = createDocumentHandler(ctx);
423 DocumentFilter myFilter = handler.getDocumentFilter();
424 // Need to make the default sort order for authority items
425 // be on the displayName field
426 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
427 if (sortBy == null || sortBy.isEmpty()) {
428 // String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
429 // + AuthorityItemJAXBSchema.DISPLAY_NAME;
430 String qualifiedDisplayNameField = AuthorityItemJAXBSchema.TERM_INFO_GROUP_SCHEMA_NAME + ":"
431 + AuthorityItemJAXBSchema.TERM_DISPLAY_NAME;
432 myFilter.setOrderByClause(qualifiedDisplayNameField);
434 String nameQ = queryParams.getFirst("refName");
436 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
438 getRepositoryClient(ctx).getFiltered(ctx, handler);
439 return (AbstractCommonList) handler.getCommonPartList();
440 } catch (Exception e) {
441 throw bigReThrow(e, ServiceMessages.GET_FAILED);
448 * @param specifier the csid or id
450 * @return the multipart output
454 public byte[] updateAuthority(
455 @PathParam("csid") String specifier,
457 PoxPayloadOut result = null;
459 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
460 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
461 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
462 DocumentHandler handler = createDocumentHandler(ctx);
464 if (spec.form == SpecifierForm.CSID) {
467 String whereClause = buildWhereForAuthByName(spec.value);
468 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
470 getRepositoryClient(ctx).update(ctx, csid, handler);
471 result = ctx.getOutput();
472 } catch (Exception e) {
473 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
475 return result.getBytes();
481 * @param csid the csid
483 * @return the response
487 public Response deleteAuthority(@PathParam("csid") String csid) {
488 if (logger.isDebugEnabled()) {
489 logger.debug("deleteAuthority with csid=" + csid);
492 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
493 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
494 DocumentHandler handler = createDocumentHandler(ctx);
495 getRepositoryClient(ctx).delete(ctx, csid, handler);
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();
552 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
553 // they should be consolidated -be DRY (don't repeat yourself).
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;
564 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
565 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
566 WorkflowClient.SERVICE_COMMONPART_NAME);
567 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
569 // Create a service context and document handler for the parent resource.
570 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
571 DocumentHandler parentDocHandler = this.createDocumentHandler(parentCtx);
572 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
574 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
575 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
576 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
578 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
579 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
580 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
582 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
583 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
584 result = ctx.getOutput();
585 } catch (Exception e) {
586 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
589 return result.getBytes();
593 * Gets the authority item.
595 * @param parentspecifier either a CSID or one of the urn forms
596 * @param itemspecifier either a CSID or one of the urn forms
598 * @return the authority item
601 @Path("{csid}/items/{itemcsid}")
602 public byte[] getAuthorityItem(
603 @Context Request request,
605 @PathParam("csid") String parentspecifier,
606 @PathParam("itemcsid") String itemspecifier) {
607 PoxPayloadOut result = null;
609 JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
610 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
611 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
613 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
614 ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
615 ctx.setJaxRsContext(jaxRsContext);
617 ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui.
619 // We omit the parentShortId, only needed when doing a create...
620 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
622 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
623 if (itemSpec.form == SpecifierForm.CSID) {
624 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
626 String itemWhereClause =
627 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
628 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
629 handler.setDocumentFilter(myFilter);
630 getRepositoryClient(ctx).get(ctx, handler);
632 // TODO should we assert that the item is in the passed vocab?
633 result = ctx.getOutput();
634 } catch (Exception e) {
635 throw bigReThrow(e, ServiceMessages.GET_FAILED);
637 if (result == null) {
638 Response response = Response.status(Response.Status.NOT_FOUND).entity(
639 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
640 "text/plain").build();
641 throw new WebApplicationException(response);
643 return result.getBytes();
647 * Gets the authorityItem list for the specified authority
648 * If partialPerm is specified, keywords will be ignored.
650 * @param specifier either a CSID or one of the urn forms
651 * @param partialTerm if non-null, matches partial terms
652 * @param keywords if non-null, matches terms in the keyword index for items
653 * @param ui passed to include additional parameters, like pagination controls
655 * @return the authorityItem list
658 @Path("{csid}/items")
659 @Produces("application/xml")
660 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
661 @Context UriInfo ui) {
663 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
664 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
665 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
666 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
667 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
669 String qualifiedDisplayNameField = authorityItemCommonSchemaName + ":"
670 + AuthorityItemJAXBSchema.DISPLAY_NAME;
672 // Note that docType defaults to the ServiceName, so we're fine with that.
673 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
675 String parentcsid = PARENT_WILDCARD.equals(specifier)?null:
676 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
678 ctx = createServiceContext(getItemServiceName(), queryParams);
680 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
681 // We omit the parentShortId, only needed when doing a create...
682 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
684 DocumentFilter myFilter = handler.getDocumentFilter();
685 // Need to make the default sort order for authority items
686 // be on the displayName field
687 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
688 if (sortBy == null || sortBy.isEmpty()) {
689 myFilter.setOrderByClause(qualifiedDisplayNameField);
692 // If we are not wildcarding the parent, add a restriction
693 if(parentcsid!=null) {
694 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
695 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
696 + "'" + parentcsid + "'",
697 IQueryManager.SEARCH_QUALIFIER_AND);
700 if (Tools.notBlank(termStatus)) {
701 // Start with the qualified termStatus field
702 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
703 + AuthorityItemJAXBSchema.TERM_STATUS;
704 String[] filterTerms = termStatus.trim().split("\\|");
705 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
706 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
709 // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
710 // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
711 // the PT query param trumps the KW and AS query params.
712 if (partialTerm != null && !partialTerm.isEmpty()) {
713 String ptClause = QueryManager.createWhereClauseForPartialMatch(
714 qualifiedDisplayNameField, partialTerm);
715 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
716 } else if (keywords != null || advancedSearch != null) {
717 // String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
718 // myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
719 return search(ctx, handler, queryParams, keywords, advancedSearch);
721 if (logger.isDebugEnabled()) {
722 logger.debug("getAuthorityItemList filtered WHERE clause: "
723 + myFilter.getWhereClause());
725 getRepositoryClient(ctx).getFiltered(ctx, handler);
726 return (AbstractCommonList) handler.getCommonPartList();
727 } catch (Exception e) {
728 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
733 * @return the name of the property used to specify references for items in this type of
734 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
735 * Some types (like Vocabulary) use a separate property.
737 protected String getRefPropName() {
738 return ServiceBindingUtils.AUTH_REF_PROP;
742 * Gets the entities referencing this Authority item instance. The service type
743 * can be passed as a query param "type", and must match a configured type
744 * for the service bindings. If not set, the type defaults to
745 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
747 * @param parentspecifier either a CSID or one of the urn forms
748 * @param itemspecifier either a CSID or one of the urn forms
751 * @return the info for the referencing objects
754 @Path("{csid}/items/{itemcsid}/refObjs")
755 @Produces("application/xml")
756 public AuthorityRefDocList getReferencingObjects(
757 @PathParam("csid") String parentspecifier,
758 @PathParam("itemcsid") String itemspecifier,
759 @Context UriInfo ui) {
760 AuthorityRefDocList authRefDocList = null;
762 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
764 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
766 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
767 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
769 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
770 if(serviceTypes == null || serviceTypes.isEmpty()) {
771 // Temporary workaround for CSPACE-4983
772 // serviceTypes = ServiceBindingUtils.getCommonServiceTypes();
773 serviceTypes = ServiceBindingUtils.getCommonProcedureServiceTypes();
776 // Note that we have to create the service context for the Items, not the main service
777 // We omit the parentShortId, only needed when doing a create...
778 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
779 createItemDocumentHandler(ctx, parentcsid, null);
781 authRefDocList = handler.getReferencingObjects(ctx, serviceTypes, getRefPropName(), itemcsid);
782 } catch (Exception e) {
783 throw bigReThrow(e, ServiceMessages.GET_FAILED);
785 if (authRefDocList == null) {
786 Response response = Response.status(Response.Status.NOT_FOUND).entity(
787 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
788 "text/plain").build();
789 throw new WebApplicationException(response);
791 return authRefDocList;
795 * Gets the authority terms used in the indicated Authority item.
797 * @param parentspecifier either a CSID or one of the urn forms
798 * @param itemspecifier either a CSID or one of the urn forms
799 * @param ui passed to include additional parameters, like pagination controls
801 * @return the authority refs for the Authority item.
804 @Path("{csid}/items/{itemcsid}/authorityrefs")
805 @Produces("application/xml")
806 public AuthorityRefList getAuthorityItemAuthorityRefs(
807 @PathParam("csid") String parentspecifier,
808 @PathParam("itemcsid") String itemspecifier,
809 @Context UriInfo ui) {
810 AuthorityRefList authRefList = null;
812 // Note that we have to create the service context for the Items, not the main service
813 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
814 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
816 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
818 ctx = createServiceContext(getItemServiceName(), queryParams);
819 // We omit the parentShortId, only needed when doing a create...
820 DocumentModelHandler handler =
821 (DocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, null);
823 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
825 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
826 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
827 } catch (Exception e) {
828 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
834 * Update authorityItem.
836 * @param parentspecifier either a CSID or one of the urn forms
837 * @param itemspecifier either a CSID or one of the urn forms
839 * @return the multipart output
842 @Path("{csid}/items/{itemcsid}")
843 public byte[] updateAuthorityItem(
844 @Context ResourceMap resourceMap,
846 @PathParam("csid") String parentspecifier,
847 @PathParam("itemcsid") String itemspecifier,
849 PoxPayloadOut result = null;
851 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
852 // Note that we have to create the service context for the Items, not the main service
853 //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
854 String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
856 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
857 ctx.setResourceMap(resourceMap);
858 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
860 // We omit the parentShortId, only needed when doing a create...
861 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
863 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
864 result = ctx.getOutput();
866 } catch (Exception e) {
867 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
869 return result.getBytes();
873 * Delete authorityItem.
875 * @param parentcsid the parentcsid
876 * @param itemcsid the itemcsid
878 * @return the response
881 @Path("{csid}/items/{itemcsid}")
882 public Response deleteAuthorityItem(
883 @PathParam("csid") String parentcsid,
884 @PathParam("itemcsid") String itemcsid) {
886 if (logger.isDebugEnabled()) {
887 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
890 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
891 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
892 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
893 // }catch (Throwable t){
894 // System.out.println("ERROR in setting up DELETE: "+t);
897 // Note that we have to create the service context for the Items, not the main service
898 ServiceContext ctx = createServiceContext(getItemServiceName());
899 DocumentHandler handler = createDocumentHandler(ctx);
900 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
901 return Response.status(HttpResponseCodes.SC_OK).build();
902 } catch (Exception e) {
903 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
906 public final static String hierarchy = "hierarchy";
909 @Path("{csid}/items/{itemcsid}/" + hierarchy)
910 @Produces("application/xml")
911 public String getHierarchy(@PathParam("csid") String csid,
912 @PathParam("itemcsid") String itemcsid,
913 @Context UriInfo ui) throws Exception {
915 // 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...?
916 String calledUri = ui.getPath();
917 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
918 ServiceContext ctx = createServiceContext(getItemServiceName());
920 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
921 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
922 return Hierarchy.surface(ctx, itemcsid, uri);
924 return Hierarchy.dive(ctx, itemcsid, uri);
926 } catch (Exception e) {
927 throw bigReThrow(e, "Error showing hierarchy", itemcsid);