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