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