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