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