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();
333 public Response createAuthority(String xmlPayload) {
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 myFilter.setOrderByClause(qualifiedDisplayNameField);
432 String nameQ = queryParams.getFirst("refName");
434 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
436 getRepositoryClient(ctx).getFiltered(ctx, handler);
437 return (AbstractCommonList) handler.getCommonPartList();
438 } catch (Exception e) {
439 throw bigReThrow(e, ServiceMessages.GET_FAILED);
446 * @param specifier the csid or id
448 * @return the multipart output
452 public byte[] updateAuthority(
453 @PathParam("csid") String specifier,
455 PoxPayloadOut result = null;
457 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
458 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
459 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
460 DocumentHandler handler = createDocumentHandler(ctx);
462 if (spec.form == SpecifierForm.CSID) {
465 String whereClause = buildWhereForAuthByName(spec.value);
466 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
468 getRepositoryClient(ctx).update(ctx, csid, handler);
469 result = ctx.getOutput();
470 } catch (Exception e) {
471 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
473 return result.getBytes();
479 * @param csid the csid
481 * @return the response
485 public Response deleteAuthority(@PathParam("csid") String csid) {
486 if (logger.isDebugEnabled()) {
487 logger.debug("deleteAuthority with csid=" + csid);
490 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
491 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
492 DocumentHandler handler = createDocumentHandler(ctx);
493 getRepositoryClient(ctx).delete(ctx, csid, handler);
494 return Response.status(HttpResponseCodes.SC_OK).build();
495 } catch (Exception e) {
496 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
500 /*************************************************************************
501 * Create an AuthorityItem - this is a sub-resource of Authority
502 * @param specifier either a CSID or one of the urn forms
503 * @return Authority item response
504 *************************************************************************/
506 @Path("{csid}/items")
507 public Response createAuthorityItem(@Context ResourceMap resourceMap, @Context UriInfo ui,
508 @PathParam("csid") String specifier, String xmlPayload) {
510 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
511 ServiceContext ctx = createServiceContext(getItemServiceName(), input);
512 ctx.setResourceMap(resourceMap);
513 ctx.setUriInfo(ui); //Laramie
515 // Note: must have the parentShortId, to do the create.
516 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
517 DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
518 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
519 UriBuilder path = UriBuilder.fromResource(resourceClass);
520 path.path(parent.CSID + "/items/" + itemcsid);
521 Response response = Response.created(path.build()).build();
523 } catch (Exception e) {
524 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
529 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
530 public byte[] getItemWorkflow(
531 @PathParam("csid") String csid,
532 @PathParam("itemcsid") String itemcsid) {
533 PoxPayloadOut result = null;
536 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
537 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
539 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
540 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
541 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
542 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
543 result = ctx.getOutput();
544 } catch (Exception e) {
545 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
547 return result.getBytes();
550 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
551 // they should be consolidated -be DRY (don't repeat yourself).
553 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
554 public byte[] updateItemWorkflowWithTransition(
555 @PathParam("csid") String csid,
556 @PathParam("itemcsid") String itemcsid,
557 @PathParam("transition") String transition) {
558 PoxPayloadOut result = null;
562 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
563 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
564 WorkflowClient.SERVICE_COMMONPART_NAME);
565 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
567 // Create a service context and document handler for the parent resource.
568 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
569 DocumentHandler parentDocHandler = this.createDocumentHandler(parentCtx);
570 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
572 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
573 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
574 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
576 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
577 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
578 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
580 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
581 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
582 result = ctx.getOutput();
583 } catch (Exception e) {
584 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
587 return result.getBytes();
591 * Gets the authority item.
593 * @param parentspecifier either a CSID or one of the urn forms
594 * @param itemspecifier either a CSID or one of the urn forms
596 * @return the authority item
599 @Path("{csid}/items/{itemcsid}")
600 public byte[] getAuthorityItem(
601 @Context Request request,
603 @PathParam("csid") String parentspecifier,
604 @PathParam("itemcsid") String itemspecifier) {
605 PoxPayloadOut result = null;
607 JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
608 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
609 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
611 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
612 ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
613 ctx.setJaxRsContext(jaxRsContext);
615 ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui.
617 // We omit the parentShortId, only needed when doing a create...
618 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
620 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
621 if (itemSpec.form == SpecifierForm.CSID) {
622 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
624 String itemWhereClause =
625 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
626 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
627 handler.setDocumentFilter(myFilter);
628 getRepositoryClient(ctx).get(ctx, handler);
630 // TODO should we assert that the item is in the passed vocab?
631 result = ctx.getOutput();
632 } catch (Exception e) {
633 throw bigReThrow(e, ServiceMessages.GET_FAILED);
635 if (result == null) {
636 Response response = Response.status(Response.Status.NOT_FOUND).entity(
637 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
638 "text/plain").build();
639 throw new WebApplicationException(response);
641 return result.getBytes();
645 * Gets the authorityItem list for the specified authority
646 * If partialPerm is specified, keywords will be ignored.
648 * @param specifier either a CSID or one of the urn forms
649 * @param partialTerm if non-null, matches partial terms
650 * @param keywords if non-null, matches terms in the keyword index for items
651 * @param ui passed to include additional parameters, like pagination controls
653 * @return the authorityItem list
656 @Path("{csid}/items")
657 @Produces("application/xml")
658 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
659 @Context UriInfo ui) {
661 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
662 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
663 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
664 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
665 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
667 String qualifiedDisplayNameField = authorityItemCommonSchemaName + ":"
668 + AuthorityItemJAXBSchema.DISPLAY_NAME;
670 // Note that docType defaults to the ServiceName, so we're fine with that.
671 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
673 String parentcsid = PARENT_WILDCARD.equals(specifier)?null:
674 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
676 ctx = createServiceContext(getItemServiceName(), queryParams);
678 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
679 // We omit the parentShortId, only needed when doing a create...
680 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
682 DocumentFilter myFilter = handler.getDocumentFilter();
683 // Need to make the default sort order for authority items
684 // be on the displayName field
685 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
686 if (sortBy == null || sortBy.isEmpty()) {
687 myFilter.setOrderByClause(qualifiedDisplayNameField);
690 // If we are not wildcarding the parent, add a restriction
691 if(parentcsid!=null) {
692 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
693 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
694 + "'" + parentcsid + "'",
695 IQueryManager.SEARCH_QUALIFIER_AND);
698 if (Tools.notBlank(termStatus)) {
699 // Start with the qualified termStatus field
700 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
701 + AuthorityItemJAXBSchema.TERM_STATUS;
702 String[] filterTerms = termStatus.trim().split("\\|");
703 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
704 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
707 // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
708 // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
709 // the PT query param trumps the KW and AS query params.
710 if (partialTerm != null && !partialTerm.isEmpty()) {
711 String ptClause = QueryManager.createWhereClauseForPartialMatch(
712 qualifiedDisplayNameField, partialTerm);
713 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
714 } else if (keywords != null || advancedSearch != null) {
715 // String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
716 // myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
717 return search(ctx, handler, queryParams, keywords, advancedSearch);
719 if (logger.isDebugEnabled()) {
720 logger.debug("getAuthorityItemList filtered WHERE clause: "
721 + myFilter.getWhereClause());
723 getRepositoryClient(ctx).getFiltered(ctx, handler);
724 return (AbstractCommonList) handler.getCommonPartList();
725 } catch (Exception e) {
726 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
731 * @return the name of the property used to specify references for items in this type of
732 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
733 * Some types (like Vocabulary) use a separate property.
735 protected String getRefPropName() {
736 return ServiceBindingUtils.AUTH_REF_PROP;
740 * Gets the entities referencing this Authority item instance. The service type
741 * can be passed as a query param "type", and must match a configured type
742 * for the service bindings. If not set, the type defaults to
743 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
745 * @param parentspecifier either a CSID or one of the urn forms
746 * @param itemspecifier either a CSID or one of the urn forms
749 * @return the info for the referencing objects
752 @Path("{csid}/items/{itemcsid}/refObjs")
753 @Produces("application/xml")
754 public AuthorityRefDocList getReferencingObjects(
755 @PathParam("csid") String parentspecifier,
756 @PathParam("itemcsid") String itemspecifier,
757 @Context UriInfo ui) {
758 AuthorityRefDocList authRefDocList = null;
760 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
762 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
764 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
765 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
767 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
768 if(serviceTypes == null || serviceTypes.isEmpty()) {
769 // Temporary workaround for CSPACE-4983
770 // serviceTypes = ServiceBindingUtils.getCommonServiceTypes();
771 serviceTypes = ServiceBindingUtils.getCommonProcedureServiceTypes();
774 // Note that we have to create the service context for the Items, not the main service
775 // We omit the parentShortId, only needed when doing a create...
776 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
777 createItemDocumentHandler(ctx, parentcsid, null);
779 authRefDocList = handler.getReferencingObjects(ctx, serviceTypes, getRefPropName(), itemcsid);
780 } catch (Exception e) {
781 throw bigReThrow(e, ServiceMessages.GET_FAILED);
783 if (authRefDocList == null) {
784 Response response = Response.status(Response.Status.NOT_FOUND).entity(
785 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
786 "text/plain").build();
787 throw new WebApplicationException(response);
789 return authRefDocList;
793 * Gets the authority terms used in the indicated Authority item.
795 * @param parentspecifier either a CSID or one of the urn forms
796 * @param itemspecifier either a CSID or one of the urn forms
797 * @param ui passed to include additional parameters, like pagination controls
799 * @return the authority refs for the Authority item.
802 @Path("{csid}/items/{itemcsid}/authorityrefs")
803 @Produces("application/xml")
804 public AuthorityRefList getAuthorityItemAuthorityRefs(
805 @PathParam("csid") String parentspecifier,
806 @PathParam("itemcsid") String itemspecifier,
807 @Context UriInfo ui) {
808 AuthorityRefList authRefList = null;
810 // Note that we have to create the service context for the Items, not the main service
811 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
812 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
814 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
816 ctx = createServiceContext(getItemServiceName(), queryParams);
817 // We omit the parentShortId, only needed when doing a create...
818 DocumentModelHandler handler =
819 (DocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, null);
821 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
823 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
824 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
825 } catch (Exception e) {
826 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
832 * Update authorityItem.
834 * @param parentspecifier either a CSID or one of the urn forms
835 * @param itemspecifier either a CSID or one of the urn forms
837 * @return the multipart output
840 @Path("{csid}/items/{itemcsid}")
841 public byte[] updateAuthorityItem(
842 @Context ResourceMap resourceMap,
844 @PathParam("csid") String parentspecifier,
845 @PathParam("itemcsid") String itemspecifier,
847 PoxPayloadOut result = null;
849 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
850 // Note that we have to create the service context for the Items, not the main service
851 //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
852 String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
854 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
855 ctx.setResourceMap(resourceMap);
856 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
858 // We omit the parentShortId, only needed when doing a create...
859 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
861 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
862 result = ctx.getOutput();
864 } catch (Exception e) {
865 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
867 return result.getBytes();
871 * Delete authorityItem.
873 * @param parentcsid the parentcsid
874 * @param itemcsid the itemcsid
876 * @return the response
879 @Path("{csid}/items/{itemcsid}")
880 public Response deleteAuthorityItem(
881 @PathParam("csid") String parentcsid,
882 @PathParam("itemcsid") String itemcsid) {
884 if (logger.isDebugEnabled()) {
885 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
888 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
889 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
890 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
891 // }catch (Throwable t){
892 // System.out.println("ERROR in setting up DELETE: "+t);
895 // Note that we have to create the service context for the Items, not the main service
896 ServiceContext ctx = createServiceContext(getItemServiceName());
897 DocumentHandler handler = createDocumentHandler(ctx);
898 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
899 return Response.status(HttpResponseCodes.SC_OK).build();
900 } catch (Exception e) {
901 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
904 public final static String hierarchy = "hierarchy";
907 @Path("{csid}/items/{itemcsid}/" + hierarchy)
908 @Produces("application/xml")
909 public String getHierarchy(@PathParam("csid") String csid,
910 @PathParam("itemcsid") String itemcsid,
911 @Context UriInfo ui) throws Exception {
913 // 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...?
914 String calledUri = ui.getPath();
915 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
916 ServiceContext ctx = createServiceContext(getItemServiceName());
918 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
919 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
920 return Hierarchy.surface(ctx, itemcsid, uri);
922 return Hierarchy.dive(ctx, itemcsid, uri);
924 } catch (Exception e) {
925 throw bigReThrow(e, "Error showing hierarchy", itemcsid);