]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
3a1b1e668ec0f490b0d16289b2c4a55142b1f273
[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.HashMap;
7 import java.util.List;
8 import java.util.Map;
9
10 import javax.ws.rs.core.MediaType;
11 import javax.ws.rs.core.MultivaluedMap;
12 import javax.ws.rs.core.Response;
13
14 import org.apache.commons.io.FileUtils;
15
16 import org.collectionspace.services.CitationJAXBSchema;
17 import org.collectionspace.services.citation.CitationTermGroup;
18 import org.collectionspace.services.citation.CitationTermGroupList;
19 import org.collectionspace.services.citation.CitationauthoritiesCommon;
20 import org.collectionspace.services.citation.CitationsCommon;
21 import org.collectionspace.services.client.test.ServiceRequestType;
22 import org.collectionspace.services.common.api.Tools;
23
24 import org.dom4j.DocumentException;
25 import org.jboss.resteasy.client.ClientResponse;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 public class CitationAuthorityClientUtils {
30     private static final Logger logger =
31         LoggerFactory.getLogger(CitationAuthorityClientUtils.class);
32     private static final String CITATION_VOCAB_TYPE = "CitationAuthority";
33
34     /**
35      * Creates a new Citation Authority
36      * @param displayName       The displayName used in UI, etc.
37      * @param refName           The proper refName for this authority
38      * @param headerLabel       The common part label
39      * @return  The PoxPayloadOut payload for the create call
40      */
41     public static PoxPayloadOut createCitationAuthorityInstance(
42                 String displayName, String shortIdentifier, String headerLabel ) {
43         CitationauthoritiesCommon citationAuthority = new CitationauthoritiesCommon();
44         citationAuthority.setDisplayName(displayName);
45         citationAuthority.setShortIdentifier(shortIdentifier);
46         citationAuthority.setVocabType(CITATION_VOCAB_TYPE); //FIXME: REM - Should this really be hard-coded?
47         PoxPayloadOut multipart = new PoxPayloadOut(CitationAuthorityClient.SERVICE_PAYLOAD_NAME);
48         PayloadOutputPart commonPart = multipart.addPart(citationAuthority, MediaType.APPLICATION_XML_TYPE);
49         commonPart.setLabel(headerLabel);
50
51         if(logger.isDebugEnabled()){
52                 logger.debug("to be created, citationAuthority common ", 
53                                         citationAuthority, CitationauthoritiesCommon.class);
54         }
55
56         return multipart;
57     }
58
59     /**
60      * @param commonPartXML the XML payload for the common part.
61      * @param headerLabel       The common part label
62      * @return  The PoxPayloadOut payload for the create call
63      * @throws DocumentException
64      */
65     public static PoxPayloadOut createCitationInstance(
66                 String commonPartXML, String headerLabel)  throws DocumentException {
67         PoxPayloadOut multipart = new PoxPayloadOut(CitationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
68         /*
69         PayloadOutputPart commonPart = multipart.addPart(commonPartXML,
70             MediaType.APPLICATION_XML_TYPE);
71         commonPart.setLabel(headerLabel);
72         */
73         PayloadOutputPart commonPart = multipart.addPart(
74                         CitationAuthorityClient.SERVICE_ITEM_COMMON_PART_NAME,
75                         commonPartXML);
76
77         if(logger.isDebugEnabled()){
78                 logger.debug("to be created, citation common ", commonPart.asXML());
79         }
80
81         return multipart;
82     }
83     
84     public static String createItemInAuthority(String vcsid,
85                 String commonPartXML,
86                 CitationAuthorityClient client ) throws DocumentException {
87         // Expected status code: 201 Created
88         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
89         // Type of service request being tested
90         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
91         
92         PoxPayloadOut multipart = 
93                 createCitationInstance(commonPartXML, client.getItemCommonPartName());
94         String newID = null;
95         Response res = client.createItem(vcsid, multipart);
96         try {
97                 int statusCode = res.getStatus();
98         
99                 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
100                         throw new RuntimeException("Could not create Item: \""+commonPartXML
101                                         +"\" in citationAuthority: \"" + vcsid
102                                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
103                 }
104                 if(statusCode != EXPECTED_STATUS_CODE) {
105                         throw new RuntimeException("Unexpected Status when creating Item: \""+commonPartXML
106                                         +"\" in citationAuthority: \"" + vcsid +"\", Status:"+ statusCode);
107                 }
108                 newID = extractId(res);
109         } finally {
110                 res.close();
111         }
112
113         return newID;
114     }
115     
116     /**
117      * Creates an item in the authority from an XML file.
118      *
119      * @param fileName the file name
120      * @return new CSID as string
121      * @throws Exception the exception
122      */
123     private String createItemInAuthorityFromXmlFile(String vcsid, String commonPartFileName, 
124                 CitationAuthorityClient client) throws Exception {
125         byte[] b = FileUtils.readFileToByteArray(new File(commonPartFileName));
126         String commonPartXML = new String(b);
127         return createItemInAuthority(vcsid, commonPartXML, client );
128     }    
129
130     public static String extractId(Response res) {
131         MultivaluedMap<String, Object> mvm = res.getMetadata();
132         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
133         if(logger.isDebugEnabled()){
134                 logger.debug("extractId:uri=" + uri);
135         }
136         String[] segments = uri.split("/");
137         String id = segments[segments.length - 1];
138         if(logger.isDebugEnabled()){
139                 logger.debug("id=" + id);
140         }
141         return id;
142     }
143     
144     /**
145      * Returns an error message indicating that the status code returned by a
146      * specific call to a service does not fall within a set of valid status
147      * codes for that service.
148      *
149      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).
150      *
151      * @param statusCode  The invalid status code that was returned in the response,
152      *                    from submitting that type of request to the service.
153      *
154      * @return An error message.
155      */
156     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
157         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
158                 requestType.validStatusCodesAsString();
159     }
160     
161      public static List<CitationTermGroup> getTermGroupInstance(String identifier) {
162         if (Tools.isBlank(identifier)) {
163             identifier = getGeneratedIdentifier();
164         }
165         List<CitationTermGroup> terms = new ArrayList<CitationTermGroup>();
166         CitationTermGroup term = new CitationTermGroup();
167         term.setTermDisplayName(identifier);
168         term.setTermName(identifier);
169         terms.add(term);
170         return terms;
171     }
172     
173     private static String getGeneratedIdentifier() {
174         return "id" + new Date().getTime(); 
175    }
176
177     public static PoxPayloadOut createCitationInstance(String shortIdentifier, String displayName,
178             String serviceItemCommonPartName) {
179         List<CitationTermGroup> terms = getTermGroupInstance(shortIdentifier, displayName);
180         
181         Map<String, String> citationInfo = new HashMap<String, String>();
182         citationInfo.put(CitationJAXBSchema.SHORT_IDENTIFIER, shortIdentifier);
183         
184         final Map<String, List<String>> EMPTY_CITATION_REPEATABLES_INFO = new HashMap<String, List<String>>();
185
186         return createCitationInstance(null, citationInfo, terms, EMPTY_CITATION_REPEATABLES_INFO, serviceItemCommonPartName);
187     }
188
189     private static PoxPayloadOut createCitationInstance(Object object, Map<String, String> citationInfo,
190             List<CitationTermGroup> terms, Map<String, List<String>> citationRepeatablesInfo,
191             String serviceItemCommonPartName) {
192         
193         CitationsCommon citation = new CitationsCommon();
194         String shortId = citationInfo.get(CitationJAXBSchema.SHORT_IDENTIFIER);
195         if (shortId == null || shortId.isEmpty()) {
196             throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
197         }       
198         citation.setShortIdentifier(shortId);
199         
200         // Set values in the Term Information Group
201         CitationTermGroupList termList = new CitationTermGroupList();
202         if (terms == null || terms.isEmpty()) {
203             terms = getTermGroupInstance(getGeneratedIdentifier());
204         }
205         termList.getCitationTermGroup().addAll(terms); 
206         citation.setCitationTermGroupList(termList);
207
208         PoxPayloadOut multipart = new PoxPayloadOut(CitationAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
209         PayloadOutputPart commonPart = multipart.addPart(citation, MediaType.APPLICATION_XML_TYPE);
210         commonPart.setLabel(serviceItemCommonPartName);
211
212         if (logger.isDebugEnabled()){
213                 logger.debug("to be created, organization common ", citation, CitationsCommon.class);
214         }
215
216         return multipart;
217     }
218
219     private static List<CitationTermGroup> getTermGroupInstance(String shortIdentifier, String displayName) {
220         if (Tools.isBlank(shortIdentifier)) {
221             shortIdentifier = getGeneratedIdentifier();
222         }
223         if (Tools.isBlank(shortIdentifier)) {
224             displayName = shortIdentifier;
225         }
226         
227         List<CitationTermGroup> terms = new ArrayList<CitationTermGroup>();
228         CitationTermGroup term = new CitationTermGroup();
229         term.setTermDisplayName(displayName);
230         term.setTermName(shortIdentifier);
231         terms.add(term);
232         return terms;
233     }
234
235 }