]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
f9c92a4572b907d4551f776471f5b3cf220b6eec
[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         if ((value = (String) taxonInfo.get(TaxonJAXBSchema.TAXON_IS_NAMED_HYBRID)) != null) {
101             taxon.setTaxonIsNamedHybrid(value);
102         }
103         if (taxonCitationList != null) {
104             taxon.setTaxonCitationList(taxonCitationList);
105         }
106
107         if (taxonAuthorGroupList != null) {
108             taxon.setTaxonAuthorGroupList(taxonAuthorGroupList);
109         }
110
111         // FIXME: When the field isNamedHybrid becomes Boolean, add it as such to sample instances.
112
113         PoxPayloadOut multipart = new PoxPayloadOut(TaxonomyAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
114         PayloadOutputPart commonPart = multipart.addPart(taxon,
115                 MediaType.APPLICATION_XML_TYPE);
116         commonPart.setLabel(headerLabel);
117
118         if (logger.isDebugEnabled()) {
119             logger.debug("to be created, taxon common ", taxon, TaxonCommon.class);
120         }
121
122         return multipart;
123     }
124
125     /**
126      * @param vcsid CSID of the authority to create a new taxon in
127      * @param TaxonomyauthorityRefName The refName for the authority
128      * @param taxonMap the properties for the new Taxon
129      * @param client the service client
130      * @return the CSID of the new item
131      */
132     public static String createItemInAuthority(String vcsid,
133             String TaxonomyauthorityRefName, Map<String, String> taxonMap,
134             TaxonAuthorGroupList taxonAuthorGroupList,
135             TaxonCitationList taxonCitationList, TaxonomyAuthorityClient client) {
136         // Expected status code: 201 Created
137         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
138         // Type of service request being tested
139         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
140
141         String displayName = taxonMap.get(TaxonJAXBSchema.DISPLAY_NAME);
142         String displayNameComputedStr = taxonMap.get(TaxonJAXBSchema.DISPLAY_NAME_COMPUTED);
143         boolean displayNameComputed = (displayNameComputedStr == null) || displayNameComputedStr.equalsIgnoreCase("true");
144         if (displayName == null) {
145             if (!displayNameComputed) {
146                 throw new RuntimeException(
147                         "CreateItem: Must supply a displayName if displayNameComputed is set to false.");
148             }
149             displayName =
150                     prepareDefaultDisplayName(
151                     taxonMap.get(TaxonJAXBSchema.NAME));
152         }
153
154         if (logger.isDebugEnabled()) {
155             logger.debug("Import: Create Item: \"" + displayName
156                     + "\" in Taxonomyauthority: \"" + TaxonomyauthorityRefName + "\"");
157         }
158         PoxPayloadOut multipart =
159                 createTaxonInstance(TaxonomyauthorityRefName,
160                 taxonMap, taxonAuthorGroupList, taxonCitationList, client.getItemCommonPartName());
161         String newID = null;
162         ClientResponse<Response> res = client.createItem(vcsid, multipart);
163         try {
164             int statusCode = res.getStatus();
165
166             if (!REQUEST_TYPE.isValidStatusCode(statusCode)) {
167                 throw new RuntimeException("Could not create Item: \""
168                         + taxonMap.get(TaxonJAXBSchema.SHORT_IDENTIFIER)
169                         + "\" in Taxonomyauthority: \"" + TaxonomyauthorityRefName
170                         + "\" " + invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
171             }
172             if (statusCode != EXPECTED_STATUS_CODE) {
173                 throw new RuntimeException("Unexpected Status when creating Item: \""
174                         + taxonMap.get(TaxonJAXBSchema.SHORT_IDENTIFIER)
175                         + "\" in Taxonomyauthority: \"" + TaxonomyauthorityRefName + "\", Status:" + statusCode);
176             }
177             newID = extractId(res);
178         } finally {
179             res.releaseConnection();
180         }
181
182         return newID;
183     }
184
185     public static PoxPayloadOut createTaxonInstance(
186             String commonPartXML, String headerLabel) throws DocumentException {
187         PoxPayloadOut multipart = new PoxPayloadOut(TaxonomyAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
188         PayloadOutputPart commonPart = multipart.addPart(commonPartXML,
189                 MediaType.APPLICATION_XML_TYPE);
190         commonPart.setLabel(headerLabel);
191
192         if (logger.isDebugEnabled()) {
193             logger.debug("to be created, Taxon common ", commonPartXML);
194         }
195
196         return multipart;
197     }
198
199     public static String createItemInAuthority(String vcsid,
200             String commonPartXML,
201             TaxonomyAuthorityClient client) throws DocumentException {
202         // Expected status code: 201 Created
203         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
204         // Type of service request being tested
205         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
206
207         PoxPayloadOut multipart =
208                 createTaxonInstance(commonPartXML, client.getItemCommonPartName());
209         String newID = null;
210         ClientResponse<Response> res = client.createItem(vcsid, multipart);
211         try {
212             int statusCode = res.getStatus();
213
214             if (!REQUEST_TYPE.isValidStatusCode(statusCode)) {
215                 throw new RuntimeException("Could not create Item: \"" + commonPartXML
216                         + "\" in Taxonomyauthority: \"" + vcsid
217                         + "\" " + invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
218             }
219             if (statusCode != EXPECTED_STATUS_CODE) {
220                 throw new RuntimeException("Unexpected Status when creating Item: \"" + commonPartXML
221                         + "\" in Taxonomyauthority: \"" + vcsid + "\", Status:" + statusCode);
222             }
223             newID = extractId(res);
224         } finally {
225             res.releaseConnection();
226         }
227
228         return newID;
229     }
230
231     /**
232      * Creates the from xml file.
233      *
234      * @param fileName the file name
235      * @return new CSID as string
236      * @throws Exception the exception
237      */
238     private String createItemInAuthorityFromXmlFile(String vcsid, String commonPartFileName,
239             TaxonomyAuthorityClient client) throws Exception {
240         byte[] b = FileUtils.readFileToByteArray(new File(commonPartFileName));
241         String commonPartXML = new String(b);
242         return createItemInAuthority(vcsid, commonPartXML, client);
243     }
244
245     /**
246      * Creates the Taxonomyauthority ref name.
247      *
248      * @param shortId the Taxonomyauthority shortIdentifier
249      * @param displaySuffix displayName to be appended, if non-null
250      * @return the string
251      */
252     public static String createTaxonomyAuthRefName(String shortId, String displaySuffix) {
253         String refName = "urn:cspace:org.collectionspace.demo:taxonomyauthority:name("
254                 + shortId + ")";
255         if (displaySuffix != null && !displaySuffix.isEmpty()) {
256             refName += "'" + displaySuffix + "'";
257         }
258         return refName;
259     }
260
261     /**
262      * Creates the taxon ref name.
263      *
264      * @param taxonomyAuthRefName the Taxonomyauthority ref name
265      * @param shortId the taxon shortIdentifier
266      * @param displaySuffix displayName to be appended, if non-null
267      * @return the string
268      */
269     public static String createTaxonomyRefName(
270             String taxonomyAuthRefName, String shortId, String displaySuffix) {
271         String refName = taxonomyAuthRefName + ":taxon:name(" + shortId + ")";
272         if (displaySuffix != null && !displaySuffix.isEmpty()) {
273             refName += "'" + displaySuffix + "'";
274         }
275         return refName;
276     }
277
278     public static String extractId(ClientResponse<Response> res) {
279         MultivaluedMap<String, Object> mvm = res.getMetadata();
280         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
281         if (logger.isDebugEnabled()) {
282             logger.debug("extractId:uri=" + uri);
283         }
284         String[] segments = uri.split("/");
285         String id = segments[segments.length - 1];
286         if (logger.isDebugEnabled()) {
287             logger.debug("id=" + id);
288         }
289         return id;
290     }
291
292     /**
293      * Returns an error message indicating that the status code returned by a
294      * specific call to a service does not fall within a set of valid status
295      * codes for that service.
296      *
297      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).
298      *
299      * @param statusCode  The invalid status code that was returned in the response,
300      *                    from submitting that type of request to the service.
301      *
302      * @return An error message.
303      */
304     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
305         return "Status code '" + statusCode + "' in response is NOT within the expected set: "
306                 + requestType.validStatusCodesAsString();
307     }
308
309     /**
310      * Produces a default displayName from the basic name and dates fields.
311      * @see TaxonomyDocumentModelHandler.prepareDefaultDisplayName() which
312      * duplicates this logic, until we define a service-general utils package
313      * that is neither client nor service specific.
314      * @param name      
315      * @return
316      */
317     public static String prepareDefaultDisplayName(
318             String name) {
319         StringBuilder newStr = new StringBuilder();
320         newStr.append(name);
321         return newStr.toString();
322     }
323 }