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