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