]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
9b473f06b0f9134ee8bcb483cf5fa718fdbfdfeb
[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, Map<String,String> locationMap,
120                 List<LocTermGroup> terms, LocationAuthorityClient client ) {
121         // Expected status code: 201 Created
122         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
123         // Type of service request being tested
124         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
125         
126         String displayName = "";
127         if ((terms !=null) && (! terms.isEmpty())) {
128             displayName = terms.get(0).getTermDisplayName();
129         }
130         
131         if(logger.isDebugEnabled()){
132                 logger.debug("Creating item with display name: \"" + displayName
133                                 +"\" in locationAuthority: \"" + vcsid +"\"");
134         }
135         
136         PoxPayloadOut multipart = 
137                 createLocationInstance( locationAuthorityRefName,
138                         locationMap, terms, client.getItemCommonPartName() );
139         String newID = null;
140         Response res = client.createItem(vcsid, multipart);
141         try {
142                 int statusCode = res.getStatus();
143         
144                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
145                         throw new RuntimeException("Could not create Item: \""
146                                         +locationMap.get(LocationJAXBSchema.SHORT_IDENTIFIER)
147                                         +"\" in locationAuthority: \"" + locationAuthorityRefName
148                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
149                 }
150                 if(statusCode != EXPECTED_STATUS_CODE) {
151                         throw new RuntimeException("Unexpected Status when creating Item: \""
152                                         +locationMap.get(LocationJAXBSchema.SHORT_IDENTIFIER)
153                                         +"\" in locationAuthority: \"" + locationAuthorityRefName +"\", Status:"+ statusCode);
154                 }
155                 newID = extractId(res);
156         } finally {
157                 res.close();
158         }
159
160         return newID;
161     }
162
163     public static PoxPayloadOut createLocationInstance(
164                 String commonPartXML, String headerLabel)  throws DocumentException {
165         PoxPayloadOut multipart = new PoxPayloadOut(LocationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
166         PayloadOutputPart commonPart = multipart.addPart(commonPartXML,
167             MediaType.APPLICATION_XML_TYPE);
168         commonPart.setLabel(headerLabel);
169
170         if(logger.isDebugEnabled()){
171                 logger.debug("to be created, location common ", commonPartXML);
172         }
173
174         return multipart;
175     }
176     
177     public static String createItemInAuthority(String vcsid,
178                 String commonPartXML,
179                 LocationAuthorityClient client ) throws DocumentException {
180         // Expected status code: 201 Created
181         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
182         // Type of service request being tested
183         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
184         
185         PoxPayloadOut multipart = 
186                 createLocationInstance(commonPartXML, client.getItemCommonPartName());
187         String newID = null;
188         Response res = client.createItem(vcsid, multipart);
189         try {
190                 int statusCode = res.getStatus();
191         
192                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
193                         throw new RuntimeException("Could not create Item: \""+commonPartXML
194                                         +"\" in locationAuthority: \"" + vcsid
195                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
196                 }
197                 if(statusCode != EXPECTED_STATUS_CODE) {
198                         throw new RuntimeException("Unexpected Status when creating Item: \""+commonPartXML
199                                         +"\" in locationAuthority: \"" + vcsid +"\", Status:"+ statusCode);
200                 }
201                 newID = extractId(res);
202         } finally {
203                 res.close();
204         }
205
206         return newID;
207     }
208     
209     /**
210      * Creates the from xml file.
211      *
212      * @param fileName the file name
213      * @return new CSID as string
214      * @throws Exception the exception
215      */
216     private String createItemInAuthorityFromXmlFile(String vcsid, String commonPartFileName, 
217                 LocationAuthorityClient client) throws Exception {
218         byte[] b = FileUtils.readFileToByteArray(new File(commonPartFileName));
219         String commonPartXML = new String(b);
220         return createItemInAuthority(vcsid, commonPartXML, client );
221     }    
222
223     /**
224      * Creates the locationAuthority ref name.
225      *
226      * @param shortId the locationAuthority shortIdentifier
227      * @param displaySuffix displayName to be appended, if non-null
228      * @return the string
229      */
230     public static String createLocationAuthRefName(String shortId, String displaySuffix) {
231         String refName = "urn:cspace:org.collectionspace.demo:locationauthority:name("
232                         +shortId+")";
233                 if(displaySuffix!=null&&!displaySuffix.isEmpty())
234                         refName += "'"+displaySuffix+"'";
235         return refName;
236     }
237
238     /**
239      * Creates the location ref name.
240      *
241      * @param locationAuthRefName the locationAuthority ref name
242      * @param shortId the location shortIdentifier
243      * @param displaySuffix displayName to be appended, if non-null
244      * @return the string
245      */
246     public static String createLocationRefName(
247                                                 String locationAuthRefName, String shortId, String displaySuffix) {
248         String refName = locationAuthRefName+":location:name("+shortId+")";
249                 if(displaySuffix!=null&&!displaySuffix.isEmpty())
250                         refName += "'"+displaySuffix+"'";
251         return refName;
252     }
253
254     public static String extractId(Response res) {
255         MultivaluedMap<String, Object> mvm = res.getMetadata();
256         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
257         if(logger.isDebugEnabled()){
258                 logger.debug("extractId:uri=" + uri);
259         }
260         String[] segments = uri.split("/");
261         String id = segments[segments.length - 1];
262         if(logger.isDebugEnabled()){
263                 logger.debug("id=" + id);
264         }
265         return id;
266     }
267     
268     /**
269      * Returns an error message indicating that the status code returned by a
270      * specific call to a service does not fall within a set of valid status
271      * codes for that service.
272      *
273      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).
274      *
275      * @param statusCode  The invalid status code that was returned in the response,
276      *                    from submitting that type of request to the service.
277      *
278      * @return An error message.
279      */
280     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
281         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
282                 requestType.validStatusCodesAsString();
283     }
284
285
286     
287     /**
288      * Produces a default displayName from the basic name and dates fields.
289      * @see LocationDocumentModelHandler.prepareDefaultDisplayName() which
290      * duplicates this logic, until we define a service-general utils package
291      * that is neither client nor service specific.
292      * @param name      
293      * @return
294      */
295     public static String prepareDefaultDisplayName(
296                 String name ) {
297         StringBuilder newStr = new StringBuilder();
298                         newStr.append(name);
299                 return newStr.toString();
300     }
301     
302     public static List<LocTermGroup> getTermGroupInstance(String identifier) {
303         if (Tools.isBlank(identifier)) {
304             identifier = getGeneratedIdentifier();
305         }
306         List<LocTermGroup> terms = new ArrayList<LocTermGroup>();
307         LocTermGroup term = new LocTermGroup();
308         term.setTermDisplayName(identifier);
309         term.setTermName(identifier);
310         terms.add(term);
311         return terms;
312     }
313     
314     private static String getGeneratedIdentifier() {
315         return "id" + new Date().getTime(); 
316    }
317
318 }