]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
2764731c50e9fc522305f16ef0ee171079bc0dbd
[tmp/jakarta-migration.git] /
1 /**
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:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
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.
23  */
24 package org.collectionspace.services.common.vocabulary;
25
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.ClientType;
32 import org.collectionspace.services.common.ResourceBase;
33 import org.collectionspace.services.common.ResourceMap;
34 import org.collectionspace.services.common.ServiceMain;
35 import org.collectionspace.services.common.ServiceMessages;
36 import org.collectionspace.services.common.XmlTools;
37 import org.collectionspace.services.common.api.RefName;
38 import org.collectionspace.services.common.api.Tools;
39 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
40 import org.collectionspace.services.common.authorityref.AuthorityRefList;
41 import org.collectionspace.services.common.context.JaxRsContext;
42 import org.collectionspace.services.common.context.MultipartServiceContext;
43 import org.collectionspace.services.common.context.MultipartServiceContextImpl;
44 import org.collectionspace.services.common.context.RemoteServiceContext;
45 import org.collectionspace.services.common.context.ServiceBindingUtils;
46 import org.collectionspace.services.common.context.ServiceContext;
47 import org.collectionspace.services.common.document.DocumentException;
48 import org.collectionspace.services.common.document.DocumentFilter;
49 import org.collectionspace.services.common.document.DocumentHandler;
50 import org.collectionspace.services.common.document.DocumentNotFoundException;
51 import org.collectionspace.services.common.document.DocumentWrapper;
52 import org.collectionspace.services.common.query.QueryManager;
53 import org.collectionspace.services.common.repository.RepositoryClient;
54 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityDocumentModelHandler;
55 import org.collectionspace.services.common.vocabulary.nuxeo.AuthorityItemDocumentModelHandler;
56 import org.collectionspace.services.common.workflow.service.nuxeo.WorkflowDocumentModelHandler;
57 import org.collectionspace.services.jaxb.AbstractCommonList;
58 import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl;
59 import org.collectionspace.services.relation.RelationResource;
60 import org.collectionspace.services.relation.RelationsCommonList;
61 import org.collectionspace.services.relation.RelationshipType;
62 import org.jboss.resteasy.util.HttpResponseCodes;
63 import org.nuxeo.ecm.core.api.DocumentModel;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 import javax.ws.rs.Consumes;
68 import javax.ws.rs.DELETE;
69 import javax.ws.rs.GET;
70 import javax.ws.rs.POST;
71 import javax.ws.rs.PUT;
72 import javax.ws.rs.Path;
73 import javax.ws.rs.PathParam;
74 import javax.ws.rs.Produces;
75 import javax.ws.rs.QueryParam;
76 import javax.ws.rs.WebApplicationException;
77 import javax.ws.rs.core.Context;
78 import javax.ws.rs.core.MultivaluedMap;
79 import javax.ws.rs.core.Request;
80 import javax.ws.rs.core.Response;
81 import javax.ws.rs.core.UriBuilder;
82 import javax.ws.rs.core.UriInfo;
83
84 import java.util.ArrayList;
85 import java.util.List;
86
87 /**
88  * The Class AuthorityResource.
89  */
90 /**
91  * @author pschmitz
92  *
93  * @param <AuthCommon>
94  * @param <AuthItemHandler>
95  */
96 /**
97  * @author pschmitz
98  *
99  * @param <AuthCommon>
100  * @param <AuthItemHandler>
101  */
102 @Consumes("application/xml")
103 @Produces("application/xml")
104 public abstract class AuthorityResource<AuthCommon, AuthItemHandler>
105         extends ResourceBase {
106
107     protected Class<AuthCommon> authCommonClass;
108     protected Class<?> resourceClass;
109     protected String authorityCommonSchemaName;
110     protected String authorityItemCommonSchemaName;
111     final static ClientType CLIENT_TYPE = ServiceMain.getInstance().getClientType();
112     final static String URN_PREFIX = "urn:cspace:";
113     final static int URN_PREFIX_LEN = URN_PREFIX.length();
114     final static String URN_PREFIX_NAME = "name(";
115     final static int URN_NAME_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_NAME.length();
116     final static String URN_PREFIX_ID = "id(";
117     final static int URN_ID_PREFIX_LEN = URN_PREFIX_LEN + URN_PREFIX_ID.length();
118     final static String FETCH_SHORT_ID = "_fetch_";
119     final Logger logger = LoggerFactory.getLogger(AuthorityResource.class);
120
121     public enum SpecifierForm {
122
123         CSID, URN_NAME
124     };
125
126     public class Specifier {
127
128         public SpecifierForm form;
129         public String value;
130
131         Specifier(SpecifierForm form, String value) {
132             this.form = form;
133             this.value = value;
134         }
135     }
136
137     protected Specifier getSpecifier(String specifierIn, String method, String op) throws WebApplicationException {
138         if (logger.isDebugEnabled()) {
139             logger.debug("getSpecifier called by: " + method + " with specifier: " + specifierIn);
140         }
141         if (specifierIn != null) {
142             if (!specifierIn.startsWith(URN_PREFIX)) {
143                 // We'll assume it is a CSID and complain if it does not match
144                 return new Specifier(SpecifierForm.CSID, specifierIn);
145             } else {
146                 if (specifierIn.startsWith(URN_PREFIX_NAME, URN_PREFIX_LEN)) {
147                     int closeParen = specifierIn.indexOf(')', URN_NAME_PREFIX_LEN);
148                     if (closeParen >= 0) {
149                         return new Specifier(SpecifierForm.URN_NAME,
150                                 specifierIn.substring(URN_NAME_PREFIX_LEN, closeParen));
151                     }
152                 } else if (specifierIn.startsWith(URN_PREFIX_ID, URN_PREFIX_LEN)) {
153                     int closeParen = specifierIn.indexOf(')', URN_ID_PREFIX_LEN);
154                     if (closeParen >= 0) {
155                         return new Specifier(SpecifierForm.CSID,
156                                 specifierIn.substring(URN_ID_PREFIX_LEN, closeParen));
157                     }
158                 }
159             }
160         }
161         logger.error(method + ": bad or missing specifier!");
162         Response response = Response.status(Response.Status.BAD_REQUEST).entity(
163                 op + " failed on bad or missing Authority specifier").type(
164                 "text/plain").build();
165         throw new WebApplicationException(response);
166     }
167
168     /**
169      * Instantiates a new Authority resource.
170      */
171     public AuthorityResource(Class<AuthCommon> authCommonClass, Class<?> resourceClass,
172             String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
173         this.authCommonClass = authCommonClass;
174         this.resourceClass = resourceClass;
175         this.authorityCommonSchemaName = authorityCommonSchemaName;
176         this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
177     }
178
179     public abstract String getItemServiceName();
180
181     @Override
182     protected String getVersionString() {
183         return "$LastChangedRevision: 2617 $";
184     }
185
186     @Override
187     public Class<AuthCommon> getCommonPartClass() {
188         return authCommonClass;
189     }
190
191     /**
192      * Creates the item document handler.
193      * 
194      * @param ctx the ctx
195      * @param inAuthority the in vocabulary
196      * 
197      * @return the document handler
198      * 
199      * @throws Exception the exception
200      */
201     protected DocumentHandler createItemDocumentHandler(
202             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
203             String inAuthority, String parentShortIdentifier)
204             throws Exception {
205         String authorityRefNameBase;
206         AuthorityItemDocumentModelHandler<?> docHandler;
207
208         if (parentShortIdentifier == null) {
209             authorityRefNameBase = null;
210         } else {
211             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx =
212                     createServiceContext(getServiceName());
213             if (parentShortIdentifier.equals(FETCH_SHORT_ID)) {
214                 // Get from parent document
215                 parentShortIdentifier = getAuthShortIdentifier(parentCtx, inAuthority);
216             }
217             authorityRefNameBase = buildAuthorityRefNameBase(parentCtx, parentShortIdentifier);
218         }
219
220         docHandler = (AuthorityItemDocumentModelHandler<?>) createDocumentHandler(ctx,
221                 ctx.getCommonPartLabel(getItemServiceName()),
222                 authCommonClass);
223         docHandler.setInAuthority(inAuthority);
224         docHandler.setAuthorityRefNameBase(authorityRefNameBase);
225
226         return docHandler;
227     }
228
229     public String getAuthShortIdentifier(
230             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String authCSID)
231             throws DocumentNotFoundException, DocumentException {
232         String shortIdentifier = null;
233         try {
234             DocumentWrapper<DocumentModel> wrapDoc = getRepositoryClient(ctx).getDocFromCsid(ctx, authCSID);
235             AuthorityDocumentModelHandler<?> handler =
236                     (AuthorityDocumentModelHandler<?>) createDocumentHandler(ctx);
237             shortIdentifier = handler.getShortIdentifier(wrapDoc, authorityCommonSchemaName);
238         } catch (Exception e) {
239             if (logger.isDebugEnabled()) {
240                 logger.debug("Caught exception ", e);
241             }
242             throw new DocumentException(e);
243         }
244         return shortIdentifier;
245     }
246
247     protected String buildAuthorityRefNameBase(
248             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String shortIdentifier) {
249         RefName.Authority authority = RefName.buildAuthority(ctx.getTenantName(),
250                 ctx.getServiceName(), shortIdentifier, null);
251         return authority.toString();
252     }
253
254     public static class CsidAndShortIdentifier {
255
256         String CSID;
257         String shortIdentifier;
258     }
259
260     public String lookupParentCSID(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
261             throws Exception {
262         CsidAndShortIdentifier tempResult = lookupParentCSIDAndShortIdentifer(parentspecifier, method, op, queryParams);
263         return tempResult.CSID;
264     }
265
266     public CsidAndShortIdentifier lookupParentCSIDAndShortIdentifer(String parentspecifier, String method, String op, MultivaluedMap<String, String> queryParams)
267             throws Exception {
268         CsidAndShortIdentifier result = new CsidAndShortIdentifier();
269         Specifier parentSpec = getSpecifier(parentspecifier, method, op);
270         // Note that we have to create the service context for the Items, not the main service
271         String parentcsid;
272         String parentShortIdentifier;
273         if (parentSpec.form == SpecifierForm.CSID) {
274             parentShortIdentifier = null;
275             parentcsid = parentSpec.value;
276             // Uncomment when app layer is ready to integrate
277             // Uncommented since refNames are currently only generated if not present - ADR CSPACE-3178
278             parentShortIdentifier = FETCH_SHORT_ID;
279         } else {
280             parentShortIdentifier = parentSpec.value;
281             String whereClause = buildWhereForAuthByName(parentSpec.value);
282             ServiceContext ctx = createServiceContext(getServiceName(), queryParams);
283             parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause); //FIXME: REM - If the parent has been soft-deleted, should we be looking for the item?
284         }
285         result.CSID = parentcsid;
286         result.shortIdentifier = parentShortIdentifier;
287         return result;
288     }
289
290     public String lookupItemCSID(String itemspecifier, String parentcsid, String method, String op, ServiceContext ctx)
291             throws DocumentException {
292         String itemcsid;
293         Specifier itemSpec = getSpecifier(itemspecifier, method, op);
294         if (itemSpec.form == SpecifierForm.CSID) {
295             itemcsid = itemSpec.value;
296         } else {
297             String itemWhereClause = buildWhereForAuthItemByName(itemSpec.value, parentcsid);
298             itemcsid = getRepositoryClient(ctx).findDocCSID(ctx, itemWhereClause); //FIXME: REM - Should we be looking for the 'wf_deleted' query param and filtering on it?
299         }
300         return itemcsid;
301     }
302
303     /*
304      * Generally, callers will first call RefName.AuthorityItem.parse with a refName, and then 
305      * use the returned item.inAuthority.resource and a resourceMap to get a service-specific
306      * Resource. They then call this method on that resource.
307      */
308     @Override
309         public DocumentModel getDocModelForAuthorityItem(RefName.AuthorityItem item) 
310                         throws Exception, DocumentNotFoundException {
311         if(item == null) {
312                 return null;
313         }
314         String whereClause = buildWhereForAuthByName(item.getParentShortIdentifier());
315         // Ensure we have the right context.
316         ServiceContext ctx = createServiceContext(item.inAuthority.resource);
317         
318         String parentcsid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
319
320         String itemWhereClause = buildWhereForAuthItemByName(item.getShortIdentifier(), parentcsid);
321         ctx = createServiceContext(getItemServiceName());
322         DocumentWrapper<DocumentModel> docWrapper = getRepositoryClient(ctx).findDoc(ctx, itemWhereClause);
323         DocumentModel docModel = docWrapper.getWrappedObject();
324         return docModel;
325     }
326
327
328     @POST
329     public Response createAuthority(String xmlPayload) {
330         try {
331             PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
332             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(input);
333             DocumentHandler handler = createDocumentHandler(ctx);
334             String csid = getRepositoryClient(ctx).create(ctx, handler);
335             UriBuilder path = UriBuilder.fromResource(resourceClass);
336             path.path("" + csid);
337             Response response = Response.created(path.build()).build();
338             return response;
339         } catch (Exception e) {
340             throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
341         }
342     }
343
344     protected String buildWhereForAuthByName(String name) {
345         return authorityCommonSchemaName
346                 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
347                 + "='" + name + "'";
348     }
349
350     protected String buildWhereForAuthItemByName(String name, String parentcsid) {
351         return authorityItemCommonSchemaName
352                 + ":" + AuthorityItemJAXBSchema.SHORT_IDENTIFIER
353                 + "='" + name + "' AND "
354                 + authorityItemCommonSchemaName + ":"
355                 + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
356                 + "'" + parentcsid + "'";
357     }
358
359     /**
360      * Gets the authority.
361      * 
362      * @param specifier either a CSID or one of the urn forms
363      * 
364      * @return the authority
365      */
366     @GET
367     @Path("{csid}")
368     @Override
369     public byte[] get( // getAuthority(
370             @Context UriInfo ui,
371             @PathParam("csid") String specifier) {
372         PoxPayloadOut result = null;
373         try {
374             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(ui);
375             DocumentHandler handler = createDocumentHandler(ctx);
376
377             Specifier spec = getSpecifier(specifier, "getAuthority", "GET");
378             if (spec.form == SpecifierForm.CSID) {
379                 if (logger.isDebugEnabled()) {
380                     logger.debug("getAuthority with csid=" + spec.value);
381                 }
382                 getRepositoryClient(ctx).get(ctx, spec.value, handler);
383             } else {
384                 String whereClause = buildWhereForAuthByName(spec.value);
385                 DocumentFilter myFilter = new DocumentFilter(whereClause, 0, 1);
386                 handler.setDocumentFilter(myFilter);
387                 getRepositoryClient(ctx).get(ctx, handler);
388             }
389             result = ctx.getOutput();
390
391         } catch (Exception e) {
392             throw bigReThrow(e, ServiceMessages.GET_FAILED, specifier);
393         }
394
395         if (result == null) {
396             Response response = Response.status(Response.Status.NOT_FOUND).entity(
397                     "Get failed, the requested Authority specifier:" + specifier + ": was not found.").type(
398                     "text/plain").build();
399             throw new WebApplicationException(response);
400         }
401
402         return result.getBytes();
403     }
404
405     /**
406      * Finds and populates the authority list.
407      * 
408      * @param ui the ui
409      * 
410      * @return the authority list
411      */
412     @GET
413     @Produces("application/xml")
414     public AbstractCommonList getAuthorityList(@Context UriInfo ui) {
415         try {
416             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
417             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(queryParams);
418             DocumentHandler handler = createDocumentHandler(ctx);
419             DocumentFilter myFilter = handler.getDocumentFilter();
420             // Need to make the default sort order for authority items
421             // be on the displayName field
422             String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
423             if (sortBy == null || sortBy.isEmpty()) {
424                 String qualifiedDisplayNameField = authorityCommonSchemaName + ":"
425                         + AuthorityItemJAXBSchema.DISPLAY_NAME;
426                 myFilter.setOrderByClause(qualifiedDisplayNameField);
427             }
428             String nameQ = queryParams.getFirst("refName");
429             if (nameQ != null) {
430                 myFilter.setWhereClause(authorityCommonSchemaName + ":refName='" + nameQ + "'");
431             }
432             getRepositoryClient(ctx).getFiltered(ctx, handler);
433             return (AbstractCommonList) handler.getCommonPartList();
434         } catch (Exception e) {
435             throw bigReThrow(e, ServiceMessages.GET_FAILED);
436         }
437     }
438
439     /**
440      * Update authority.
441      *
442      * @param specifier the csid or id
443      *
444      * @return the multipart output
445      */
446     @PUT
447     @Path("{csid}")
448     public byte[] updateAuthority(
449             @PathParam("csid") String specifier,
450             String xmlPayload) {
451         PoxPayloadOut result = null;
452         try {
453             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
454             Specifier spec = getSpecifier(specifier, "updateAuthority", "UPDATE");
455             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(theUpdate);
456             DocumentHandler handler = createDocumentHandler(ctx);
457             String csid;
458             if (spec.form == SpecifierForm.CSID) {
459                 csid = spec.value;
460             } else {
461                 String whereClause = buildWhereForAuthByName(spec.value);
462                 csid = getRepositoryClient(ctx).findDocCSID(ctx, whereClause);
463             }
464             getRepositoryClient(ctx).update(ctx, csid, handler);
465             result = ctx.getOutput();
466         } catch (Exception e) {
467             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
468         }
469         return result.getBytes();
470     }
471
472     /**
473      * Delete authority.
474      * 
475      * @param csid the csid
476      * 
477      * @return the response
478      */
479     @DELETE
480     @Path("{csid}")
481     public Response deleteAuthority(@PathParam("csid") String csid) {
482         if (logger.isDebugEnabled()) {
483             logger.debug("deleteAuthority with csid=" + csid);
484         }
485         try {
486             ensureCSID(csid, ServiceMessages.DELETE_FAILED, "Authority.csid");
487             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
488             getRepositoryClient(ctx).delete(ctx, csid);
489             return Response.status(HttpResponseCodes.SC_OK).build();
490         } catch (Exception e) {
491             throw bigReThrow(e, ServiceMessages.DELETE_FAILED, csid);
492         }
493     }
494
495     /*************************************************************************
496      * Create an AuthorityItem - this is a sub-resource of Authority
497      * @param specifier either a CSID or one of the urn forms
498      * @return Authority item response
499      *************************************************************************/
500     @POST
501     @Path("{csid}/items")
502     public Response createAuthorityItem(@Context ResourceMap resourceMap, @Context UriInfo ui, 
503                 @PathParam("csid") String specifier, String xmlPayload) {
504         try {
505             PoxPayloadIn input = new PoxPayloadIn(xmlPayload);
506             ServiceContext ctx = createServiceContext(getItemServiceName(), input);
507             ctx.setResourceMap(resourceMap);
508             ctx.setUriInfo(ui);    //Laramie
509
510             // Note: must have the parentShortId, to do the create.
511             CsidAndShortIdentifier parent = lookupParentCSIDAndShortIdentifer(specifier, "createAuthorityItem", "CREATE_ITEM", null);
512             DocumentHandler handler = createItemDocumentHandler(ctx, parent.CSID, parent.shortIdentifier);
513             String itemcsid = getRepositoryClient(ctx).create(ctx, handler);
514             UriBuilder path = UriBuilder.fromResource(resourceClass);
515             path.path(parent.CSID + "/items/" + itemcsid);
516             Response response = Response.created(path.build()).build();
517             return response;
518         } catch (Exception e) {
519             throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
520         }
521     }
522
523     @GET
524     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
525     public byte[] getItemWorkflow(
526             @PathParam("csid") String csid,
527             @PathParam("itemcsid") String itemcsid) {
528         PoxPayloadOut result = null;
529
530         try {
531             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
532             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
533
534             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME);
535             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
536             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
537             getRepositoryClient(ctx).get(ctx, itemcsid, handler);
538             result = ctx.getOutput();
539         } catch (Exception e) {
540             throw bigReThrow(e, ServiceMessages.READ_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
541         }
542         return result.getBytes();
543     }
544
545     @PUT
546     @Path("{csid}/items/{itemcsid}" + WorkflowClient.SERVICE_PATH)
547     public byte[] updateWorkflow(
548             @PathParam("csid") String csid,
549             @PathParam("itemcsid") String itemcsid,
550             String xmlPayload) {
551         PoxPayloadOut result = null;
552         try {
553             ServiceContext<PoxPayloadIn, PoxPayloadOut> parentCtx = createServiceContext(getItemServiceName());
554             String parentWorkspaceName = parentCtx.getRepositoryWorkspaceName();
555
556             PoxPayloadIn workflowUpdate = new PoxPayloadIn(xmlPayload);
557             MultipartServiceContext ctx = (MultipartServiceContext) createServiceContext(WorkflowClient.SERVICE_NAME, workflowUpdate);
558             WorkflowDocumentModelHandler handler = createWorkflowDocumentHandler(ctx);
559             ctx.setRespositoryWorkspaceName(parentWorkspaceName); //find the document in the parent's workspace
560             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
561             result = ctx.getOutput();
562         } catch (Exception e) {
563             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED + WorkflowClient.SERVICE_PAYLOAD_NAME, csid);
564         }
565         return result.getBytes();
566     }
567
568     /**
569      * Gets the authority item.
570      * 
571      * @param parentspecifier either a CSID or one of the urn forms
572      * @param itemspecifier either a CSID or one of the urn forms
573      * 
574      * @return the authority item
575      */
576     @GET
577     @Path("{csid}/items/{itemcsid}")
578     public byte[] getAuthorityItem(
579             @Context Request request,
580             @Context UriInfo ui,
581             @PathParam("csid") String parentspecifier,
582             @PathParam("itemcsid") String itemspecifier) {
583         PoxPayloadOut result = null;
584         try {
585             JaxRsContext jaxRsContext = new JaxRsContext(request, ui);
586             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
587             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItem(parent)", "GET_ITEM", queryParams);
588
589             RemoteServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
590             ctx = (RemoteServiceContext) createServiceContext(getItemServiceName(), queryParams);
591             ctx.setJaxRsContext(jaxRsContext);
592
593             ctx.setUriInfo(ui); //ARG!   must pass this or subsequent calls will not have a ui.
594
595             // We omit the parentShortId, only needed when doing a create...
596             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
597
598             Specifier itemSpec = getSpecifier(itemspecifier, "getAuthorityItem(item)", "GET_ITEM");
599             if (itemSpec.form == SpecifierForm.CSID) {
600                 getRepositoryClient(ctx).get(ctx, itemSpec.value, handler);
601             } else {
602                 String itemWhereClause =
603                         buildWhereForAuthItemByName(itemSpec.value, parentcsid);
604                 DocumentFilter myFilter = new DocumentFilter(itemWhereClause, 0, 1);
605                 handler.setDocumentFilter(myFilter);
606                 getRepositoryClient(ctx).get(ctx, handler);
607             }
608             // TODO should we assert that the item is in the passed vocab?
609             result = ctx.getOutput();
610         } catch (Exception e) {
611             throw bigReThrow(e, ServiceMessages.GET_FAILED);
612         }
613         if (result == null) {
614             Response response = Response.status(Response.Status.NOT_FOUND).entity(
615                     "Get failed, the requested AuthorityItem specifier:" + itemspecifier + ": was not found.").type(
616                     "text/plain").build();
617             throw new WebApplicationException(response);
618         }
619         return result.getBytes();
620     }
621
622     /**
623      * Gets the authorityItem list for the specified authority
624      * If partialPerm is specified, keywords will be ignored.
625      * 
626      * @param specifier either a CSID or one of the urn forms
627      * @param partialTerm if non-null, matches partial terms
628      * @param keywords if non-null, matches terms in the keyword index for items
629      * @param ui passed to include additional parameters, like pagination controls
630      * 
631      * @return the authorityItem list
632      */
633     @GET
634     @Path("{csid}/items")
635     @Produces("application/xml")
636     public AbstractCommonList getAuthorityItemList(@PathParam("csid") String specifier,
637             @Context UriInfo ui) {
638         try {
639             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
640             String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
641             String keywords = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_KW);
642             String advancedSearch = queryParams.getFirst(IQueryManager.SEARCH_TYPE_KEYWORDS_AS);
643
644             String qualifiedDisplayNameField = authorityItemCommonSchemaName + ":"
645                     + AuthorityItemJAXBSchema.DISPLAY_NAME;
646
647             // Note that docType defaults to the ServiceName, so we're fine with that.
648             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
649
650             String parentcsid = lookupParentCSID(specifier, "getAuthorityItemList", "LIST", queryParams);
651
652             ctx = createServiceContext(getItemServiceName(), queryParams);
653             // We omit the parentShortId, only needed when doing a create...
654             DocumentHandler handler = createItemDocumentHandler(ctx,
655                     parentcsid, null);
656             DocumentFilter myFilter = handler.getDocumentFilter();
657             // Need to make the default sort order for authority items
658             // be on the displayName field
659             String sortBy = queryParams.getFirst(IClientQueryParams.SORT_BY_PARAM);
660             if (sortBy == null || sortBy.isEmpty()) {
661                 myFilter.setOrderByClause(qualifiedDisplayNameField);
662             }
663
664             myFilter.appendWhereClause(authorityItemCommonSchemaName + ":"
665                     + AuthorityItemJAXBSchema.IN_AUTHORITY + "="
666                     + "'" + parentcsid + "'",
667                     IQueryManager.SEARCH_QUALIFIER_AND);
668
669             // AND vocabularyitems_common:displayName LIKE '%partialTerm%'
670             // NOTE: Partial terms searches are mutually exclusive to keyword and advanced-search, but
671             // the PT query param trumps the KW and AS query params.
672             if (partialTerm != null && !partialTerm.isEmpty()) {
673                 String ptClause = QueryManager.createWhereClauseForPartialMatch(
674                         qualifiedDisplayNameField, partialTerm);
675                 myFilter.appendWhereClause(ptClause, IQueryManager.SEARCH_QUALIFIER_AND);
676             } else if (keywords != null || advancedSearch != null) {
677 //                              String kwdClause = QueryManager.createWhereClauseFromKeywords(keywords);
678 //                              myFilter.appendWhereClause(kwdClause, IQueryManager.SEARCH_QUALIFIER_AND);
679                 return search(ctx, handler, queryParams, keywords, advancedSearch);
680             }
681             if (logger.isDebugEnabled()) {
682                 logger.debug("getAuthorityItemList filtered WHERE clause: "
683                         + myFilter.getWhereClause());
684             }
685             getRepositoryClient(ctx).getFiltered(ctx, handler);
686             return (AbstractCommonList) handler.getCommonPartList();
687         } catch (Exception e) {
688             throw bigReThrow(e, ServiceMessages.LIST_FAILED);
689         }
690     }
691
692     /**
693      * @return the name of the property used to specify references for items in this type of
694      * authority. For most authorities, it is ServiceBindingUtils.AUTH_REF_PROP ("authRef").
695      * Some types (like Vocabulary) use a separate property.
696      */
697     protected String getRefPropName() {
698         return ServiceBindingUtils.AUTH_REF_PROP;
699     }
700     
701     /**
702      * Gets the entities referencing this Authority item instance. The service type
703      * can be passed as a query param "type", and must match a configured type
704      * for the service bindings. If not set, the type defaults to
705      * ServiceBindingUtils.SERVICE_TYPE_PROCEDURE.
706      *
707      * @param parentspecifier either a CSID or one of the urn forms
708      * @param itemspecifier either a CSID or one of the urn forms
709      * @param ui the ui
710      * 
711      * @return the info for the referencing objects
712      */
713     @GET
714     @Path("{csid}/items/{itemcsid}/refObjs")
715     @Produces("application/xml")
716     public AuthorityRefDocList getReferencingObjects(
717             @PathParam("csid") String parentspecifier,
718             @PathParam("itemcsid") String itemspecifier,
719             @Context UriInfo ui) {
720         AuthorityRefDocList authRefDocList = null;
721         try {
722             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
723
724             String parentcsid = lookupParentCSID(parentspecifier, "getReferencingObjects(parent)", "GET_ITEM_REF_OBJS", queryParams);
725
726             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), queryParams);
727             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getReferencingObjects(item)", "GET_ITEM_REF_OBJS", ctx);
728
729             // Note that we have to create the service context for the Items, not the main service
730             // We omit the parentShortId, only needed when doing a create...
731             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
732             RepositoryClient repoClient = getRepositoryClient(ctx);
733             DocumentFilter myFilter = handler.getDocumentFilter();
734             String serviceType = ServiceBindingUtils.SERVICE_TYPE_PROCEDURE;
735             List<String> list = queryParams.remove(ServiceBindingUtils.SERVICE_TYPE_PROP);
736             if (list != null) {
737                 serviceType = list.get(0);
738             }
739             DocumentWrapper<DocumentModel> docWrapper = repoClient.getDoc(ctx, itemcsid);
740             DocumentModel docModel = docWrapper.getWrappedObject();
741             String refName = (String) docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
742
743             authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(ctx,
744                     repoClient,
745                     serviceType,
746                     refName,
747                     getRefPropName(),
748                     myFilter.getPageSize(), myFilter.getStartPage(), true /*computeTotal*/);
749         } catch (Exception e) {
750             throw bigReThrow(e, ServiceMessages.GET_FAILED);
751         }
752         if (authRefDocList == null) {
753             Response response = Response.status(Response.Status.NOT_FOUND).entity(
754                     "Get failed, the requested Item CSID:" + itemspecifier + ": was not found.").type(
755                     "text/plain").build();
756             throw new WebApplicationException(response);
757         }
758         return authRefDocList;
759     }
760
761     /**
762      * Gets the authority terms used in the indicated Authority item.
763      *
764      * @param parentspecifier either a CSID or one of the urn forms
765      * @param itemspecifier either a CSID or one of the urn forms
766      * @param ui passed to include additional parameters, like pagination controls
767      *
768      * @return the authority refs for the Authority item.
769      */
770     @GET
771     @Path("{csid}/items/{itemcsid}/authorityrefs")
772     @Produces("application/xml")
773     public AuthorityRefList getAuthorityItemAuthorityRefs(
774             @PathParam("csid") String parentspecifier,
775             @PathParam("itemcsid") String itemspecifier,
776             @Context UriInfo ui) {
777         AuthorityRefList authRefList = null;
778         try {
779             // Note that we have to create the service context for the Items, not the main service
780             MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
781             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
782
783             String parentcsid = lookupParentCSID(parentspecifier, "getAuthorityItemAuthRefs(parent)", "GET_ITEM_AUTH_REFS", queryParams);
784
785             ctx = createServiceContext(getItemServiceName(), queryParams);
786             // We omit the parentShortId, only needed when doing a create...
787             RemoteDocumentModelHandlerImpl handler =
788                     (RemoteDocumentModelHandlerImpl) createItemDocumentHandler(ctx, parentcsid, null);
789
790             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "getAuthorityItemAuthRefs(item)", "GET_ITEM_AUTH_REFS", ctx);
791
792             DocumentWrapper<DocumentModel> docWrapper = getRepositoryClient(ctx).getDoc(ctx, itemcsid);
793             List<String> authRefFields =
794                     ((MultipartServiceContextImpl) ctx).getCommonPartPropertyValues(
795                     ServiceBindingUtils.AUTH_REF_PROP, ServiceBindingUtils.QUALIFIED_PROP_NAMES);
796             authRefList = handler.getAuthorityRefs(docWrapper, authRefFields);
797         } catch (Exception e) {
798             throw bigReThrow(e, ServiceMessages.GET_FAILED + " parentspecifier: " + parentspecifier + " itemspecifier:" + itemspecifier);
799         }
800         return authRefList;
801     }
802
803     /**
804      * Update authorityItem.
805      * 
806      * @param parentspecifier either a CSID or one of the urn forms
807      * @param itemspecifier either a CSID or one of the urn forms
808      *
809      * @return the multipart output
810      */
811     @PUT
812     @Path("{csid}/items/{itemcsid}")
813     public byte[] updateAuthorityItem(
814                 @Context ResourceMap resourceMap, 
815             @Context UriInfo ui,
816             @PathParam("csid") String parentspecifier,
817             @PathParam("itemcsid") String itemspecifier,
818             String xmlPayload) {
819         PoxPayloadOut result = null;
820         try {
821             PoxPayloadIn theUpdate = new PoxPayloadIn(xmlPayload);
822             // Note that we have to create the service context for the Items, not the main service
823             //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
824             String parentcsid = lookupParentCSID(parentspecifier, "updateAuthorityItem(parent)", "UPDATE_ITEM", null);
825
826             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(getItemServiceName(), theUpdate);
827             ctx.setResourceMap(resourceMap);
828             String itemcsid = lookupItemCSID(itemspecifier, parentcsid, "updateAuthorityItem(item)", "UPDATE_ITEM", ctx);
829
830             // We omit the parentShortId, only needed when doing a create...
831             DocumentHandler handler = createItemDocumentHandler(ctx, parentcsid, null);
832             ctx.setUriInfo(ui);
833             getRepositoryClient(ctx).update(ctx, itemcsid, handler);
834             result = ctx.getOutput();
835
836         } catch (Exception e) {
837             throw bigReThrow(e, ServiceMessages.UPDATE_FAILED);
838         }
839         return result.getBytes();
840     }
841
842     /**
843      * Delete authorityItem.
844      * 
845      * @param parentcsid the parentcsid
846      * @param itemcsid the itemcsid
847      * 
848      * @return the response
849      */
850     @DELETE
851     @Path("{csid}/items/{itemcsid}")
852     public Response deleteAuthorityItem(
853             @PathParam("csid") String parentcsid,
854             @PathParam("itemcsid") String itemcsid) {
855         //try{
856         if (logger.isDebugEnabled()) {
857             logger.debug("deleteAuthorityItem with parentcsid=" + parentcsid + " and itemcsid=" + itemcsid);
858         }
859         try {
860             ensureCSID(parentcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.parentcsid");
861             ensureCSID(itemcsid, ServiceMessages.DELETE_FAILED, "AuthorityItem.itemcsid");
862             //Laramie, removing this catch, since it will surely fail below, since itemcsid or parentcsid will be null.
863             // }catch (Throwable t){
864             //    System.out.println("ERROR in setting up DELETE: "+t);
865             // }
866             // try {
867             // Note that we have to create the service context for the Items, not the main service
868             ServiceContext ctx = createServiceContext(getItemServiceName());
869             getRepositoryClient(ctx).delete(ctx, itemcsid);
870             return Response.status(HttpResponseCodes.SC_OK).build();
871         } catch (Exception e) {
872             throw bigReThrow(e, ServiceMessages.DELETE_FAILED + "  itemcsid: " + itemcsid + " parentcsid:" + parentcsid);
873         }
874     }
875     public final static String hierarchy = "hierarchy";
876
877     @GET
878     @Path("{csid}/items/{itemcsid}/" + hierarchy)
879     @Produces("application/xml")
880     public String getHierarchy(@PathParam("csid") String csid,
881             @PathParam("itemcsid") String itemcsid,
882             @Context UriInfo ui) throws Exception {
883         try {
884             // 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...?
885             String calledUri = ui.getPath();
886             String uri = "/" + calledUri.substring(0, (calledUri.length() - ("/" + hierarchy).length()));
887             ServiceContext ctx = createServiceContext(getItemServiceName());
888             ctx.setUriInfo(ui);
889             String direction = ui.getQueryParameters().getFirst(Hierarchy.directionQP);
890             if (Tools.notBlank(direction) && Hierarchy.direction_parents.equals(direction)) {
891                 return Hierarchy.surface(ctx, itemcsid, uri);
892             } else {
893                 return Hierarchy.dive(ctx, itemcsid, uri);
894             }
895         } catch (Exception e) {
896             throw bigReThrow(e, "Error showing hierarchy", itemcsid);
897         }
898     }
899 }