]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
789929283720edb51628f36bc6ed1f203a157261
[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
13 import org.collectionspace.services.MaterialJAXBSchema;
14 import org.collectionspace.services.client.test.ServiceRequestType;
15 import org.collectionspace.services.common.api.Tools;
16 import org.collectionspace.services.material.MaterialTermGroup;
17 import org.collectionspace.services.material.MaterialTermGroupList;
18 import org.collectionspace.services.material.MaterialauthoritiesCommon;
19 import org.collectionspace.services.material.MaterialsCommon;
20
21 import org.dom4j.DocumentException;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24
25 public class MaterialAuthorityClientUtils {
26     private static final Logger logger =
27         LoggerFactory.getLogger(MaterialAuthorityClientUtils.class);
28
29     /**
30      * Creates a new Material 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 createMaterialAuthorityInstance(
37             String displayName, String shortIdentifier, String headerLabel ) {
38         MaterialauthoritiesCommon materialAuthority = new MaterialauthoritiesCommon();
39         materialAuthority.setDisplayName(displayName);
40         materialAuthority.setShortIdentifier(shortIdentifier);
41         String refName = createMaterialAuthRefName(shortIdentifier, displayName);
42         materialAuthority.setRefName(refName);
43         materialAuthority.setVocabType("MaterialAuthority"); //FIXME: REM - Should this really be hard-coded?
44         PoxPayloadOut multipart = new PoxPayloadOut(MaterialAuthorityClient.SERVICE_PAYLOAD_NAME);
45         PayloadOutputPart commonPart = multipart.addPart(materialAuthority, MediaType.APPLICATION_XML_TYPE);
46         commonPart.setLabel(headerLabel);
47
48         if(logger.isDebugEnabled()){
49             logger.debug("to be created, materialAuthority common ", 
50                         materialAuthority, MaterialauthoritiesCommon.class);
51         }
52
53         return multipart;
54     }
55
56     /**
57      * @param materialRefName  The proper refName for this authority
58      * @param materialInfo the properties for the new Material. 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 createMaterialInstance( 
64             String materialAuthRefName, Map<String, String> materialInfo, 
65         List<MaterialTermGroup> terms, String headerLabel){
66         MaterialsCommon material = new MaterialsCommon();
67         String shortId = materialInfo.get(MaterialJAXBSchema.SHORT_IDENTIFIER);
68         material.setShortIdentifier(shortId);
69
70         // Set values in the Term Information Group
71         MaterialTermGroupList termList = new MaterialTermGroupList();
72         if (terms == null || terms.isEmpty()) {
73             terms = getTermGroupInstance(getGeneratedIdentifier());
74         }
75         termList.getMaterialTermGroup().addAll(terms); 
76         material.setMaterialTermGroupList(termList);
77         
78         PoxPayloadOut multipart = new PoxPayloadOut(MaterialAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
79         PayloadOutputPart commonPart = multipart.addPart(material,
80             MediaType.APPLICATION_XML_TYPE);
81         commonPart.setLabel(headerLabel);
82
83         if(logger.isDebugEnabled()){
84             logger.debug("to be created, material common ", material, MaterialsCommon.class);
85         }
86
87         return multipart;
88     }
89     
90     /**
91      * @param vcsid CSID of the authority to create a new material
92      * @param materialAuthorityRefName The refName for the authority
93      * @param materialMap the properties for the new Material
94      * @param client the service client
95      * @return the CSID of the new item
96      */
97     public static String createItemInAuthority(String vcsid, 
98             String materialAuthorityRefName, Map<String,String> materialMap,
99             List<MaterialTermGroup> terms, MaterialAuthorityClient client ) {
100         // Expected status code: 201 Created
101         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
102         // Type of service request being tested
103         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
104         
105         String displayName = "";
106         if ((terms !=null) && (! terms.isEmpty())) {
107             displayName = terms.get(0).getTermDisplayName();
108         }
109         if(logger.isDebugEnabled()){
110             logger.debug("Creating item with display name: \"" + displayName
111                     +"\" in locationAuthority: \"" + vcsid +"\"");
112         }
113         PoxPayloadOut multipart = 
114             createMaterialInstance(materialAuthorityRefName, materialMap, terms, client.getItemCommonPartName() );
115         String newID = null;
116         Response res = client.createItem(vcsid, multipart);
117         try {
118             int statusCode = res.getStatus();
119     
120             if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
121                 throw new RuntimeException("Could not create Item: \""
122                         +materialMap.get(MaterialJAXBSchema.SHORT_IDENTIFIER)
123                         +"\" in materialAuthority: \"" + materialAuthorityRefName
124                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
125             }
126             if(statusCode != EXPECTED_STATUS_CODE) {
127                 throw new RuntimeException("Unexpected Status when creating Item: \""
128                         +materialMap.get(MaterialJAXBSchema.SHORT_IDENTIFIER)
129                         +"\" in materialAuthority: \"" + materialAuthorityRefName +"\", Status:"+ statusCode);
130             }
131             newID = extractId(res);
132         } finally {
133             res.close();
134         }
135
136         return newID;
137     }
138
139     public static PoxPayloadOut createMaterialInstance(
140             String commonPartXML, String headerLabel)  throws DocumentException {
141         PoxPayloadOut multipart = new PoxPayloadOut(MaterialAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
142         PayloadOutputPart commonPart = multipart.addPart(commonPartXML,
143             MediaType.APPLICATION_XML_TYPE);
144         commonPart.setLabel(headerLabel);
145
146         if(logger.isDebugEnabled()){
147             logger.debug("to be created, material common ", commonPartXML);
148         }
149
150         return multipart;
151     }
152     
153     public static String createItemInAuthority(String vcsid,
154             String commonPartXML,
155             MaterialAuthorityClient client ) throws DocumentException {
156         // Expected status code: 201 Created
157         int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
158         // Type of service request being tested
159         ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
160         
161         PoxPayloadOut multipart = 
162             createMaterialInstance(commonPartXML, client.getItemCommonPartName());
163         String newID = null;
164         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: \""+commonPartXML
170                         +"\" in materialAuthority: \"" + vcsid
171                         +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
172             }
173             if(statusCode != EXPECTED_STATUS_CODE) {
174                 throw new RuntimeException("Unexpected Status when creating Item: \""+commonPartXML
175                         +"\" in materialAuthority: \"" + vcsid +"\", Status:"+ statusCode);
176             }
177             newID = extractId(res);
178         } finally {
179             res.close();
180         }
181
182         return newID;
183     }
184     
185     /**
186      * Creates the from xml file.
187      *
188      * @param fileName the file name
189      * @return new CSID as string
190      * @throws Exception the exception
191      */
192     private String createItemInAuthorityFromXmlFile(String vcsid, String commonPartFileName, 
193             MaterialAuthorityClient client) throws Exception {
194         byte[] b = FileUtils.readFileToByteArray(new File(commonPartFileName));
195         String commonPartXML = new String(b);
196         return createItemInAuthority(vcsid, commonPartXML, client );
197     }    
198
199     /**
200      * Creates the materialAuthority ref name.
201      *
202      * @param shortId the materialAuthority shortIdentifier
203      * @param displaySuffix displayName to be appended, if non-null
204      * @return the string
205      */
206     public static String createMaterialAuthRefName(String shortId, String displaySuffix) {
207         String refName = "urn:cspace:org.collectionspace.demo:materialauthority:name("
208             +shortId+")";
209         if(displaySuffix!=null&&!displaySuffix.isEmpty())
210             refName += "'"+displaySuffix+"'";
211         return refName;
212     }
213
214     /**
215      * Creates the material ref name.
216      *
217      * @param materialAuthRefName the materialAuthority ref name
218      * @param shortId the material shortIdentifier
219      * @param displaySuffix displayName to be appended, if non-null
220      * @return the string
221      */
222     public static String createMaterialRefName(
223                             String materialAuthRefName, String shortId, String displaySuffix) {
224         String refName = materialAuthRefName+":material:name("+shortId+")";
225         if(displaySuffix!=null&&!displaySuffix.isEmpty())
226             refName += "'"+displaySuffix+"'";
227         return refName;
228     }
229
230     public static String extractId(Response res) {
231         MultivaluedMap<String, Object> mvm = res.getMetadata();
232         String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
233         if(logger.isDebugEnabled()){
234             logger.debug("extractId:uri=" + uri);
235         }
236         String[] segments = uri.split("/");
237         String id = segments[segments.length - 1];
238         if(logger.isDebugEnabled()){
239             logger.debug("id=" + id);
240         }
241         return id;
242     }
243     
244     /**
245      * Returns an error message indicating that the status code returned by a
246      * specific call to a service does not fall within a set of valid status
247      * codes for that service.
248      *
249      * @param serviceRequestType  A type of service request (e.g. CREATE, DELETE).
250      *
251      * @param statusCode  The invalid status code that was returned in the response,
252      *                    from submitting that type of request to the service.
253      *
254      * @return An error message.
255      */
256     public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
257         return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
258                 requestType.validStatusCodesAsString();
259     }
260
261
262     
263     /**
264      * Produces a default displayName from one or more supplied field(s).
265      * @see MaterialAuthorityDocumentModelHandler.prepareDefaultDisplayName() which
266      * duplicates this logic, until we define a service-general utils package
267      * that is neither client nor service specific.
268      * @param materialName  
269      * @return a display name
270      */
271     public static String prepareDefaultDisplayName(
272             String materialName ) {
273         StringBuilder newStr = new StringBuilder();
274             newStr.append(materialName);
275         return newStr.toString();
276     }
277     
278     public static List<MaterialTermGroup> getTermGroupInstance(String identifier) {
279         if (Tools.isBlank(identifier)) {
280             identifier = getGeneratedIdentifier();
281         }
282         List<MaterialTermGroup> terms = new ArrayList<MaterialTermGroup>();
283         MaterialTermGroup term = new MaterialTermGroup();
284         term.setTermDisplayName(identifier);
285         term.setTermName(identifier);
286         terms.add(term);
287         return terms;
288     }
289     
290     private static String getGeneratedIdentifier() {
291         return "id" + new Date().getTime(); 
292    }
293     
294 }