]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
c2eb57e8bef7cf2c299dd50765b0f2e9a6062091
[tmp/jakarta-migration.git] /
1 /**     
2  * CitationAuthorityClientUtils.java
3  *
4  * {Purpose of This Class}
5  *
6  * {Other Notes Relating to This Class (Optional)}
7  *
8  * $LastChangedBy: $
9  * $LastChangedRevision: $
10  * $LastChangedDate: $
11  *
12  * This document is a part of the source code and related artifacts
13  * for CollectionSpace, an open source collections management system
14  * for museums and related institutions:
15  *
16  * http://www.collectionspace.org
17  * http://wiki.collectionspace.org
18  *
19  * Copyright © 2009 {Contributing Institution}
20  *
21  * Licensed under the Educational Community License (ECL), Version 2.0.
22  * You may not use this file except in compliance with this License.
23  *
24  * You may obtain a copy of the ECL 2.0 License at
25  * https://source.collectionspace.org/collection-space/LICENSE.txt
26  */
27 package org.collectionspace.services.client;
28
29 import java.util.*;
30
31 import javax.ws.rs.core.MediaType;
32 import javax.ws.rs.core.MultivaluedMap;
33 import javax.ws.rs.core.Response;
34
35 import org.collectionspace.services.CitationJAXBSchema;
36 import org.collectionspace.services.client.test.ServiceRequestType;
37 import org.collectionspace.services.common.api.Tools;
38 import org.collectionspace.services.citation.CitationTermGroup;
39 import org.collectionspace.services.citation.CitationTermGroupList;
40 import org.collectionspace.services.citation.CitationsCommon;
41 import org.collectionspace.services.citation.CitationauthoritiesCommon;
42 import org.jboss.resteasy.client.ClientResponse;
43 //import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.collectionspace.services.citation.StructuredDateGroup;
47
48 /**
49  * The Class CitationAuthorityClientUtils.
50  */
51 public class CitationAuthorityClientUtils {
52     
53     /** The Constant logger. */
54     private static final Logger logger =
55         LoggerFactory.getLogger(CitationAuthorityClientUtils.class);
56         private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
57
58     /**
59      * @param csid the id of the CitationAuthority
60      * @param client if null, creates a new client
61      * @return
62      */
63     public static String getAuthorityRefName(String csid, CitationAuthorityClient client){
64         if (client == null) {
65                 client = new CitationAuthorityClient();
66         }
67         ClientResponse<String> res = client.read(csid);
68         try {
69                 int statusCode = res.getStatus();
70                 if(!READ_REQ.isValidStatusCode(statusCode)
71                         ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
72                         throw new RuntimeException("Invalid status code returned: "+statusCode);
73                 }
74                 //FIXME: remove the following try catch once Aron fixes signatures
75                 try {
76                     PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
77                     CitationauthoritiesCommon citationAuthority = 
78                         (CitationauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
79                             client.getCommonPartName(), CitationauthoritiesCommon.class);
80                         if(citationAuthority == null) {
81                                 throw new RuntimeException("Null citationAuthority returned from service.");
82                         }
83                     return citationAuthority.getRefName();
84                 } catch (Exception e) {
85                     throw new RuntimeException(e);
86                 }
87         } finally {
88                 res.releaseConnection();
89         }
90     }
91
92     /**
93      * @param csid the id of the CitationAuthority
94      * @param client if null, creates a new client
95      * @return
96      */
97     public static String getCitationRefName(String inAuthority, String csid, CitationAuthorityClient client){
98         if ( client == null) {
99                 client = new CitationAuthorityClient();
100         }
101         ClientResponse<String> res = client.readItem(inAuthority, csid);
102         try {
103                 int statusCode = res.getStatus();
104                 if(!READ_REQ.isValidStatusCode(statusCode)
105                                 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
106                         throw new RuntimeException("Invalid status code returned: "+statusCode);
107                 }
108                 //FIXME: remove the following try catch once Aron fixes signatures
109                 try {
110                     PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
111                     CitationsCommon citation = 
112                         (CitationsCommon) CollectionSpaceClientUtils.extractPart(input,
113                             client.getItemCommonPartName(), CitationsCommon.class);
114                         if (citation == null) {
115                                 throw new RuntimeException("Null citation returned from service.");
116                         }
117                     return citation.getRefName();
118                 } catch (Exception e) {
119                     throw new RuntimeException(e);
120                 }
121         } finally {
122                 res.releaseConnection();
123         }
124     }
125
126     /**
127      * Creates the citation authority instance.
128      *
129      * @param displayName the display name
130      * @param shortIdentifier the short Id 
131      * @param headerLabel the header label
132      * @return the multipart output
133      */
134     public static PoxPayloadOut createCitationAuthorityInstance(
135                 String displayName, String shortIdentifier, String headerLabel ) {
136         CitationauthoritiesCommon citationAuthority = new CitationauthoritiesCommon();
137         citationAuthority.setDisplayName(displayName);
138         citationAuthority.setShortIdentifier(shortIdentifier);
139         //String refName = createCitationAuthRefName(shortIdentifier, displayName);
140         //citationAuthority.setRefName(refName);
141         citationAuthority.setVocabType("CitationAuthority");
142         PoxPayloadOut multipart = new PoxPayloadOut(CitationAuthorityClient.SERVICE_PAYLOAD_NAME);
143         PayloadOutputPart commonPart = multipart.addPart(citationAuthority, MediaType.APPLICATION_XML_TYPE);
144         commonPart.setLabel(headerLabel);
145
146         if(logger.isDebugEnabled()){
147                 logger.debug("to be created, citationAuthority common ", 
148                                         citationAuthority, CitationauthoritiesCommon.class);
149         }
150
151         return multipart;
152     }
153
154     /**
155      * Creates a citation instance.
156      *
157      * @param inAuthority the owning authority
158      * @param citationAuthRefName the owning Authority ref name
159      * @param citationInfo the citation info
160      * @param headerLabel the header label
161      * @return the multipart output
162      */
163     public static PoxPayloadOut createCitationInstance(String inAuthority,
164                 String citationAuthRefName,
165                 Map<String, String> citationInfo,
166                 List<CitationTermGroup> terms,
167                 String headerLabel){
168         if (terms == null || terms.isEmpty()) {
169             terms = getTermGroupInstance(getGeneratedIdentifier());
170         }
171         final Map<String, List<String>> EMPTY_CITATION_REPEATABLES_INFO =
172                 new HashMap<String, List<String>>();
173         return createCitationInstance(inAuthority, null /*citationAuthRefName*/,
174                 citationInfo, terms, EMPTY_CITATION_REPEATABLES_INFO, headerLabel);
175     }
176
177     /**
178      * Creates a citation instance.
179      *
180      * @param inAuthority the owning authority
181      * @param citationAuthRefName the owning Authority ref name
182      * @param citationInfo the citation info
183      * @param terms a list of Citation terms
184      * @param citationRepeatablesInfo names and values of repeatable scalar fields in the Citation record
185      * @param headerLabel the header label
186      * @return the multipart output
187      */
188     public static PoxPayloadOut createCitationInstance(String inAuthority, 
189                 String citationAuthRefName, Map<String, String> citationInfo,
190                 List<CitationTermGroup> terms,
191                 Map<String, List<String>> citationRepeatablesInfo, String headerLabel){
192         CitationsCommon citation = new CitationsCommon();
193         citation.setInAuthority(inAuthority);
194         String shortId = citationInfo.get(CitationJAXBSchema.SHORT_IDENTIFIER);
195         if (shortId == null || shortId.isEmpty()) {
196                 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
197         }       
198         citation.setShortIdentifier(shortId);
199         
200         String value;
201         List<String> values = null;
202         
203         // Set values in the Term Information Group
204         CitationTermGroupList termList = new CitationTermGroupList();
205         if (terms == null || terms.isEmpty()) {
206             terms = getTermGroupInstance(getGeneratedIdentifier());
207         }
208         termList.getCitationTermGroup().addAll(terms); 
209         citation.setCitationTermGroupList(termList);               
210         
211         PoxPayloadOut multipart = new PoxPayloadOut(CitationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
212         PayloadOutputPart commonPart = multipart.addPart(citation,
213             MediaType.APPLICATION_XML_TYPE);
214         commonPart.setLabel(headerLabel);
215
216         if(logger.isDebugEnabled()){
217                 logger.debug("to be created, citation common ", citation, CitationsCommon.class);
218         }
219
220         return multipart;
221     }
222     
223     /**
224      * Creates the item in authority.
225      *
226      * @param vcsid the vcsid
227      * @param citationAuthorityRefName the citation authority ref name
228      * @param citationMap the citation map. CitationJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
229      * @param client the client
230      * @return the string
231      */
232     public static String createItemInAuthority(String vcsid, 
233                 String citationAuthorityRefName, Map<String,String> citationMap,
234                 List<CitationTermGroup> terms, Map<String, List<String>> citationRepeatablesMap,
235                 CitationAuthorityClient client ) {
236         // Expected status code: 201 Created
237         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
238         // Type of service request being tested
239         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
240         
241         String displayName = "";
242         if (terms !=null && terms.size() > 0) {
243             displayName = terms.get(0).getTermDisplayName();
244         }
245         
246         if(logger.isDebugEnabled()){
247                 logger.debug("Creating item with display name: \"" + displayName
248                                 +"\" in citationAuthority: \"" + vcsid +"\"");
249         }
250         PoxPayloadOut multipart = 
251                 createCitationInstance(vcsid, null /*citationAuthorityRefName*/,
252                         citationMap, terms, citationRepeatablesMap, client.getItemCommonPartName());
253         
254         String result = null;
255         ClientResponse<Response> res = client.createItem(vcsid, multipart);
256         try {
257                 int statusCode = res.getStatus();
258         
259                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
260                         throw new RuntimeException("Could not create Item: \""+citationMap.get(CitationJAXBSchema.SHORT_IDENTIFIER)
261                                         +"\" in citationAuthority: \"" + vcsid //citationAuthorityRefName
262                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
263                 }
264                 if(statusCode != EXPECTED_STATUS_CODE) {
265                         throw new RuntimeException("Unexpected Status when creating Item: \""+citationMap.get(CitationJAXBSchema.SHORT_IDENTIFIER)
266                                         +"\" in citationAuthority: \"" + vcsid /*citationAuthorityRefName*/ +"\", Status:"+ statusCode);
267                 }
268         
269                 result = extractId(res);
270         } finally {
271                 res.releaseConnection();
272         }
273         
274         return result;
275     }
276
277     /**
278      * Creates the citationAuthority ref name.
279      *
280      * @param shortId the citationAuthority shortIdentifier
281      * @param displaySuffix displayName to be appended, if non-null
282      * @return the string
283      */
284     /*
285     public static String createCitationAuthRefName(String shortId, String displaySuffix) {
286         String refName = "urn:cspace:org.collectionspace.demo:citationauthority:name("
287                         +shortId+")";
288         if(displaySuffix!=null&&!displaySuffix.isEmpty())
289                 refName += "'"+displaySuffix+"'";
290         return refName;
291     }
292     */
293
294     /**
295      * Creates the citation ref name.
296      *
297      * @param citationAuthRefName the citation auth ref name
298      * @param shortId the citation shortIdentifier
299      * @param displaySuffix displayName to be appended, if non-null
300      * @return the string
301      */
302     /*
303     public static String createCitationRefName(
304                                                 String citationAuthRefName, String shortId, String displaySuffix) {
305         String refName = citationAuthRefName+":citation:name("+shortId+")";
306         if(displaySuffix!=null&&!displaySuffix.isEmpty())
307                 refName += "'"+displaySuffix+"'";
308         return refName;
309     }
310     */
311
312     /**
313      * Extract id.
314      *
315      * @param res the res
316      * @return the string
317      */
318     public static String extractId(ClientResponse<Response> res) {
319         MultivaluedMap<String, Object> mvm = res.getMetadata();
320         // FIXME: This may throw an NPE if the Location: header isn't present
321         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
322         if(logger.isDebugEnabled()){
323                 logger.debug("extractId:uri=" + uri);
324         }
325         String[] segments = uri.split("/");
326         String id = segments[segments.length - 1];
327         if(logger.isDebugEnabled()){
328                 logger.debug("id=" + id);
329         }
330         return id;
331     }
332     
333     /**
334      * Returns an error message indicating that the status code returned by a
335      * specific call to a service does not fall within a set of valid status
336      * codes for that service.
337      *
338      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).
339      *
340      * @param statusCode  The invalid status code that was returned in the response,
341      *                    from submitting that type of request to the service.
342      *
343      * @return An error message.
344      */
345     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
346         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
347                 requestType.validStatusCodesAsString();
348     }
349
350
351     
352     /**
353      * Produces a default displayName from the basic name and dates fields.
354      * @see CitationDocumentModelHandler.prepareDefaultDisplayName() which
355      * duplicates this logic, until we define a service-general utils package
356      * that is neither client nor service specific.
357      * @param foreName  
358      * @param middleName
359      * @param surName
360      * @param birthDate
361      * @param deathDate
362      * @return display name
363      */
364     public static String prepareDefaultDisplayName(
365                 String foreName, String middleName, String surName, 
366             String birthDate, String deathDate) {
367         StringBuilder newStr = new StringBuilder();
368                 final String sep = " ";
369                 final String dateSep = "-";
370                 List<String> nameStrings = 
371                         Arrays.asList(foreName, middleName, surName);
372                 boolean firstAdded = false;
373         for(String partStr : nameStrings ){
374                         if(null != partStr ) {
375                                 if(firstAdded) {
376                                         newStr.append(sep);
377                                 }
378                                 newStr.append(partStr);
379                                 firstAdded = true;
380                         }
381         }
382         // Now we add the dates. In theory could have dates with no name, but that is their problem.
383         boolean foundBirth = false;
384         if(null != birthDate) {
385          if(firstAdded) {
386              newStr.append(sep);
387          }
388          newStr.append(birthDate);
389                  newStr.append(dateSep);     // Put this in whether there is a death date or not
390          foundBirth = true;
391         }
392         if(null != deathDate) {
393          if(!foundBirth) {
394              if(firstAdded) {
395                  newStr.append(sep);
396              }
397              newStr.append(dateSep);
398          }
399          newStr.append(deathDate);
400         }
401                 return newStr.toString();
402     }
403     
404     public static List<CitationTermGroup> getTermGroupInstance(String identifier) {
405         if (Tools.isBlank(identifier)) {
406             identifier = getGeneratedIdentifier();
407         }
408         List<CitationTermGroup> terms = new ArrayList<CitationTermGroup>();
409         CitationTermGroup term = new CitationTermGroup();
410         term.setTermDisplayName(identifier);
411         term.setTermName(identifier);
412         terms.add(term);
413         return terms;
414     }
415     
416     private static String getGeneratedIdentifier() {
417         return "id" + new Date().getTime(); 
418    }
419
420 }