]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
e8ae69ad01207ad654bbfbda7d8e8111457d2217
[tmp/jakarta-migration.git] /
1 package org.collectionspace.services.client;\r
2 \r
3 import java.io.File;\r
4 import java.util.ArrayList;\r
5 import java.util.Date;\r
6 import java.util.List;\r
7 import java.util.Map;\r
8 import javax.ws.rs.core.MediaType;\r
9 import javax.ws.rs.core.MultivaluedMap;\r
10 import javax.ws.rs.core.Response;\r
11 import org.apache.commons.io.FileUtils;\r
12 import org.collectionspace.services.LocationJAXBSchema;\r
13 import org.collectionspace.services.client.test.ServiceRequestType;\r
14 import org.collectionspace.services.common.api.Tools;\r
15 import org.collectionspace.services.location.*;\r
16 import org.dom4j.DocumentException;\r
17 import org.jboss.resteasy.client.ClientResponse;\r
18 import org.slf4j.Logger;\r
19 import org.slf4j.LoggerFactory;\r
20 \r
21 public class LocationAuthorityClientUtils {\r
22     private static final Logger logger =\r
23         LoggerFactory.getLogger(LocationAuthorityClientUtils.class);\r
24 \r
25     /**\r
26      * Creates a new Location Authority\r
27      * @param displayName       The displayName used in UI, etc.\r
28      * @param refName           The proper refName for this authority\r
29      * @param headerLabel       The common part label\r
30      * @return  The PoxPayloadOut payload for the create call\r
31      */\r
32     public static PoxPayloadOut createLocationAuthorityInstance(\r
33                 String displayName, String shortIdentifier, String headerLabel ) {\r
34         \r
35         LocationauthoritiesCommon locationAuthority = new LocationauthoritiesCommon();\r
36         locationAuthority.setDisplayName(displayName);\r
37         locationAuthority.setShortIdentifier(shortIdentifier);\r
38         // String refName = createLocationAuthRefName(shortIdentifier, displayName);\r
39         // locationAuthority.setRefName(refName);\r
40         locationAuthority.setVocabType("LocationAuthority"); //FIXME: REM - Should this really be hard-coded?\r
41         \r
42         PoxPayloadOut multipart = new PoxPayloadOut(LocationAuthorityClient.SERVICE_PAYLOAD_NAME);\r
43         PayloadOutputPart commonPart = multipart.addPart(headerLabel, locationAuthority);\r
44 \r
45         if(logger.isDebugEnabled()){\r
46                 logger.debug("to be created, locationAuthority common ", \r
47                                         locationAuthority, LocationauthoritiesCommon.class);\r
48         }\r
49 \r
50         return multipart;\r
51     }\r
52 \r
53     /**\r
54      * @param locationRefName  The proper refName for this authority\r
55      * @param locationInfo the properties for the new Location. Can pass in one condition\r
56      *                                          note and date string.\r
57      * @param headerLabel       The common part label\r
58      * @return  The PoxPayloadOut payload for the create call\r
59      */\r
60     public static PoxPayloadOut createLocationInstance( \r
61                 String locationAuthRefName, Map<String, String> locationInfo, \r
62                                 List<LocTermGroup> terms, String headerLabel){\r
63         LocationsCommon location = new LocationsCommon();\r
64         String shortId = locationInfo.get(LocationJAXBSchema.SHORT_IDENTIFIER);\r
65         String displayName = locationInfo.get(LocationJAXBSchema.DISPLAY_NAME);\r
66         location.setShortIdentifier(shortId);\r
67         // String locationRefName = createLocationRefName(locationAuthRefName, shortId, displayName);\r
68         // location.setRefName(locationRefName);\r
69         String value = null;\r
70         value = locationInfo.get(LocationJAXBSchema.DISPLAY_NAME_COMPUTED);\r
71         boolean displayNameComputed = (value==null) || value.equalsIgnoreCase("true");\r
72         \r
73         // Set values in the Term Information Group\r
74         LocTermGroupList termList = new LocTermGroupList();\r
75         if (terms == null || terms.isEmpty()) {\r
76             terms = getTermGroupInstance(getGeneratedIdentifier());\r
77         }\r
78         termList.getLocTermGroup().addAll(terms); \r
79         location.setLocTermGroupList(termList);\r
80         \r
81         if((value = (String)locationInfo.get(LocationJAXBSchema.CONDITION_NOTE))!=null) {\r
82             ConditionGroupList conditionGroupList = new ConditionGroupList();\r
83             List<ConditionGroup> conditionGroups = conditionGroupList.getConditionGroup();\r
84             ConditionGroup conditionGroup = new ConditionGroup();\r
85             conditionGroup.setConditionNote(value);\r
86             if((value = (String)locationInfo.get(LocationJAXBSchema.CONDITION_NOTE_DATE))!=null)\r
87                 conditionGroup.setConditionNoteDate(value);\r
88             conditionGroups.add(conditionGroup);\r
89             location.setConditionGroupList(conditionGroupList);\r
90         }\r
91         if((value = (String)locationInfo.get(LocationJAXBSchema.SECURITY_NOTE))!=null)\r
92                 location.setSecurityNote(value);\r
93         if((value = (String)locationInfo.get(LocationJAXBSchema.ACCESS_NOTE))!=null)\r
94                 location.setAccessNote(value);\r
95         if((value = (String)locationInfo.get(LocationJAXBSchema.LOCATION_TYPE))!=null)\r
96                 location.setLocationType(value);\r
97         if((value = (String)locationInfo.get(LocationJAXBSchema.ADDRESS))!=null)\r
98                 location.setAddress(value);\r
99 \r
100         PoxPayloadOut multipart = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);\r
101         PayloadOutputPart commonPart = multipart.addPart(location,\r
102             MediaType.APPLICATION_XML_TYPE);\r
103         commonPart.setLabel(headerLabel);\r
104 \r
105         if(logger.isDebugEnabled()){\r
106                 logger.debug("to be created, location common ", location, LocationsCommon.class);\r
107         }\r
108 \r
109         return multipart;\r
110     }\r
111     \r
112     /**\r
113      * @param vcsid CSID of the authority to create a new location in\r
114      * @param locationAuthorityRefName The refName for the authority\r
115      * @param locationMap the properties for the new Location\r
116      * @param client the service client\r
117      * @return the CSID of the new item\r
118      */\r
119     public static String createItemInAuthority(String vcsid, \r
120                 String locationAuthorityRefName, Map<String,String> locationMap,\r
121                 List<LocTermGroup> terms, LocationAuthorityClient client ) {\r
122         // Expected status code: 201 Created\r
123         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();\r
124         // Type of service request being tested\r
125         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;\r
126         \r
127         String displayName = "";\r
128         if ((terms !=null) && (! terms.isEmpty())) {\r
129             displayName = terms.get(0).getTermDisplayName();\r
130         }\r
131         \r
132         if(logger.isDebugEnabled()){\r
133                 logger.debug("Creating item with display name: \"" + displayName\r
134                                 +"\" in locationAuthority: \"" + vcsid +"\"");\r
135         }\r
136         \r
137         PoxPayloadOut multipart = \r
138                 createLocationInstance( locationAuthorityRefName,\r
139                         locationMap, terms, client.getItemCommonPartName() );\r
140         String newID = null;\r
141         ClientResponse<Response> res = client.createItem(vcsid, multipart);\r
142         try {\r
143                 int statusCode = res.getStatus();\r
144         \r
145                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {\r
146                         throw new RuntimeException("Could not create Item: \""\r
147                                         +locationMap.get(LocationJAXBSchema.SHORT_IDENTIFIER)\r
148                                         +"\" in locationAuthority: \"" + locationAuthorityRefName\r
149                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));\r
150                 }\r
151                 if(statusCode != EXPECTED_STATUS_CODE) {\r
152                         throw new RuntimeException("Unexpected Status when creating Item: \""\r
153                                         +locationMap.get(LocationJAXBSchema.SHORT_IDENTIFIER)\r
154                                         +"\" in locationAuthority: \"" + locationAuthorityRefName +"\", Status:"+ statusCode);\r
155                 }\r
156                 newID = extractId(res);\r
157         } finally {\r
158                 res.releaseConnection();\r
159         }\r
160 \r
161         return newID;\r
162     }\r
163 \r
164     public static PoxPayloadOut createLocationInstance(\r
165                 String commonPartXML, String headerLabel)  throws DocumentException {\r
166         PoxPayloadOut multipart = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);\r
167         PayloadOutputPart commonPart = multipart.addPart(commonPartXML,\r
168             MediaType.APPLICATION_XML_TYPE);\r
169         commonPart.setLabel(headerLabel);\r
170 \r
171         if(logger.isDebugEnabled()){\r
172                 logger.debug("to be created, location common ", commonPartXML);\r
173         }\r
174 \r
175         return multipart;\r
176     }\r
177     \r
178     public static String createItemInAuthority(String vcsid,\r
179                 String commonPartXML,\r
180                 LocationAuthorityClient client ) throws DocumentException {\r
181         // Expected status code: 201 Created\r
182         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();\r
183         // Type of service request being tested\r
184         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;\r
185         \r
186         PoxPayloadOut multipart = \r
187                 createLocationInstance(commonPartXML, client.getItemCommonPartName());\r
188         String newID = null;\r
189         ClientResponse<Response> res = client.createItem(vcsid, multipart);\r
190         try {\r
191                 int statusCode = res.getStatus();\r
192         \r
193                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {\r
194                         throw new RuntimeException("Could not create Item: \""+commonPartXML\r
195                                         +"\" in locationAuthority: \"" + vcsid\r
196                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));\r
197                 }\r
198                 if(statusCode != EXPECTED_STATUS_CODE) {\r
199                         throw new RuntimeException("Unexpected Status when creating Item: \""+commonPartXML\r
200                                         +"\" in locationAuthority: \"" + vcsid +"\", Status:"+ statusCode);\r
201                 }\r
202                 newID = extractId(res);\r
203         } finally {\r
204                 res.releaseConnection();\r
205         }\r
206 \r
207         return newID;\r
208     }\r
209     \r
210     /**\r
211      * Creates the from xml file.\r
212      *\r
213      * @param fileName the file name\r
214      * @return new CSID as string\r
215      * @throws Exception the exception\r
216      */\r
217     private String createItemInAuthorityFromXmlFile(String vcsid, String commonPartFileName, \r
218                 LocationAuthorityClient client) throws Exception {\r
219         byte[] b = FileUtils.readFileToByteArray(new File(commonPartFileName));\r
220         String commonPartXML = new String(b);\r
221         return createItemInAuthority(vcsid, commonPartXML, client );\r
222     }    \r
223 \r
224     /**\r
225      * Creates the locationAuthority ref name.\r
226      *\r
227      * @param shortId the locationAuthority shortIdentifier\r
228      * @param displaySuffix displayName to be appended, if non-null\r
229      * @return the string\r
230      */\r
231     public static String createLocationAuthRefName(String shortId, String displaySuffix) {\r
232         String refName = "urn:cspace:org.collectionspace.demo:locationauthority:name("\r
233                         +shortId+")";\r
234                 if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
235                         refName += "'"+displaySuffix+"'";\r
236         return refName;\r
237     }\r
238 \r
239     /**\r
240      * Creates the location ref name.\r
241      *\r
242      * @param locationAuthRefName the locationAuthority ref name\r
243      * @param shortId the location shortIdentifier\r
244      * @param displaySuffix displayName to be appended, if non-null\r
245      * @return the string\r
246      */\r
247     public static String createLocationRefName(\r
248                                                 String locationAuthRefName, String shortId, String displaySuffix) {\r
249         String refName = locationAuthRefName+":location:name("+shortId+")";\r
250                 if(displaySuffix!=null&&!displaySuffix.isEmpty())\r
251                         refName += "'"+displaySuffix+"'";\r
252         return refName;\r
253     }\r
254 \r
255     public static String extractId(ClientResponse<Response> res) {\r
256         MultivaluedMap<String, Object> mvm = res.getMetadata();\r
257         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);\r
258         if(logger.isDebugEnabled()){\r
259                 logger.debug("extractId:uri=" + uri);\r
260         }\r
261         String[] segments = uri.split("/");\r
262         String id = segments[segments.length - 1];\r
263         if(logger.isDebugEnabled()){\r
264                 logger.debug("id=" + id);\r
265         }\r
266         return id;\r
267     }\r
268     \r
269     /**\r
270      * Returns an error message indicating that the status code returned by a\r
271      * specific call to a service does not fall within a set of valid status\r
272      * codes for that service.\r
273      *\r
274      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).\r
275      *\r
276      * @param statusCode  The invalid status code that was returned in the response,\r
277      *                    from submitting that type of request to the service.\r
278      *\r
279      * @return An error message.\r
280      */\r
281     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {\r
282         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +\r
283                 requestType.validStatusCodesAsString();\r
284     }\r
285 \r
286 \r
287     \r
288     /**\r
289      * Produces a default displayName from the basic name and dates fields.\r
290      * @see LocationDocumentModelHandler.prepareDefaultDisplayName() which\r
291      * duplicates this logic, until we define a service-general utils package\r
292      * that is neither client nor service specific.\r
293      * @param name      \r
294      * @return\r
295      */\r
296     public static String prepareDefaultDisplayName(\r
297                 String name ) {\r
298         StringBuilder newStr = new StringBuilder();\r
299                         newStr.append(name);\r
300                 return newStr.toString();\r
301     }\r
302     \r
303     public static List<LocTermGroup> getTermGroupInstance(String identifier) {\r
304         if (Tools.isBlank(identifier)) {\r
305             identifier = getGeneratedIdentifier();\r
306         }\r
307         List<LocTermGroup> terms = new ArrayList<LocTermGroup>();\r
308         LocTermGroup term = new LocTermGroup();\r
309         term.setTermDisplayName(identifier);\r
310         term.setTermName(identifier);\r
311         terms.add(term);\r
312         return terms;\r
313     }\r
314     \r
315     private static String getGeneratedIdentifier() {\r
316         return "id" + new Date().getTime(); \r
317    }\r
318 \r
319 }\r