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