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