]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
e336b542465b61fe43c2b92e5190d36df80f0b63
[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 /**\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.isEmpty())) {\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         if (terms == null || terms.isEmpty()) {\r
243             terms = getTermGroupInstance(getGeneratedIdentifier());\r
244         }\r
245         termList.getOrgTermGroup().addAll(terms); \r
246         organization.setOrgTermGroupList(termList);\r
247         \r
248         if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) {\r
249                 ContactNameList contactsList = new ContactNameList();\r
250                 List<String> contactNames = contactsList.getContactName();\r
251                 contactNames.addAll(values);\r
252                 organization.setContactNames(contactsList);\r
253         }\r
254         if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null)\r
255                 organization.setFoundingDate(value);\r
256         if((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null)\r
257                 organization.setDissolutionDate(value);\r
258         if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null)\r
259                 organization.setFoundingPlace(value);\r
260         if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) {\r
261                 GroupList groupsList = new GroupList();\r
262                 List<String> groups = groupsList.getGroup();\r
263                 groups.addAll(values);\r
264                 organization.setGroups(groupsList);\r
265         }\r
266         if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) {\r
267                 FunctionList functionsList = new FunctionList();\r
268                 List<String> functions = functionsList.getFunction();\r
269                 functions.addAll(values);\r
270                 organization.setFunctions(functionsList);\r
271         }\r
272         if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) {\r
273                 HistoryNoteList historyNotesList = new HistoryNoteList();\r
274                 List<String> historyNotes = historyNotesList.getHistoryNote();\r
275                 historyNotes.addAll(values);\r
276                 organization.setHistoryNotes(historyNotesList);\r
277         }\r
278 \r
279         PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);\r
280         PayloadOutputPart commonPart = multipart.addPart(organization,\r
281             MediaType.APPLICATION_XML_TYPE);\r
282         commonPart.setLabel(headerLabel);\r
283 \r
284         if(logger.isDebugEnabled()){\r
285                 logger.debug("to be created, organization common ", organization, OrganizationsCommon.class);\r
286         }\r
287 \r
288         return multipart;\r
289     }\r
290 \r
291     /**\r
292      * Returns an error message indicating that the status code returned by a\r
293      * specific call to a service does not fall within a set of valid status\r
294      * codes for that service.\r
295      *\r
296      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).\r
297      *\r
298      * @param statusCode  The invalid status code that was returned in the response,\r
299      *                    from submitting that type of request to the service.\r
300      *\r
301      * @return An error message.\r
302      */\r
303     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {\r
304         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +\r
305                 requestType.validStatusCodesAsString();\r
306     }\r
307 \r
308     /**\r
309      * Extract id.\r
310      *\r
311      * @param res the res\r
312      * @return the string\r
313      */\r
314     public static String extractId(ClientResponse<Response> res) {\r
315         MultivaluedMap<String, Object> mvm = res.getMetadata();\r
316         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);\r
317         if(logger.isDebugEnabled()){\r
318                 logger.info("extractId:uri=" + uri);\r
319         }\r
320         String[] segments = uri.split("/");\r
321         String id = segments[segments.length - 1];\r
322         if(logger.isDebugEnabled()){\r
323                 logger.debug("id=" + id);\r
324         }\r
325         return id;\r
326     }\r
327     \r
328     /**\r
329      * Creates the org auth ref name.\r
330      *\r
331      * @param shortId the orgAuthority shortIdentifier\r
332      * @param displaySuffix displayName to be appended, if non-null\r
333      * @return the string\r
334      */\r
335     /*\r
336     public static String createOrgAuthRefName(String shortId, String displaySuffix) {\r
337         String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name("\r
338                         +shortId+")";\r
339         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
340                 refName += "'"+displaySuffix+"'";\r
341         return refName;\r
342     }\r
343     */\r
344 \r
345     /**\r
346      * Creates the organization ref name.\r
347      *\r
348      * @param orgAuthRefName the org auth ref name\r
349      * @param shortId the person shortIdentifier\r
350      * @param displaySuffix displayName to be appended, if non-null\r
351      * @return the string\r
352      */\r
353     /*\r
354     public static String createOrganizationRefName(\r
355                         String orgAuthRefName, String shortId, String displaySuffix) {\r
356         String refName = orgAuthRefName+":organization:name("+shortId+")";\r
357         if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
358                 refName += "'"+displaySuffix+"'";\r
359         return refName;\r
360     }\r
361     */\r
362 \r
363     /**\r
364      * Produces a default displayName from the basic name and foundingPlace fields.\r
365      * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which\r
366      * duplicates this logic, until we define a service-general utils package\r
367      * that is neither client nor service specific.\r
368      * @param shortName\r
369      * @param foundingPlace\r
370      * @return\r
371      * @throws Exception\r
372      */\r
373     public static String prepareDefaultDisplayName(\r
374                 String shortName, String foundingPlace ) {\r
375         StringBuilder newStr = new StringBuilder();\r
376                 final String sep = " ";\r
377                 boolean firstAdded = false;\r
378                 if(null != shortName ) {\r
379                         newStr.append(shortName);\r
380                         firstAdded = true;\r
381                 }\r
382         // Now we add the place\r
383                 if(null != foundingPlace ) {\r
384                         if(firstAdded) {\r
385                                 newStr.append(sep);\r
386                         }\r
387                         newStr.append(foundingPlace);\r
388                 }\r
389                 return newStr.toString();\r
390     }\r
391 \r
392     public static List<OrgTermGroup> getTermGroupInstance(String identifier) {\r
393         if (Tools.isBlank(identifier)) {\r
394             identifier = getGeneratedIdentifier();\r
395         }\r
396         List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();\r
397         OrgTermGroup term = new OrgTermGroup();\r
398         term.setTermDisplayName(identifier);\r
399         term.setTermName(identifier);\r
400         terms.add(term);\r
401         return terms;\r
402     }\r
403     \r
404     private static String getGeneratedIdentifier() {\r
405         return "id" + new Date().getTime(); \r
406    }\r
407     \r
408 }\r