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