2 * OrgAuthorityClientUtils.java
\r
4 * {Purpose of This Class}
\r
6 * {Other Notes Relating to This Class (Optional)}
\r
9 * $LastChangedRevision$
\r
12 * This document is a part of the source code and related artifacts
\r
13 * for CollectionSpace, an open source collections management system
\r
14 * for museums and related institutions:
\r
16 * http://www.collectionspace.org
\r
17 * http://wiki.collectionspace.org
\r
19 * Copyright © 2009 {Contributing Institution}
\r
21 * Licensed under the Educational Community License (ECL), Version 2.0.
\r
22 * You may not use this file except in compliance with this License.
\r
24 * You may obtain a copy of the ECL 2.0 License at
\r
25 * https://source.collectionspace.org/collection-space/LICENSE.txt
\r
27 package org.collectionspace.services.client;
\r
29 import java.util.ArrayList;
\r
30 import java.util.HashMap;
\r
31 import java.util.List;
\r
32 import java.util.Map;
\r
34 import javax.ws.rs.core.MediaType;
\r
35 import javax.ws.rs.core.MultivaluedMap;
\r
36 import javax.ws.rs.core.Response;
\r
38 import org.collectionspace.services.OrganizationJAXBSchema;
\r
39 import org.collectionspace.services.client.test.BaseServiceTest;
\r
40 import org.collectionspace.services.client.test.ServiceRequestType;
\r
41 import org.collectionspace.services.organization.ContactNameList;
\r
42 import org.collectionspace.services.organization.FunctionList;
\r
43 import org.collectionspace.services.organization.GroupList;
\r
44 import org.collectionspace.services.organization.HistoryNoteList;
\r
45 import org.collectionspace.services.organization.OrganizationsCommon;
\r
46 import org.collectionspace.services.organization.OrgauthoritiesCommon;
\r
47 import org.collectionspace.services.organization.OrgTermGroup;
\r
48 import org.collectionspace.services.organization.OrgTermGroupList;
\r
49 import org.collectionspace.services.person.PersonauthoritiesCommon;
\r
50 import org.collectionspace.services.person.PersonsCommon;
\r
51 import org.jboss.resteasy.client.ClientResponse;
\r
52 import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
\r
53 import org.slf4j.Logger;
\r
54 import org.slf4j.LoggerFactory;
\r
57 * The Class OrgAuthorityClientUtils.
\r
59 public class OrgAuthorityClientUtils {
\r
61 /** The Constant logger. */
\r
62 private static final Logger logger =
\r
63 LoggerFactory.getLogger(OrgAuthorityClientUtils.class);
\r
64 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
\r
67 * @param csid the id of the OrgAuthority
\r
68 * @param client if null, creates a new client
\r
71 public static String getAuthorityRefName(String csid, OrgAuthorityClient client){
\r
73 client = new OrgAuthorityClient();
\r
74 ClientResponse<String> res = client.read(csid);
\r
76 int statusCode = res.getStatus();
\r
77 if(!READ_REQ.isValidStatusCode(statusCode)
\r
78 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
\r
79 throw new RuntimeException("Invalid status code returned: "+statusCode);
\r
81 //FIXME: remove the following try catch once Aron fixes signatures
\r
83 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
\r
84 OrgauthoritiesCommon orgAuthority =
\r
85 (OrgauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
\r
86 client.getCommonPartName(), OrgauthoritiesCommon.class);
\r
87 if(orgAuthority==null) {
\r
88 throw new RuntimeException("Null orgAuthority returned from service.");
\r
90 return orgAuthority.getRefName();
\r
91 } catch (Exception e) {
\r
92 throw new RuntimeException(e);
\r
95 res.releaseConnection();
\r
100 * @param inAuthority the ID of the parent OrgAuthority
\r
101 * @param csid the ID of the Organization
\r
102 * @param client if null, creates a new client
\r
105 public static String getOrgRefName(String inAuthority, String csid, OrgAuthorityClient client){
\r
107 client = new OrgAuthorityClient();
\r
108 ClientResponse<String> res = client.readItem(inAuthority, csid);
\r
110 int statusCode = res.getStatus();
\r
111 if(!READ_REQ.isValidStatusCode(statusCode)
\r
112 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
\r
113 throw new RuntimeException("Invalid status code returned: "+statusCode);
\r
115 //FIXME: remove the following try catch once Aron fixes signatures
\r
117 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
\r
118 OrganizationsCommon org =
\r
119 (OrganizationsCommon) CollectionSpaceClientUtils.extractPart(input,
\r
120 client.getItemCommonPartName(), OrganizationsCommon.class);
\r
122 throw new RuntimeException("Null Organization returned from service.");
\r
124 return org.getRefName();
\r
125 } catch (Exception e) {
\r
126 throw new RuntimeException(e);
\r
129 res.releaseConnection();
\r
134 * Creates the org authority instance.
\r
136 * @param displayName the display name
\r
137 * @param shortIdentifier the short Id
\r
138 * @param headerLabel the header label
\r
139 * @return the multipart output
\r
141 public static PoxPayloadOut createOrgAuthorityInstance(
\r
142 String displayName, String shortIdentifier, String headerLabel ) {
\r
143 OrgauthoritiesCommon orgAuthority = new OrgauthoritiesCommon();
\r
144 orgAuthority.setDisplayName(displayName);
\r
145 orgAuthority.setShortIdentifier(shortIdentifier);
\r
146 //String refName = createOrgAuthRefName(shortIdentifier, displayName);
\r
147 //orgAuthority.setRefName(refName);
\r
148 orgAuthority.setVocabType("OrgAuthority");
\r
149 PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_PAYLOAD_NAME);
\r
150 PayloadOutputPart commonPart = multipart.addPart(orgAuthority, MediaType.APPLICATION_XML_TYPE);
\r
151 commonPart.setLabel(headerLabel);
\r
153 if(logger.isDebugEnabled()){
\r
154 logger.debug("to be created, orgAuthority common ",
\r
155 orgAuthority, OrgauthoritiesCommon.class);
\r
162 * Creates the item in authority.
\r
164 * @param inAuthority the owning authority
\r
165 * @param orgAuthorityRefName the owning Authority ref name
\r
166 * @param orgInfo the org info. OrganizationJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
\r
167 * @param client the client
\r
168 * @return the string
\r
170 public static String createItemInAuthority( String inAuthority,
\r
171 String orgAuthorityRefName, List<OrgTermGroup> terms, Map<String, String> orgInfo,
\r
172 Map<String, List<String>> orgRepeatablesInfo, OrgAuthorityClient client) {
\r
173 // Expected status code: 201 Created
\r
174 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
\r
175 // Type of service request being tested
\r
176 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
\r
177 String displayName = createDisplayName(orgInfo);
\r
179 if(logger.isDebugEnabled()){
\r
180 logger.debug("Import: Create Item: \""+displayName
\r
181 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\"");
\r
183 PoxPayloadOut multipart =
\r
184 createOrganizationInstance(orgAuthorityRefName,
\r
185 orgInfo, terms, orgRepeatablesInfo, client.getItemCommonPartName());
\r
187 ClientResponse<Response> res = client.createItem(inAuthority, multipart);
\r
190 int statusCode = res.getStatus();
\r
192 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
\r
193 throw new RuntimeException("Could not create Item: \""+orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
\r
194 +"\" in orgAuthority: \"" + orgAuthorityRefName
\r
195 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
\r
197 if(statusCode != EXPECTED_STATUS_CODE) {
\r
198 throw new RuntimeException("Unexpected Status when creating Item: \""+ orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
\r
199 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\", Status:"+ statusCode);
\r
202 result = extractId(res);
\r
204 res.releaseConnection();
\r
211 * Creates the organization instance.
\r
213 * @param orgAuthRefName the owning Authority ref name
\r
214 * @param orgInfo the org info
\r
215 * @param headerLabel the header label
\r
216 * @return the multipart output
\r
218 public static PoxPayloadOut createOrganizationInstance(
\r
219 String orgAuthRefName, Map<String, String> orgInfo,
\r
220 List<OrgTermGroup> terms, String headerLabel){
\r
221 final Map<String, List<String>> EMPTY_ORG_REPEATABLES_INFO =
\r
222 new HashMap<String, List<String>>();
\r
223 return createOrganizationInstance(orgAuthRefName,
\r
224 orgInfo, terms, EMPTY_ORG_REPEATABLES_INFO, headerLabel);
\r
229 * Creates the organization instance.
\r
231 * @param orgAuthRefName the owning Authority ref name
\r
232 * @param orgInfo the org info
\r
233 * @param orgRepeatablesInfo names and values of repeatable scalar
\r
234 * fields in the Organization record
\r
235 * @param headerLabel the header label
\r
236 * @return the multipart output
\r
238 public static PoxPayloadOut createOrganizationInstance(
\r
239 String orgAuthRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
\r
240 Map<String, List<String>> orgRepeatablesInfo, String headerLabel){
\r
241 OrganizationsCommon organization = new OrganizationsCommon();
\r
242 String shortId = orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER);
\r
243 if (shortId == null || shortId.isEmpty()) {
\r
244 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
\r
246 organization.setShortIdentifier(shortId);
\r
247 String value = null;
\r
248 List<String> values = null;
\r
251 // Handle terms here
\r
253 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) {
\r
254 ContactNameList contactsList = new ContactNameList();
\r
255 List<String> contactNames = contactsList.getContactName();
\r
256 contactNames.addAll(values);
\r
257 organization.setContactNames(contactsList);
\r
259 if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null)
\r
260 organization.setFoundingDate(value);
\r
261 if((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null)
\r
262 organization.setDissolutionDate(value);
\r
263 if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null)
\r
264 organization.setFoundingPlace(value);
\r
265 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) {
\r
266 GroupList groupsList = new GroupList();
\r
267 List<String> groups = groupsList.getGroup();
\r
268 groups.addAll(values);
\r
269 organization.setGroups(groupsList);
\r
271 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) {
\r
272 FunctionList functionsList = new FunctionList();
\r
273 List<String> functions = functionsList.getFunction();
\r
274 functions.addAll(values);
\r
275 organization.setFunctions(functionsList);
\r
277 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) {
\r
278 HistoryNoteList historyNotesList = new HistoryNoteList();
\r
279 List<String> historyNotes = historyNotesList.getHistoryNote();
\r
280 historyNotes.addAll(values);
\r
281 organization.setHistoryNotes(historyNotesList);
\r
284 PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
\r
285 PayloadOutputPart commonPart = multipart.addPart(organization,
\r
286 MediaType.APPLICATION_XML_TYPE);
\r
287 commonPart.setLabel(headerLabel);
\r
289 if(logger.isDebugEnabled()){
\r
290 logger.debug("to be created, organization common ", organization, OrganizationsCommon.class);
\r
297 * Returns an error message indicating that the status code returned by a
\r
298 * specific call to a service does not fall within a set of valid status
\r
299 * codes for that service.
\r
301 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
\r
303 * @param statusCode The invalid status code that was returned in the response,
\r
304 * from submitting that type of request to the service.
\r
306 * @return An error message.
\r
308 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
\r
309 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
\r
310 requestType.validStatusCodesAsString();
\r
316 * @param res the res
\r
317 * @return the string
\r
319 public static String extractId(ClientResponse<Response> res) {
\r
320 MultivaluedMap<String, Object> mvm = res.getMetadata();
\r
321 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
\r
322 if(logger.isDebugEnabled()){
\r
323 logger.info("extractId:uri=" + uri);
\r
325 String[] segments = uri.split("/");
\r
326 String id = segments[segments.length - 1];
\r
327 if(logger.isDebugEnabled()){
\r
328 logger.debug("id=" + id);
\r
334 * Creates the org auth ref name.
\r
336 * @param shortId the orgAuthority shortIdentifier
\r
337 * @param displaySuffix displayName to be appended, if non-null
\r
338 * @return the string
\r
341 public static String createOrgAuthRefName(String shortId, String displaySuffix) {
\r
342 String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name("
\r
344 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
345 refName += "'"+displaySuffix+"'";
\r
351 * Creates the organization ref name.
\r
353 * @param orgAuthRefName the org auth ref name
\r
354 * @param shortId the person shortIdentifier
\r
355 * @param displaySuffix displayName to be appended, if non-null
\r
356 * @return the string
\r
359 public static String createOrganizationRefName(
\r
360 String orgAuthRefName, String shortId, String displaySuffix) {
\r
361 String refName = orgAuthRefName+":organization:name("+shortId+")";
\r
362 if(displaySuffix!=null&&!displaySuffix.isEmpty())
\r
363 refName += "'"+displaySuffix+"'";
\r
369 * Produces a default displayName from the basic name and foundingPlace fields.
\r
370 * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which
\r
371 * duplicates this logic, until we define a service-general utils package
\r
372 * that is neither client nor service specific.
\r
374 * @param foundingPlace
\r
376 * @throws Exception
\r
378 public static String prepareDefaultDisplayName(
\r
379 String shortName, String foundingPlace ) {
\r
380 StringBuilder newStr = new StringBuilder();
\r
381 final String sep = " ";
\r
382 boolean firstAdded = false;
\r
383 if(null != shortName ) {
\r
384 newStr.append(shortName);
\r
387 // Now we add the place
\r
388 if(null != foundingPlace ) {
\r
390 newStr.append(sep);
\r
392 newStr.append(foundingPlace);
\r
394 return newStr.toString();
\r
397 public static String createDisplayName(Map<String, String> orgInfo) {
\r
398 String displayName = orgInfo.get(OrganizationJAXBSchema.DISPLAY_NAME);
\r
399 String displayNameComputedStr = orgInfo.get(OrganizationJAXBSchema.DISPLAY_NAME_COMPUTED);
\r
400 boolean displayNameComputed = (displayNameComputedStr==null) || displayNameComputedStr.equalsIgnoreCase("true");
\r
401 if( displayName == null ) {
\r
402 if(!displayNameComputed) {
\r
403 throw new RuntimeException(
\r
404 "CreateItem: Must supply a displayName if displayNameComputed is set to false.");
\r
406 displayName = prepareDefaultDisplayName(
\r
407 orgInfo.get(OrganizationJAXBSchema.SHORT_NAME ),
\r
408 orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE ));
\r
410 return displayName;
\r