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