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