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.*;
90 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
91 import org.collectionspace.services.config.service.ServiceBindingType;
93 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
96 * The Class AuthorityResource.
101 * @param <AuthCommon>
102 * @param <AuthItemHandler>
107 * @param <AuthCommon>
108 * @param <AuthItemHandler>
110 @Consumes("application/xml")
111 @Produces("application/xml")
112 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
113 extends ResourceBase {
115 final static String SEARCH_TYPE_TERMSTATUS = "ts";
117 protected Class<AuthCommon> authCommonClass;
118 protected Class<?> resourceClass;
119 protected String authorityCommonSchemaName;
120 protected String authorityItemCommonSchemaName;
121 final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType(); //FIXME: REM - 3 Why is this field needed? I see no references to it.
122 final static String URN_PREFIX = "urn:cspace:";
123 final static int URN_PREFIX_LEN = URN_PREFIX.length();
124 final static String URN_PREFIX_NAME = "name(";
125 final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
126 final static String URN_PREFIX_ID = "id(";
127 final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
128 final static String FETCH_SHORT_ID = "_fetch_";
129 final static String PARENT_WILDCARD = "_ALL_";
131 final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
133 public enum SpecifierForm {
138 public class Specifier {
140 public SpecifierForm form;
143 Specifier(SpecifierForm form, String value) {
149 protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException {
150 if (logger.isDebugEnabled()) {
151 logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
153 if (specifierIn != null) {
154 if (!specifierIn.startsWith(URN_PREFIX)) {
155 // We'll assume it is a CSID and complain if it does not match
156 return new Specifier(SpecifierForm.CSID, specifierIn);
158 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
159 int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
160 if (closeParen >= 0) {
161 return new Specifier(SpecifierForm.URN_NAME,
162 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
164 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
165 int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
166 if (closeParen >= 0) {
167 return new Specifier(SpecifierForm.CSID,
168 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
173 logger.error(method + ": bad or missing specifier!");
174 Response response = Response.status(Response.Status.BAD_REQUEST).entity(
175 op + " failed on bad or missing Authority specifier").type(
176 "text/plain").build();
177 throw new WebApplicationException(response);
181 * Instantiates a new Authority resource.
183 public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
184 String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
185 this.authCommonClass = authCommonClass;
186 this.resourceClass = resourceClass;
187 this.authorityCommonSchemaName = authorityCommonSchemaName;
188 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
191 public abstract String getItemServiceName();
193 public abstract String getItemTermInfoGroupXPathBase();
196 protected String getVersionString() {
197 return "$LastChangedRevision: 2617 $";
201 public Class<AuthCommon> getCommonPartClass() {
202 return authCommonClass;
206 * Creates the item document handler.
209 * @param inAuthority the in vocabulary
211 * @return the document handler
213 * @throws Exception the exception
215 protected DocumentHandler createItemDocumentHandler(
216 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
217 String inAuthority, String parentShortIdentifier)
219 String authorityRefNameBase;
220 AuthorityItemDocumentModelHandler<?> docHandler;
222 if (parentShortIdentifier == null) {
223 authorityRefNameBase = null;
225 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
226 createServiceContext(getServiceName());
227 if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
228 // Get from parent document
229 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
231 authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
234 docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
235 ctx.getCommonPartLabel(getItemServiceName()),
237 // FIXME - Richard and Aron think the following three lines should
238 // be in the constructor for the AuthorityItemDocumentModelHandler
239 // because all three are required fields.
240 docHandler.setInAuthority(inAuthority);
241 docHandler.setAuthorityRefNameBase(authorityRefNameBase);
242 docHandler.setItemTermInfoGroupXPathBase(getItemTermInfoGroupXPathBase());
246 public String getAuthShortIdentifier(
247 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
248 throws DocumentNotFoundException, DocumentException {
249 String shortIdentifier = null;
251 AuthorityDocumentModelHandler<?> handler =
252 (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
253 shortIdentifier = handler.getShortIdentifier(authCSID, authorityCommonSchemaName);
254 } catch (Exception e) {
255 if (logger.isDebugEnabled()) {
256 logger.debug("Caught exception ", e);
258 throw new DocumentException(e);
260 return shortIdentifier;
263 protected String buildAuthorityRefNameBase(
264 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
265 RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(),
266 ctx.getServiceName(), shortIdentifier, null);
267 return authority.toString();
270 public static class CsidAndShortIdentifier {
273 String shortIdentifier;
276 protected String lookupParentCSID(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
278 CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams);
279 return tempResult.CSID;
282 private CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
284 CsidAndShortIdentifier result = new CsidAndShortIdentifier();
285 Specifier parentSpec = getSpecifier(parentspecifier, method, op);
286 // Note that we have to create the service context for the Items, not the main service
288 String parentShortIdentifier;
289 if (parentSpec.form == SpecifierForm.CSID) {
290 parentShortIdentifier = null;
291 parentcsid = parentSpec.value;
292 // Uncomment when app layer is ready to integrate
293 // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
294 parentShortIdentifier = FETCH_SHORT_ID;
296 parentShortIdentifier = parentSpec.value;
297 String whereClause = buildWhereForAuthByName(parentSpec.value);
298 ServiceContext ctx = createServiceContext(getServiceName(), queryParams);
299 parentcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
301 result.CSID = parentcsid;
302 result.shortIdentifier = parentShortIdentifier;
306 public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext ctx)
307 throws DocumentException {
309 Specifier itemSpec = getSpecifier(itemspecifier, method, op);
310 if (itemSpec.form == SpecifierForm.CSID) {
311 itemcsid = itemSpec.value;
313 String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
314 itemcsid = getRepositoryClient(ctx).findDocCSID(null, ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
320 * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then
321 * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
322 * Resource. They then call this method on that resource.
325 public DocumentModel getDocModelForAuthorityItem(RepositoryInstance repoSession, RefName.AuthorityItem item)
326 throws Exception, DocumentNotFoundException {
330 String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
331 // Ensure we have the right context.
332 ServiceContext ctx = createServiceContext(item.inAuthority.resource);
334 // HACK - this really must be moved to the doc handler, not here. No Nuxeo specific stuff here!
335 RepositoryJavaClientImpl client = (RepositoryJavaClientImpl)getRepositoryClient(ctx);
336 String parentcsid = client.findDocCSID(repoSession, ctx, whereClause);
338 String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
339 ctx = createServiceContext(getItemServiceName());
340 DocumentWrapper<DocumentModel> docWrapper = client.findDoc(repoSession, ctx, itemWhereClause);
341 DocumentModel docModel = docWrapper.getWrappedObject();
346 @POST //FIXME: REM - 5/1/2012 - We can probably remove this method.
347 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.
349 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
350 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
351 DocumentHandler handler = createDocumentHandler(ctx);
352 String csid = getRepositoryClient(ctx).create(ctx, handler);
353 UriBuilder path = UriBuilder.fromResource(resourceClass);
354 path.path("" + csid);
355 Response response = Response.created(path.build()).build();
357 } catch (Exception e) {
358 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
362 protected String buildWhereForAuthByName(String name) {
363 return authorityCommonSchemaName
364 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
368 protected String buildWhereForAuthItemByName(String name, String parentcsid) {
369 return authorityItemCommonSchemaName
370 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
371 + "='" + name + "' AND "
372 + authorityItemCommonSchemaName + ":"
373 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
374 + "'" + parentcsid + "'";
378 * Gets the authority.
380 * @param specifier either a CSID or one of the urn forms
382 * @return the authority
387 public byte[] get( // getAuthority(
389 @PathParam("csid") String specifier) {
390 PoxPayloadOut result = null;
392 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
393 DocumentHandler handler = createDocumentHandler(ctx);
395 Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
396 if (spec.form == SpecifierForm.CSID) {
397 if (logger.isDebugEnabled()) {
398 logger.debug("getAuthority with csid=" + spec.value);
400 getRepositoryClient(ctx).get(ctx, spec.value, handler);
402 String whereClause = buildWhereForAuthByName(spec.value);
403 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
404 handler.setDocumentFilter(myFilter);
405 getRepositoryClient(ctx).get(ctx, handler);
407 result = ctx.getOutput();
409 } catch (Exception e) {
410 throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
413 if (result == null) {
414 Response response = Response.status(Response.Status.NOT_FOUND).entity(
415 "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
416 "text/plain").build();
417 throw new WebApplicationException(response);
420 return result.getBytes();
424 * Finds and populates the authority list.
428 * @return the authority list
431 @Produces("application/xml")
432 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.
434 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
435 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
436 DocumentHandler handler = createDocumentHandler(ctx);
437 DocumentFilter myFilter = handler.getDocumentFilter();
438 // Need to make the default sort order for authority items
439 // be on the displayName field
440 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
441 if (sortBy == null || sortBy.isEmpty()) {
442 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
443 + AuthorityItemJAXBSchema.DISPLAY_NAME;
444 myFilter.setOrderByClause(qualifiedDisplayNameField);
446 String nameQ = queryParams.getFirst("refName");
448 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
450 getRepositoryClient(ctx).getFiltered(ctx, handler);
451 return (AbstractCommonList) handler.getCommonPartList();
452 } catch (Exception e) {
453 throw bigReThrow(e, ServiceMessages.GET_FAILED);
461 * @param specifier the csid or id
463 * @return the multipart output
467 public byte[] updateAuthority(
468 @PathParam("csid") String specifier,
470 PoxPayloadOut result = null;
472 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
473 Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
474 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
475 DocumentHandler handler = createDocumentHandler(ctx);
477 if (spec.form == SpecifierForm.CSID) {
480 String whereClause = buildWhereForAuthByName(spec.value);
481 csid = getRepositoryClient(ctx).findDocCSID(null, ctx, whereClause);
483 getRepositoryClient(ctx).update(ctx, csid, handler);
484 result = ctx.getOutput();
485 } catch (Exception e) {
486 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
488 return result.getBytes();
494 * @param csid the csid
496 * @return the response
500 public Response deleteAuthority(@PathParam("csid") String csid) {
501 if (logger.isDebugEnabled()) {
502 logger.debug("deleteAuthority with csid=" + csid);
505 ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
506 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
507 DocumentHandler handler = createDocumentHandler(ctx);
508 getRepositoryClient(ctx).delete(ctx, csid, handler);
509 return Response.status(HttpResponseCodes.SC_OK).build();
510 } catch (Exception e) {
511 throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
515 /*************************************************************************
516 * Create an AuthorityItem - this is a sub-resource of Authority
517 * @param specifier either a CSID or one of the urn forms
518 * @return Authority item response
519 *************************************************************************/
521 @Path("{csid}/items")
522 public Response createAuthorityItem(@Context ResourceMap resourceMap, @Context UriInfo ui,
523 @PathParam("csid") String specifier, String xmlPayload) {
525 PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
526 ServiceContext ctx = createServiceContext(getItemServiceName(), input);
527 ctx.setResourceMap(resourceMap);
528 ctx.setUriInfo(ui); //Laramie
530 // Note: must have the parentShortId, to do the create.
531 CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
532 DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
533 String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
534 UriBuilder path = UriBuilder.fromResource(resourceClass);
535 path.path(parent.CSID + "/items/" + itemcsid);
536 Response response = Response.created(path.build()).build();
538 } catch (Exception e) {
539 throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
544 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
545 public byte[] getItemWorkflow(
546 @PathParam("csid") String csid,
547 @PathParam("itemcsid") String itemcsid) {
548 PoxPayloadOut result = null;
551 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
552 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
554 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
555 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
556 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
557 getRepositoryClient(ctx).get(ctx, itemcsid, handler);
558 result = ctx.getOutput();
559 } catch (Exception e) {
560 throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
562 return result.getBytes();
565 //FIXME: This method is almost identical to the method org.collectionspace.services.common.updateWorkflowWithTransition() so
566 // they should be consolidated -be DRY (don't repeat yourself).
568 @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH + "/{transition}")
569 public byte[] updateItemWorkflowWithTransition(
570 @PathParam("csid") String csid,
571 @PathParam("itemcsid") String itemcsid,
572 @PathParam("transition") String transition) {
573 PoxPayloadOut result = null;
577 // Create an empty workflow_commons input part and set it into a new "workflow" sub-resource context
578 PoxPayloadIn input = new PoxPayloadIn(WorkflowClient.SERVICE_PAYLOAD_NAME, new WorkflowCommon(),
579 WorkflowClient.SERVICE_COMMONPART_NAME);
580 MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, input);
582 // Create a service context and document handler for the parent resource.
583 ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
584 DocumentHandler parentDocHandler = this.createDocumentHandler(parentCtx);
585 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
587 // When looking for the document, we need to use the parent's workspace name -not the "workflow" workspace name
588 String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
589 ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
591 // Get the type of transition we're being asked to make and store it as a context parameter -used by the workflow document handler
592 TransitionDef transitionDef = getTransitionDef(parentCtx, transition);
593 ctx.setProperty(WorkflowClient.TRANSITION_ID, transitionDef);
595 WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
596 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
597 result = ctx.getOutput();
598 } catch (Exception e) {
599 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
602 return result.getBytes();
606 * Gets the authority item.
608 * @param parentspecifier either a CSID or one of the urn forms
609 * @param itemspecifier either a CSID or one of the urn forms
611 * @return the authority item
614 @Path("{csid}/items/{itemcsid}")
615 public byte[] getAuthorityItem(
616 @Context Request request,
618 @PathParam("csid") String parentspecifier,
619 @PathParam("itemcsid") String itemspecifier) {
620 PoxPayloadOut result = null;
622 JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
623 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
624 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
626 RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
627 ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
628 ctx.setJaxRsContext(jaxRsContext);
630 ctx.setUriInfo(ui); //ARG! must pass this or subsequent calls will not have a ui.
632 // We omit the parentShortId, only needed when doing a create...
633 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
635 Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
636 if (itemSpec.form == SpecifierForm.CSID) {
637 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
639 String itemWhereClause =
640 buildWhereForAuthItemByName(itemSpec.value, parentcsid);
641 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
642 handler.setDocumentFilter(myFilter);
643 getRepositoryClient(ctx).get(ctx, handler);
645 // TODO should we assert that the item is in the passed vocab?
646 result = ctx.getOutput();
647 } catch (Exception e) {
648 throw bigReThrow(e, ServiceMessages.GET_FAILED);
650 if (result == null) {
651 Response response = Response.status(Response.Status.NOT_FOUND).entity(
652 "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
653 "text/plain").build();
654 throw new WebApplicationException(response);
656 return result.getBytes();
660 * Most of the authority child classes will/should use this implementation. However, the Vocabulary service's item schema is
661 * different enough that it will have to override this method in it's resource class.
663 protected String getOrderByField() {
664 String result = null;
666 result = NuxeoUtils.getPrimaryElPathPropertyName(
667 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
668 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
673 protected String getPartialTermMatchField() {
674 String result = null;
676 result = NuxeoUtils.getMultiElPathPropertyName(
677 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(),
678 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
684 * Gets the authorityItem list for the specified authority
685 * If partialPerm is specified, keywords will be ignored.
687 * @param specifier either a CSID or one of the urn forms
688 * @param partialTerm if non-null, matches partial terms
689 * @param keywords if non-null, matches terms in the keyword index for items
690 * @param ui passed to include additional parameters, like pagination controls
692 * @return the authorityItem list
695 @Path("{csid}/items")
696 @Produces("application/xml")
697 public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
698 @Context UriInfo ui) {
700 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
701 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
702 String termStatus = queryParams.getFirst(SEARCH_TYPE_TERMSTATUS);
703 String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
704 String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
706 // Note that docType defaults to the ServiceName, so we're fine with that.
707 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
709 String parentcsid = PARENT_WILDCARD.equals(specifier)?null:
710 lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
712 ctx = createServiceContext(getItemServiceName(), queryParams);
714 // For the wildcard case, parentcsid is null, but docHandler will deal with this.
715 // We omit the parentShortId, only needed when doing a create...
716 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
718 DocumentFilter myFilter = handler.getDocumentFilter();
719 // Need to make the default sort order for authority items
720 // be on the displayName field
721 String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
722 if (sortBy == null || sortBy.isEmpty()) {
723 String orderByField = getOrderByField();
724 myFilter.setOrderByClause(orderByField);
727 // If we are not wildcarding the parent, add a restriction
728 if(parentcsid!=null) {
729 myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
730 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
731 + "'" + parentcsid + "'",
732 IQueryManager.SEARCH_QUALIFIER_AND);
735 if (Tools.notBlank(termStatus)) {
736 // Start with the qualified termStatus field
737 String qualifiedTermStatusField = authorityItemCommonSchemaName + ":"
738 + AuthorityItemJAXBSchema.TERM_STATUS;
739 String[] filterTerms = termStatus.trim().split("\\|");
740 String tsClause = QueryManager.createWhereClauseToFilterFromStringList(qualifiedTermStatusField, filterTerms, IQueryManager.FILTER_EXCLUDE);
741 myFilter.appendWhereClause(tsClause, IQueryManager.SEARCH_QUALIFIER_AND);
744 // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
745 // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
746 // the PT query param trumps the KW and AS query params.
747 if (partialTerm != null && !partialTerm.isEmpty()) {
748 String partialTermMatchField = getPartialTermMatchField();
749 String ptClause = QueryManager.createWhereClauseForPartialMatch(
750 partialTermMatchField, partialTerm);
751 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
752 } else if (keywords != null || advancedSearch != null) {
753 // String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
754 // myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
755 return search(ctx, handler, queryParams, keywords, advancedSearch);
757 if (logger.isDebugEnabled()) {
758 logger.debug("getAuthorityItemList filtered WHERE clause: "
759 + myFilter.getWhereClause()
760 + " and ORDER BY clause: " + myFilter.getOrderByClause());
762 getRepositoryClient(ctx).getFiltered(ctx, handler);
763 return (AbstractCommonList) handler.getCommonPartList();
764 } catch (Exception e) {
765 throw bigReThrow(e, ServiceMessages.LIST_FAILED);
770 * @return the name of the property used to specify references for items in this type of
771 * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
772 * Some types (like Vocabulary) use a separate property.
774 protected String getRefPropName() {
775 return ServiceBindingUtils.AUTH_REF_PROP;
779 * Gets the entities referencing this Authority item instance. The service type
780 * can be passed as a query param "type", and must match a configured type
781 * for the service bindings. If not set, the type defaults to
782 * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
784 * @param parentspecifier either a CSID or one of the urn forms
785 * @param itemspecifier either a CSID or one of the urn forms
788 * @return the info for the referencing objects
791 @Path("{csid}/items/{itemcsid}/refObjs")
792 @Produces("application/xml")
793 public AuthorityRefDocList getReferencingObjects(
794 @PathParam("csid") String parentspecifier,
795 @PathParam("itemcsid") String itemspecifier,
796 @Context UriInfo ui) {
797 AuthorityRefDocList authRefDocList = null;
799 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
801 String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
803 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
804 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
806 List<String> serviceTypes = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
807 if(serviceTypes == null || serviceTypes.isEmpty()) {
808 // Temporary workaround for CSPACE-4983
809 // serviceTypes = ServiceBindingUtils.getCommonServiceTypes();
810 serviceTypes = ServiceBindingUtils.getCommonProcedureServiceTypes();
813 // Note that we have to create the service context for the Items, not the main service
814 // We omit the parentShortId, only needed when doing a create...
815 AuthorityItemDocumentModelHandler<?> handler = (AuthorityItemDocumentModelHandler<?>)
816 createItemDocumentHandler(ctx, parentcsid, null);
818 authRefDocList = handler.getReferencingObjects(ctx, serviceTypes, getRefPropName(), itemcsid);
819 } catch (Exception e) {
820 throw bigReThrow(e, ServiceMessages.GET_FAILED);
822 if (authRefDocList == null) {
823 Response response = Response.status(Response.Status.NOT_FOUND).entity(
824 "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
825 "text/plain").build();
826 throw new WebApplicationException(response);
828 return authRefDocList;
832 * Gets the authority terms used in the indicated Authority item.
834 * @param parentspecifier either a CSID or one of the urn forms
835 * @param itemspecifier either a CSID or one of the urn forms
836 * @param ui passed to include additional parameters, like pagination controls
838 * @return the authority refs for the Authority item.
841 @Path("{csid}/items/{itemcsid}/authorityrefs")
842 @Produces("application/xml")
843 public AuthorityRefList getAuthorityItemAuthorityRefs(
844 @PathParam("csid") String parentspecifier,
845 @PathParam("itemcsid") String itemspecifier,
846 @Context UriInfo ui) {
847 AuthorityRefList authRefList = null;
849 // Note that we have to create the service context for the Items, not the main service
850 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
851 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
853 String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
855 ctx = createServiceContext(getItemServiceName(), queryParams);
856 // We omit the parentShortId, only needed when doing a create...
857 DocumentModelHandler handler =
858 (DocumentModelHandler)createItemDocumentHandler(ctx, parentcsid, null);
860 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
862 List<RefNameServiceUtils.AuthRefConfigInfo> authRefsInfo = RefNameServiceUtils.getConfiguredAuthorityRefs(ctx);
863 authRefList = handler.getAuthorityRefs(itemcsid, authRefsInfo);
864 } catch (Exception e) {
865 throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
871 * Update authorityItem.
873 * @param parentspecifier either a CSID or one of the urn forms
874 * @param itemspecifier either a CSID or one of the urn forms
876 * @return the multipart output
879 @Path("{csid}/items/{itemcsid}")
880 public byte[] updateAuthorityItem(
881 @Context ResourceMap resourceMap,
883 @PathParam("csid") String parentspecifier,
884 @PathParam("itemcsid") String itemspecifier,
886 PoxPayloadOut result = null;
888 PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
889 // Note that we have to create the service context for the Items, not the main service
890 //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
891 String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
893 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
894 ctx.setResourceMap(resourceMap);
895 String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
897 // We omit the parentShortId, only needed when doing a create...
898 DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
900 getRepositoryClient(ctx).update(ctx, itemcsid, handler);
901 result = ctx.getOutput();
903 } catch (Exception e) {
904 throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
906 return result.getBytes();
910 * Delete authorityItem.
912 * @param parentcsid the parentcsid
913 * @param itemcsid the itemcsid
915 * @return the response
918 @Path("{csid}/items/{itemcsid}")
919 public Response deleteAuthorityItem(
920 @PathParam("csid") String parentcsid,
921 @PathParam("itemcsid") String itemcsid) {
923 if (logger.isDebugEnabled()) {
924 logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
927 ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
928 ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
929 //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
930 // }catch (Throwable t){
931 // System.out.println("ERROR in setting up DELETE: "+t);
934 // Note that we have to create the service context for the Items, not the main service
935 ServiceContext ctx = createServiceContext(getItemServiceName());
936 DocumentHandler handler = createDocumentHandler(ctx);
937 getRepositoryClient(ctx).delete(ctx, itemcsid, handler);
938 return Response.status(HttpResponseCodes.SC_OK).build();
939 } catch (Exception e) {
940 throw bigReThrow(e, ServiceMessages.DELETE_FAILED + " itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
943 public final static String hierarchy = "hierarchy";
946 @Path("{csid}/items/{itemcsid}/" + hierarchy)
947 @Produces("application/xml")
948 public String getHierarchy(@PathParam("csid") String csid,
949 @PathParam("itemcsid") String itemcsid,
950 @Context UriInfo ui) throws Exception {
952 // 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...?
953 String calledUri = ui.getPath();
954 String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
955 ServiceContext ctx = createServiceContext(getItemServiceName());
957 String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
958 if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
959 return Hierarchy.surface(ctx, itemcsid, uri);
961 return Hierarchy.dive(ctx, itemcsid, uri);
963 } catch (Exception e) {
964 throw bigReThrow(e, "Error showing hierarchy", itemcsid);
968 public String getItemDocType() {
969 // FIXME: Proof of concept placeholder
970 // return "item-" + getServiceName();
972 return super.getDocType(getItemServiceName());
975 // FIXME: Replace this outrageous hack; a tenant with this ID may not exist
977 final String DEFAULT_TENANT_ID = "1";
978 TenantBindingConfigReaderImpl reader = ServiceMain.getInstance().getTenantBindingConfigReader();
979 ServiceBindingType sb = reader.getServiceBinding(DEFAULT_TENANT_ID, getItemServiceName());
980 docType = sb.getObject().getName();
984 String arbitraryTenantId = "";
985 ServiceBindingType sb;
986 TenantBindingConfigReaderImpl reader = ServiceMain.getInstance().getTenantBindingConfigReader();
987 // FIXME: Makes the outrageous assumption that the list of service names and associated
988 // document types is essentially identical across tenants
989 arbitraryTenantId = getArbitraryTenantId(reader);
990 if (Tools.notBlank(arbitraryTenantId)) {
991 ServiceBindingType sb = reader.getServiceBinding(arbitraryTenantId, getItemServiceName());
992 docType = sb.getObject().getName();
1000 public Map<String,StoredValuesUriTemplate> getUriTemplateMap() {
1001 // Get resource URI template from superclass
1002 Map<String,StoredValuesUriTemplate> uriTemplateMap = super.getUriTemplateMap();
1003 // Add item URI template, and return both templates in the map
1004 String itemDocType = getItemDocType();
1005 StoredValuesUriTemplate itemUriTemplate = getUriTemplate(UriTemplateFactory.ITEM);
1006 if (itemDocType == null) {
1007 return uriTemplateMap; // return map as obtained from superclass
1009 if (itemUriTemplate == null) {
1010 return uriTemplateMap; // return map as obtained from superclass
1012 uriTemplateMap.put(itemDocType, itemUriTemplate);
1013 return uriTemplateMap;