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.HashMap;
85 import java.util.List;
87 import org.collectionspace.services.client.*;
88 import org.collectionspace.services.common.*;
89 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
92 * The Class AuthorityResource.
98 * @param <AuthItemHandler>
103 * @param <AuthCommon>
104 * @param <AuthItemHandler>
106 @Consumes("application/xml")
107 @Produces("application/xml")
108 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
109 extends ResourceBase {
111 final static String SEARCH_TYPE_TERMSTATUS = "ts";
113 protected Class<AuthCommon> authCommonClass;
114 protected Class<?> resourceClass;
115 protected String authorityCommonSchemaName;
116 protected String authorityItemCommonSchemaName;
117 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
118 final static String URN_PREFIX = "urn:cspace:";
119 final static int URN_PREFIX_LEN = URN_PREFIX.length();
120 final static String URN_PREFIX_NAME = "name(";
121 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
122 final static String URN_PREFIX_ID = "id(";
123 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
124 final static String FETCH_SHORT_ID = "_fetch_";
125 final static String PARENT_WILDCARD = "_ALL_";
127 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
129 public enum SpecifierForm {
134 public class Specifier {
136 public SpecifierForm form;
139 Specifier(SpecifierForm form, String value) {
145 protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException {
146 if (logger.isDebugEnabled()) {
147 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
149 if (specifierIn != null) {
150 if (!specifierIn.startsWith(URN_PREFIX)) {
151 // We'll assume it is a CSID and complain if it does not match
152 return new Specifier(SpecifierForm.CSID, specifierIn);
154 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
155 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
156 if (closeParen >= 0) {
157 return new Specifier(SpecifierForm.URN_NAME,
158 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
160 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
161 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
162 if (closeParen >= 0) {
163 return new Specifier(SpecifierForm.CSID,
164 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
169 logger.error(method + ": bad or missing specifier!");
170 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
171 op + " failed on bad or missing Authority specifier").type(
172 "text/plain").build();
173 throw new WebApplicationException(response);
177 * Instantiates a new Authority resource.
179 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
180 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
181 this.authCommonClass = authCommonClass;
182 this.resourceClass = resourceClass;
183 this.authorityCommonSchemaName = authorityCommonSchemaName;
184 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
187 public abstract String getItemServiceName();
189 public abstract String getItemTermInfoGroupXPathBase();
192 protected String getVersionString() {
193 return "$LastChangedRevision: 2617 $";
197 public Class<AuthCommon> getCommonPartClass() {
198 return authCommonClass;
202 * Creates the item document handler.
205 * @param inAuthority the in vocabulary
207 * @return the document handler
209 * @throws Exception the exception
211 protected DocumentHandler createItemDocumentHandler(
212 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
213 String inAuthority, String parentShortIdentifier)
215 String authorityRefNameBase;
216 AuthorityItemDocumentModelHandler<?> docHandler;
218 if (parentShortIdentifier == null) {
219 authorityRefNameBase = null;
221 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
222 createServiceContext(getServiceName());
223 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
224 // Get from parent document
225 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
227 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
230 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
231 ctx.getCommonPartLabel(getItemServiceName()),
233 // FIXME - Richard and Aron think the following three lines should
234 // be in the constructor for the AuthorityItemDocumentModelHandler
235 // because all three are required fields.
236 docHandler.setInAuthority(inAuthority);
237 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
238 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
242 public String getAuthShortIdentifier(
243 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
244 throws DocumentNotFoundException, DocumentException {
245 String shortIdentifier = null;
247 AuthorityDocumentModelHandler<?> handler =
248 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
249 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
250 } catch (Exception e) {
251 if (logger.isDebugEnabled()) {
252 logger.debug("Caught exception ", e);
254 throw new DocumentException(e);
256 return shortIdentifier;
259 protected String buildAuthorityRefNameBase(
260 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
261 RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(),
262 ctx.getServiceName(), shortIdentifier, null);
263 return authority.toString();
266 public static class CsidAndShortIdentifier {
269 String shortIdentifier;
272 protected String lookupParentCSID(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
274 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams);
275 return tempResult.CSID;
278 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
280 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
281 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
282 // Note that we have to create the service context for the Items, not the main service
284 String parentShortIdentifier;
285 if (parentSpec.form == SpecifierForm.CSID) {
286 parentShortIdentifier = null;
287 parentcsid = parentSpec.value;
288 // Uncomment when app layer is ready to integrate
289 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
290 parentShortIdentifier = FETCH_SHORT_ID;
292 parentShortIdentifier = parentSpec.value;
293 String whereClause = buildWhereForAuthByName(parentSpec.value);
294 ServiceContext ctx = createServiceContext(getServiceName(), queryParams);
295 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
297 result.CSID = parentcsid;
298 result.shortIdentifier = parentShortIdentifier;
302 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext ctx)
303 throws DocumentException {
305 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
306 if (itemSpec.form == SpecifierForm.CSID) {
307 itemcsid = itemSpec.value;
309 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
310 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
316 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
317 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
318 * Resource. They then call this method on that resource.
321 public DocumentModel getDocModelForAuthorityItem(RepositoryInstance repoSession, RefName.AuthorityItem item)
322 throws Exception, DocumentNotFoundException {
326 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
327 // Ensure we have the right context.
328 ServiceContext ctx = createServiceContext(item.inAuthority.resource);
330 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
331 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
332 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
334 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
335 ctx = createServiceContext(getItemServiceName());
336 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
337 DocumentModel docModel = docWrapper.getWrappedObject();
342 @POST //FIXME: REM - 5/1/2012 - We can probably remove this method.
343 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.
345 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
346 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
347 DocumentHandler handler = createDocumentHandler(ctx);
348 String csid = getRepositoryClient(ctx).create(ctx, handler);
349 UriBuilder path = UriBuilder.fromResource(resourceClass);
350 path.path("" + csid);
351 Response response = Response.created(path.build()).build();
353 } catch (Exception e) {
354 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
358 protected String buildWhereForAuthByName(String name) {
359 return authorityCommonSchemaName
360 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
364 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
365 return authorityItemCommonSchemaName
366 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
367 + "='" + name + "' AND "
368 + authorityItemCommonSchemaName + ":"
369 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
370 + "'" + parentcsid + "'";
374 * Gets the authority.
376 * @param specifier either a CSID or one of the urn forms
378 * @return the authority
383 public byte[] get( // getAuthority(
385 @PathParam("csid") String specifier) {
386 PoxPayloadOut result = null;
388 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
389 DocumentHandler handler = createDocumentHandler(ctx);
391 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
392 if (spec.form == SpecifierForm.CSID) {
393 if (logger.isDebugEnabled()) {
394 logger.debug("getAuthority with csid=" + spec.value);
396 getRepositoryClient(ctx).get(ctx, spec.value, handler);
398 String whereClause = buildWhereForAuthByName(spec.value);
399 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
400 handler.setDocumentFilter(myFilter);
401 getRepositoryClient(ctx).get(ctx, handler);
403 result = ctx.getOutput();
405 } catch (Exception e) {
406 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
409 if (result == null) {
410 Response response = Response.status(Response.Status.NOT_FOUND).entity(
411 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
412 "text/plain").build();
413 throw new WebApplicationException(response);
416 return result.getBytes();
420 * Finds and populates the authority list.
424 * @return the authority list
427 @Produces("application/xml")
428 public AbstractCommonList getAuthorityList(@Context UriInfo ui) { //FIXME - REM 5/3/2012 - This is not reachable from the JAX-RS dispatcher. Instead the equivalent method in ResourceBase is getting called.
430 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
431 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
432 DocumentHandler handler = createDocumentHandler(ctx);
433 DocumentFilter myFilter = handler.getDocumentFilter();
434 // Need to make the default sort order for authority items
435 // be on the displayName field
436 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
437 if (sortBy == null || sortBy.isEmpty()) {
438 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
439 + AuthorityItemJAXBSchema.DISPLAY_NAME;
440 myFilter.setOrderByClause(qualifiedDisplayNameField);
442 String nameQ = queryParams.getFirst("refName");
444 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
446 getRepositoryClient(ctx).getFiltered(ctx, handler);
447 return (AbstractCommonList) handler.getCommonPartList();
448 } catch (Exception e) {
449 throw bigReThrow(e, ServiceMessages.GET_FAILED);
457 * @param specifier the csid or id
459 * @return the multipart output
463 public byte[] updateAuthority(
464 @PathParam("csid") String specifier,
466 PoxPayloadOut result = null;
468 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
469 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
470 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
471 DocumentHandler handler = createDocumentHandler(ctx);
473 if (spec.form == SpecifierForm.CSID) {
476 String whereClause = buildWhereForAuthByName(spec.value);
477 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
479 getRepositoryClient(ctx).update(ctx, csid, handler);
480 result = ctx.getOutput();
481 } catch (Exception e) {
482 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
484 return result.getBytes();
490 * @param csid the csid
492 * @return the response
496 public Response deleteAuthority(@PathParam("csid") String csid) {
497 if (logger.isDebugEnabled()) {
498 logger.debug("deleteAuthority with csid=" + csid);
501 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
502 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
503 DocumentHandler handler = createDocumentHandler(ctx);
504 getRepositoryClient(ctx).delete(ctx, csid, handler);
505 return Response.status(HttpResponseCodes.SC_OK).build();
506 } catch (Exception e) {
507 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
511 /*************************************************************************
512 * Create an AuthorityItem - this is a sub-resource of Authority
513 * @param specifier either a CSID or one of the urn forms
514 * @return Authority item response
515 *************************************************************************/
517 @Path("{csid}/items")
518 public Response createAuthorityItem(@Context ResourceMap resourceMap, @Context UriInfo ui,
519 @PathParam("csid") String specifier, String xmlPayload) {
521 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
522 ServiceContext ctx = createServiceContext(getItemServiceName(), input);
523 ctx.setResourceMap(resourceMap);
524 ctx.setUriInfo(ui); //Laramie
526 // Note: must have the parentShortId, to do the create.
527 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
528 DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
529 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
530 UriBuilder path = UriBuilder.fromResource(resourceClass);
531 path.path(parent.CSID + "/items/" + itemcsid);
532 Response response = Response.created(path.build()).build();
534 } catch (Exception e) {
535 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
540 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
541 public byte[] getItemWorkflow(
542 @PathParam("csid") String csid,
543 @PathParam("itemcsid") String itemcsid) {
544 PoxPayloadOut result = null;
547 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
548 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
550 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
551 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
552 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
553 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
554 result = ctx.getOutput();
555 } catch (Exception e) {
556 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
558 return result.getBytes();
561 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
562 // they should be consolidated -be DRY (don't repeat yourself).
564 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
565 public byte[] updateItemWorkflowWithTransition(
566 @PathParam("csid") String csid,
567 @PathParam("itemcsid") String itemcsid,
568 @PathParam("transition") String transition) {
569 PoxPayloadOut result = null;
573 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
574 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
575 WorkflowClient.SERVICE_COMMONPART_NAME);
576 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
578 // Create a service context and document handler for the parent resource.
579 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
580 DocumentHandler parentDocHandler = this.createDocumentHandler(parentCtx);
581 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
583 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
584 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
585 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
587 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
588 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
589 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
591 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
592 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
593 result = ctx.getOutput();
594 } catch (Exception e) {
595 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
598 return result.getBytes();
602 * Gets the authority item.
604 * @param parentspecifier either a CSID or one of the urn forms
605 * @param itemspecifier either a CSID or one of the urn forms
607 * @return the authority item
610 @Path("{csid}/items/{itemcsid}")
611 public byte[] getAuthorityItem(
612 @Context Request request,
614 @PathParam("csid") String parentspecifier,
615 @PathParam("itemcsid") String itemspecifier) {
616 PoxPayloadOut result = null;
618 JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
619 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
620 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
622 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
623 ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
624 ctx.setJaxRsContext(jaxRsContext);
626 ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui.
628 // We omit the parentShortId, only needed when doing a create...
629 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
631 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
632 if (itemSpec.form == SpecifierForm.CSID) {
633 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
635 String itemWhereClause =
636 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
637 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
638 handler.setDocumentFilter(myFilter);
639 getRepositoryClient(ctx).get(ctx, handler);
641 // TODO should we assert that the item is in the passed vocab?
642 result = ctx.getOutput();
643 } catch (Exception e) {
644 throw bigReThrow(e, ServiceMessages.GET_FAILED);
646 if (result == null) {
647 Response response = Response.status(Response.Status.NOT_FOUND).entity(
648 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
649 "text/plain").build();
650 throw new WebApplicationException(response);
652 return result.getBytes();
656 * Most of the authority child classes will/should use this implementation. However, the Vocabulary service's item schema is
657 * different enough that it will have to override this method in it's resource class.
659 protected String getOrderByField() {
660 String result = null;
662 result = NuxeoUtils.getPrimaryElPathPropertyName(
663 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
664 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
669 protected String getPartialTermMatchField() {
670 String result = null;
672 result = NuxeoUtils.getMultiElPathPropertyName(
673 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
674 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
680 * Gets the authorityItem list for the specified authority
681 * If partialPerm is specified, keywords will be ignored.
683 * @param specifier either a CSID or one of the urn forms
684 * @param partialTerm if non-null, matches partial terms
685 * @param keywords if non-null, matches terms in the keyword index for items
686 * @param ui passed to include additional parameters, like pagination controls
688 * @return the authorityItem list
691 @Path("{csid}/items")
692 @Produces("application/xml")
693 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
694 @Context UriInfo ui) {
696 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
697 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
698 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
699 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
700 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
702 // Note that docType defaults to the ServiceName, so we're fine with that.
703 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
705 String parentcsid = PARENT_WILDCARD.equals(specifier)?null:
706 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
708 ctx = createServiceContext(getItemServiceName(), queryParams);
710 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
711 // We omit the parentShortId, only needed when doing a create...
712 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
714 DocumentFilter myFilter = handler.getDocumentFilter();
715 // Need to make the default sort order for authority items
716 // be on the displayName field
717 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
718 if (sortBy == null || sortBy.isEmpty()) {
719 String orderByField = getOrderByField();
720 myFilter.setOrderByClause(orderByField);
723 // If we are not wildcarding the parent, add a restriction
724 if(parentcsid!=null) {
725 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
726 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
727 + "'" + parentcsid + "'",
728 IQueryManager.SEARCH_QUALIFIER_AND);
731 if (Tools.notBlank(termStatus)) {
732 // Start with the qualified termStatus field
733 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
734 + AuthorityItemJAXBSchema.TERM_STATUS;
735 String[] filterTerms = termStatus.trim().split("\\|");
736 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
737 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
740 // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
741 // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
742 // the PT query param trumps the KW and AS query params.
743 if (partialTerm != null && !partialTerm.isEmpty()) {
744 String partialTermMatchField = getPartialTermMatchField();
745 String ptClause = QueryManager.createWhereClauseForPartialMatch(
746 partialTermMatchField, partialTerm);
747 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
748 } else if (keywords != null || advancedSearch != null) {
749 // String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
750 // myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
751 return search(ctx, handler, queryParams, keywords, advancedSearch);
753 if (logger.isDebugEnabled()) {
754 logger.debug("getAuthorityItemList filtered WHERE clause: "
755 + myFilter.getWhereClause()
756 + " and ORDER BY clause: " + myFilter.getOrderByClause());
758 getRepositoryClient(ctx).getFiltered(ctx, handler);
759 return (AbstractCommonList) handler.getCommonPartList();
760 } catch (Exception e) {
761 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
766 * @return the name of the property used to specify references for items in this type of
767 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
768 * Some types (like Vocabulary) use a separate property.
770 protected String getRefPropName() {
771 return ServiceBindingUtils.AUTH_REF_PROP;
775 * Gets the entities referencing this Authority item instance. The service type
776 * can be passed as a query param "type", and must match a configured type
777 * for the service bindings. If not set, the type defaults to
778 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
780 * @param parentspecifier either a CSID or one of the urn forms
781 * @param itemspecifier either a CSID or one of the urn forms
784 * @return the info for the referencing objects
787 @Path("{csid}/items/{itemcsid}/refObjs")
788 @Produces("application/xml")
789 public AuthorityRefDocList getReferencingObjects(
790 @PathParam("csid") String parentspecifier,
791 @PathParam("itemcsid") String itemspecifier,
792 @Context UriInfo ui) {
793 AuthorityRefDocList authRefDocList = null;
795 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
797 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
799 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
800 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
802 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
803 if(serviceTypes == null || serviceTypes.isEmpty()) {
804 // Temporary workaround for CSPACE-4983
805 // serviceTypes = ServiceBindingUtils.getCommonServiceTypes();
806 serviceTypes = ServiceBindingUtils.getCommonProcedureServiceTypes();
809 // Note that we have to create the service context for the Items, not the main service
810 // We omit the parentShortId, only needed when doing a create...
811 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
812 createItemDocumentHandler(ctx, parentcsid, null);
814 authRefDocList = handler.getReferencingObjects(ctx, serviceTypes, getRefPropName(), itemcsid);
815 } catch (Exception e) {
816 throw bigReThrow(e, ServiceMessages.GET_FAILED);
818 if (authRefDocList == null) {
819 Response response = Response.status(Response.Status.NOT_FOUND).entity(
820 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
821 "text/plain").build();
822 throw new WebApplicationException(response);
824 return authRefDocList;
828 * Gets the authority terms used in the indicated Authority item.
830 * @param parentspecifier either a CSID or one of the urn forms
831 * @param itemspecifier either a CSID or one of the urn forms
832 * @param ui passed to include additional parameters, like pagination controls
834 * @return the authority refs for the Authority item.
837 @Path("{csid}/items/{itemcsid}/authorityrefs")
838 @Produces("application/xml")
839 public AuthorityRefList getAuthorityItemAuthorityRefs(
840 @PathParam("csid") String parentspecifier,
841 @PathParam("itemcsid") String itemspecifier,
842 @Context UriInfo ui) {
843 AuthorityRefList authRefList = null;
845 // Note that we have to create the service context for the Items, not the main service
846 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
847 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
849 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
851 ctx = createServiceContext(getItemServiceName(), queryParams);
852 // We omit the parentShortId, only needed when doing a create...
853 DocumentModelHandler handler =
854 (DocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, null);
856 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
858 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
859 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
860 } catch (Exception e) {
861 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
867 * Update authorityItem.
869 * @param parentspecifier either a CSID or one of the urn forms
870 * @param itemspecifier either a CSID or one of the urn forms
872 * @return the multipart output
875 @Path("{csid}/items/{itemcsid}")
876 public byte[] updateAuthorityItem(
877 @Context ResourceMap resourceMap,
879 @PathParam("csid") String parentspecifier,
880 @PathParam("itemcsid") String itemspecifier,
882 PoxPayloadOut result = null;
884 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
885 // Note that we have to create the service context for the Items, not the main service
886 //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
887 String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
889 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
890 ctx.setResourceMap(resourceMap);
891 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
893 // We omit the parentShortId, only needed when doing a create...
894 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
896 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
897 result = ctx.getOutput();
899 } catch (Exception e) {
900 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
902 return result.getBytes();
906 * Delete authorityItem.
908 * @param parentcsid the parentcsid
909 * @param itemcsid the itemcsid
911 * @return the response
914 @Path("{csid}/items/{itemcsid}")
915 public Response deleteAuthorityItem(
916 @PathParam("csid") String parentcsid,
917 @PathParam("itemcsid") String itemcsid) {
919 if (logger.isDebugEnabled()) {
920 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
923 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
924 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
925 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
926 // }catch (Throwable t){
927 // System.out.println("ERROR in setting up DELETE: "+t);
930 // Note that we have to create the service context for the Items, not the main service
931 ServiceContext ctx = createServiceContext(getItemServiceName());
932 DocumentHandler handler = createDocumentHandler(ctx);
933 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
934 return Response.status(HttpResponseCodes.SC_OK).build();
935 } catch (Exception e) {
936 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
939 public final static String hierarchy = "hierarchy";
942 @Path("{csid}/items/{itemcsid}/" + hierarchy)
943 @Produces("application/xml")
944 public String getHierarchy(@PathParam("csid") String csid,
945 @PathParam("itemcsid") String itemcsid,
946 @Context UriInfo ui) throws Exception {
948 // 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...?
949 String calledUri = ui.getPath();
950 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
951 ServiceContext ctx = createServiceContext(getItemServiceName());
953 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
954 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
955 return Hierarchy.surface(ctx, itemcsid, uri);
957 return Hierarchy.dive(ctx, itemcsid, uri);
959 } catch (Exception e) {
960 throw bigReThrow(e, "Error showing hierarchy", itemcsid);
964 public String getItemDocType() {
965 // FIXME: Proof of concept placeholder
966 return getServiceName();
970 public Map<String,StoredValuesUriTemplate> getUriTemplateMap() {
971 // Get resource URI template from superclass
972 Map<String,StoredValuesUriTemplate> uriTemplateMap = super.getUriTemplateMap();
973 // Add item URI template
974 String itemDocType = getItemDocType();
975 StoredValuesUriTemplate itemUriTemplate = getItemUriTemplate();
976 if (itemDocType == null) {
977 return uriTemplateMap; // return map as obtained from superclass
979 if (itemUriTemplate == null) {
980 return uriTemplateMap; // return map as obtained from superclass
982 uriTemplateMap.put(itemDocType, itemUriTemplate);
983 cacheUriTemplateMap(uriTemplateMap);
984 return uriTemplateMap;
987 private StoredValuesUriTemplate getItemUriTemplate() {
988 Map<String,String> storedValuesMap = new HashMap<String,String>();
989 storedValuesMap.put(UriTemplateFactory.SERVICENAME_VAR, getServiceName());
990 StoredValuesUriTemplate template =
991 UriTemplateFactory.getURITemplate(UriTemplateFactory.ITEM,