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