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