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