1 package org.collectionspace.services.client;
4 import java.util.ArrayList;
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.WorkJAXBSchema;
13 import org.collectionspace.services.client.test.ServiceRequestType;
14 import org.collectionspace.services.common.api.Tools;
15 import org.collectionspace.services.work.WorkTermGroup;
16 import org.collectionspace.services.work.WorkTermGroupList;
17 import org.collectionspace.services.work.WorkauthoritiesCommon;
18 import org.collectionspace.services.work.WorksCommon;
19 import org.dom4j.DocumentException;
20 import org.jboss.resteasy.client.ClientResponse;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
24 public class WorkAuthorityClientUtils {
25 private static final Logger logger =
26 LoggerFactory.getLogger(WorkAuthorityClientUtils.class);
29 * Creates a new Work 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
35 public static PoxPayloadOut createWorkAuthorityInstance(
36 String displayName, String shortIdentifier, String headerLabel ) {
37 WorkauthoritiesCommon workAuthority = new WorkauthoritiesCommon();
38 workAuthority.setDisplayName(displayName);
39 workAuthority.setShortIdentifier(shortIdentifier);
40 String refName = createWorkAuthRefName(shortIdentifier, displayName);
41 workAuthority.setRefName(refName);
42 workAuthority.setVocabType("WorkAuthority"); //FIXME: REM - Should this really be hard-coded?
43 PoxPayloadOut multipart = new PoxPayloadOut(WorkAuthorityClient.SERVICE_PAYLOAD_NAME);
44 PayloadOutputPart commonPart = multipart.addPart(workAuthority, MediaType.APPLICATION_XML_TYPE);
45 commonPart.setLabel(headerLabel);
47 if(logger.isDebugEnabled()){
48 logger.debug("to be created, workAuthority common ",
49 workAuthority, WorkauthoritiesCommon.class);
56 * @param workRefName The proper refName for this authority
57 * @param workInfo the properties for the new Work. Can pass in one condition
58 * note and date string.
59 * @param headerLabel The common part label
60 * @return The PoxPayloadOut payload for the create call
62 public static PoxPayloadOut createWorkInstance(
63 String workAuthRefName, Map<String, String> workInfo,
64 List<WorkTermGroup> terms, String headerLabel){
65 WorksCommon work = new WorksCommon();
66 String shortId = workInfo.get(WorkJAXBSchema.SHORT_IDENTIFIER);
67 work.setShortIdentifier(shortId);
69 // Set values in the Term Information Group
70 WorkTermGroupList termList = new WorkTermGroupList();
71 if (terms == null || terms.isEmpty()) {
72 terms = getTermGroupInstance(getGeneratedIdentifier());
74 termList.getWorkTermGroup().addAll(terms);
75 work.setWorkTermGroupList(termList);
77 PoxPayloadOut multipart = new PoxPayloadOut(WorkAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
78 PayloadOutputPart commonPart = multipart.addPart(work,
79 MediaType.APPLICATION_XML_TYPE);
80 commonPart.setLabel(headerLabel);
82 if(logger.isDebugEnabled()){
83 logger.debug("to be created, work common ", work, WorksCommon.class);
90 * @param vcsid CSID of the authority to create a new work
91 * @param workAuthorityRefName The refName for the authority
92 * @param workMap the properties for the new Work
93 * @param client the service client
94 * @return the CSID of the new item
96 public static String createItemInAuthority(String vcsid,
97 String workAuthorityRefName, Map<String,String> workMap,
98 List<WorkTermGroup> terms, WorkAuthorityClient client ) {
99 // Expected status code: 201 Created
100 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
101 // Type of service request being tested
102 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
104 String displayName = "";
105 if ((terms !=null) && (! terms.isEmpty())) {
106 displayName = terms.get(0).getTermDisplayName();
108 if(logger.isDebugEnabled()){
109 logger.debug("Creating item with display name: \"" + displayName
110 +"\" in locationAuthority: \"" + vcsid +"\"");
112 PoxPayloadOut multipart =
113 createWorkInstance( workAuthorityRefName,
114 workMap, terms, client.getItemCommonPartName() );
116 ClientResponse<Response> res = client.createItem(vcsid, multipart);
118 int statusCode = res.getStatus();
120 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
121 throw new RuntimeException("Could not create Item: \""
122 +workMap.get(WorkJAXBSchema.SHORT_IDENTIFIER)
123 +"\" in workAuthority: \"" + workAuthorityRefName
124 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
126 if(statusCode != EXPECTED_STATUS_CODE) {
127 throw new RuntimeException("Unexpected Status when creating Item: \""
128 +workMap.get(WorkJAXBSchema.SHORT_IDENTIFIER)
129 +"\" in workAuthority: \"" + workAuthorityRefName +"\", Status:"+ statusCode);
131 newID = extractId(res);
133 res.releaseConnection();
139 public static PoxPayloadOut createWorkInstance(
140 String commonPartXML, String headerLabel) throws DocumentException {
141 PoxPayloadOut multipart = new PoxPayloadOut(WorkAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
142 PayloadOutputPart commonPart = multipart.addPart(commonPartXML,
143 MediaType.APPLICATION_XML_TYPE);
144 commonPart.setLabel(headerLabel);
146 if(logger.isDebugEnabled()){
147 logger.debug("to be created, work common ", commonPartXML);
153 public static String createItemInAuthority(String vcsid,
154 String commonPartXML,
155 WorkAuthorityClient 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;
161 PoxPayloadOut multipart =
162 createWorkInstance(commonPartXML, client.getItemCommonPartName());
164 ClientResponse<Response> res = client.createItem(vcsid, multipart);
166 int statusCode = res.getStatus();
168 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
169 throw new RuntimeException("Could not create Item: \""+commonPartXML
170 +"\" in workAuthority: \"" + vcsid
171 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
173 if(statusCode != EXPECTED_STATUS_CODE) {
174 throw new RuntimeException("Unexpected Status when creating Item: \""+commonPartXML
175 +"\" in workAuthority: \"" + vcsid +"\", Status:"+ statusCode);
177 newID = extractId(res);
179 res.releaseConnection();
186 * Creates the from xml file.
188 * @param fileName the file name
189 * @return new CSID as string
190 * @throws Exception the exception
192 private String createItemInAuthorityFromXmlFile(String vcsid, String commonPartFileName,
193 WorkAuthorityClient client) throws Exception {
194 byte[] b = FileUtils.readFileToByteArray(new File(commonPartFileName));
195 String commonPartXML = new String(b);
196 return createItemInAuthority(vcsid, commonPartXML, client );
200 * Creates the workAuthority ref name.
202 * @param shortId the workAuthority shortIdentifier
203 * @param displaySuffix displayName to be appended, if non-null
206 public static String createWorkAuthRefName(String shortId, String displaySuffix) {
207 String refName = "urn:cspace:org.collectionspace.demo:workauthority:name("
209 if(displaySuffix!=null&&!displaySuffix.isEmpty())
210 refName += "'"+displaySuffix+"'";
215 * Creates the work ref name.
217 * @param workAuthRefName the workAuthority ref name
218 * @param shortId the work shortIdentifier
219 * @param displaySuffix displayName to be appended, if non-null
222 public static String createWorkRefName(
223 String workAuthRefName, String shortId, String displaySuffix) {
224 String refName = workAuthRefName+":work:name("+shortId+")";
225 if(displaySuffix!=null&&!displaySuffix.isEmpty())
226 refName += "'"+displaySuffix+"'";
230 public static String extractId(ClientResponse<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);
236 String[] segments = uri.split("/");
237 String id = segments[segments.length - 1];
238 if(logger.isDebugEnabled()){
239 logger.debug("id=" + id);
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.
249 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
251 * @param statusCode The invalid status code that was returned in the response,
252 * from submitting that type of request to the service.
254 * @return An error message.
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();
264 * Produces a default displayName from one or more supplied field(s).
265 * @see WorkAuthorityDocumentModelHandler.prepareDefaultDisplayName() which
266 * duplicates this logic, until we define a service-general utils package
267 * that is neither client nor service specific.
269 * @return a display name
271 public static String prepareDefaultDisplayName(
273 StringBuilder newStr = new StringBuilder();
274 newStr.append(workName);
275 return newStr.toString();
278 public static List<WorkTermGroup> getTermGroupInstance(String identifier) {
279 if (Tools.isBlank(identifier)) {
280 identifier = getGeneratedIdentifier();
282 List<WorkTermGroup> terms = new ArrayList<WorkTermGroup>();
283 WorkTermGroup term = new WorkTermGroup();
284 term.setTermDisplayName(identifier);
285 term.setTermName(identifier);
290 private static String getGeneratedIdentifier() {
291 return "id" + new Date().getTime();