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