2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright © 2009 University of California, Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
17 package org.collectionspace.services.client;
19 import java.util.ArrayList;
20 import java.util.Date;
21 import java.util.HashMap;
22 import java.util.List;
25 import javax.ws.rs.core.MediaType;
26 import javax.ws.rs.core.MultivaluedMap;
27 import javax.ws.rs.core.Response;
29 import org.collectionspace.services.OrganizationJAXBSchema;
30 import org.collectionspace.services.client.test.ServiceRequestType;
31 import org.collectionspace.services.common.api.Tools;
33 import org.collectionspace.services.organization.StructuredDateGroup;
34 import org.collectionspace.services.organization.ContactNameList;
35 import org.collectionspace.services.organization.FunctionList;
36 import org.collectionspace.services.organization.GroupList;
37 import org.collectionspace.services.organization.HistoryNoteList;
38 import org.collectionspace.services.organization.OrganizationsCommon;
39 import org.collectionspace.services.organization.OrgauthoritiesCommon;
40 import org.collectionspace.services.organization.OrgTermGroup;
41 import org.collectionspace.services.organization.OrgTermGroupList;
43 import org.jboss.resteasy.client.ClientResponse;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * OrgAuthorityClientUtils.
50 public class OrgAuthorityClientUtils {
52 /** The Constant logger. */
53 private static final Logger logger =
54 LoggerFactory.getLogger(OrgAuthorityClientUtils.class);
55 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
58 * @param csid the id of the OrgAuthority
59 * @param client if null, creates a new client
63 public static String getAuthorityRefName(String csid, OrganizationClient client) throws Exception{
65 client = new OrganizationClient();
68 Response res = client.read(csid);
70 int statusCode = res.getStatus();
71 if (!READ_REQ.isValidStatusCode(statusCode) || statusCode != CollectionSpaceClientUtils.STATUS_OK) {
72 throw new RuntimeException("Invalid status code returned: "+statusCode);
74 //FIXME: remove the following try catch once Aron fixes signatures
76 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
77 OrgauthoritiesCommon orgAuthority =
78 (OrgauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
79 client.getCommonPartName(), OrgauthoritiesCommon.class);
80 if(orgAuthority==null) {
81 throw new RuntimeException("Null orgAuthority returned from service.");
83 return orgAuthority.getRefName();
84 } catch (Exception e) {
85 throw new RuntimeException(e);
93 * @param inAuthority the ID of the parent OrgAuthority
94 * @param csid the ID of the Organization
95 * @param client if null, creates a new client
99 public static String getOrgRefName(String inAuthority, String csid, OrganizationClient client) throws Exception{
100 if (client == null) {
101 client = new OrganizationClient();
104 Response res = client.readItem(inAuthority, csid);
106 int statusCode = res.getStatus();
107 if(!READ_REQ.isValidStatusCode(statusCode)
108 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
109 throw new RuntimeException("Invalid status code returned: "+statusCode);
111 //FIXME: remove the following try catch once Aron fixes signatures
113 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
114 OrganizationsCommon org =
115 (OrganizationsCommon) CollectionSpaceClientUtils.extractPart(input,
116 client.getItemCommonPartName(), OrganizationsCommon.class);
118 throw new RuntimeException("Null Organization returned from service.");
120 return org.getRefName();
121 } catch (Exception e) {
122 throw new RuntimeException(e);
130 * Creates the org authority instance.
132 * @param displayName the display name
133 * @param shortIdentifier the short Id
134 * @param headerLabel the header label
135 * @return the multipart output
137 public static PoxPayloadOut createOrgAuthorityInstance(
138 String displayName, String shortIdentifier, String headerLabel ) {
139 OrgauthoritiesCommon orgAuthority = new OrgauthoritiesCommon();
140 orgAuthority.setDisplayName(displayName);
141 orgAuthority.setShortIdentifier(shortIdentifier);
142 //String refName = createOrgAuthRefName(shortIdentifier, displayName);
143 //orgAuthority.setRefName(refName);
144 orgAuthority.setVocabType("OrgAuthority");
145 PoxPayloadOut multipart = new PoxPayloadOut(OrganizationClient.SERVICE_PAYLOAD_NAME);
146 PayloadOutputPart commonPart = multipart.addPart(orgAuthority, MediaType.APPLICATION_XML_TYPE);
147 commonPart.setLabel(headerLabel);
149 if(logger.isDebugEnabled()){
150 logger.debug("to be created, orgAuthority common ",
151 orgAuthority, OrgauthoritiesCommon.class);
158 * Creates the item in authority.
160 * @param inAuthority the owning authority
161 * @param orgAuthorityRefName the owning Authority ref name
162 * @param orgInfo the org info. OrganizationJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
163 * @param client the client
166 public static String createItemInAuthority( String inAuthority,
167 String orgAuthorityRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
168 Map<String, List<String>> orgRepeatablesInfo, OrganizationClient client) {
169 // Expected status code: 201 Created
170 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
171 // Type of service request being tested
172 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
174 String displayName = "";
175 if ((terms !=null) && (! terms.isEmpty())) {
176 displayName = terms.get(0).getTermDisplayName();
179 if(logger.isDebugEnabled()){
180 logger.debug("Import: Create Item: \""+displayName
181 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\"");
183 PoxPayloadOut multipart =
184 createOrganizationInstance(orgAuthorityRefName,
185 orgInfo, terms, orgRepeatablesInfo, client.getItemCommonPartName());
187 Response res = client.createItem(inAuthority, multipart);
190 int statusCode = res.getStatus();
192 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
193 throw new RuntimeException("Could not create Item: \""+orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
194 +"\" in orgAuthority: \"" + orgAuthorityRefName
195 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
197 if(statusCode != EXPECTED_STATUS_CODE) {
198 throw new RuntimeException("Unexpected Status when creating Item: \""+ orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
199 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\", Status:"+ statusCode);
202 result = extractId(res);
210 public static List<OrgTermGroup> getTermGroupInstance(String shortIdentifier, String displayName) {
211 if (Tools.isBlank(shortIdentifier)) {
212 shortIdentifier = getGeneratedIdentifier();
214 if (Tools.isBlank(shortIdentifier)) {
215 displayName = shortIdentifier;
218 List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();
219 OrgTermGroup term = new OrgTermGroup();
220 term.setTermDisplayName(displayName);
221 term.setTermName(shortIdentifier);
227 * Create a very simple Organization term -just a short ID and display name.
229 public static PoxPayloadOut createOrganizationInstance(String shortIdentifier, String displayName,
230 String headerLabel) {
231 List<OrgTermGroup> terms = getTermGroupInstance(shortIdentifier, displayName);
233 Map<String, String> orgInfo = new HashMap<String, String>();
234 orgInfo.put(OrganizationJAXBSchema.SHORT_IDENTIFIER, shortIdentifier);
236 final Map<String, List<String>> EMPTY_ORG_REPEATABLES_INFO = new HashMap<String, List<String>>();
238 return createOrganizationInstance(null, orgInfo, terms, EMPTY_ORG_REPEATABLES_INFO, headerLabel);
242 * Creates the organization instance.
244 * @param orgAuthRefName the owning Authority ref name
245 * @param orgInfo the org info
246 * @param headerLabel the header label
247 * @return the multipart output
249 public static PoxPayloadOut createOrganizationInstance(
250 String orgAuthRefName,
251 Map<String, String> orgInfo,
252 List<OrgTermGroup> terms,
253 String headerLabel) {
254 final Map<String, List<String>> EMPTY_ORG_REPEATABLES_INFO = new HashMap<String, List<String>>();
255 return createOrganizationInstance(orgAuthRefName, orgInfo, terms,
256 EMPTY_ORG_REPEATABLES_INFO, headerLabel);
260 * Creates the organization instance.
262 * @param orgAuthRefName the owning Authority ref name
263 * @param orgInfo the org info
264 * @param orgRepeatablesInfo names and values of repeatable scalar
265 * fields in the Organization record
266 * @param headerLabel the header label
267 * @return the multipart output
269 public static PoxPayloadOut createOrganizationInstance(
270 String orgAuthRefName,
271 Map<String, String> orgInfo,
272 List<OrgTermGroup> terms,
273 Map<String, List<String>> orgRepeatablesInfo,
274 String headerLabel) {
276 OrganizationsCommon organization = new OrganizationsCommon();
277 String shortId = orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER);
278 if (shortId == null || shortId.isEmpty()) {
279 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
281 organization.setShortIdentifier(shortId);
283 List<String> values = null;
285 // Set values in the Term Information Group
286 OrgTermGroupList termList = new OrgTermGroupList();
287 if (terms == null || terms.isEmpty()) {
288 terms = getTermGroupInstance(getGeneratedIdentifier());
290 termList.getOrgTermGroup().addAll(terms);
291 organization.setOrgTermGroupList(termList);
293 if ((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) {
294 ContactNameList contactsList = new ContactNameList();
295 List<String> contactNames = contactsList.getContactName();
296 contactNames.addAll(values);
297 organization.setContactNames(contactsList);
299 if ((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null) {
300 StructuredDateGroup foundingDate = new StructuredDateGroup();
301 foundingDate.setDateDisplayDate(value);
302 organization.setFoundingDateGroup(foundingDate);
304 if ((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null) {
305 StructuredDateGroup dissolutionDate = new StructuredDateGroup();
306 dissolutionDate.setDateDisplayDate(value);
307 organization.setDissolutionDateGroup(dissolutionDate);
309 if ((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null)
310 organization.setFoundingPlace(value);
311 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) {
312 GroupList groupsList = new GroupList();
313 List<String> groups = groupsList.getGroup();
314 groups.addAll(values);
315 organization.setGroups(groupsList);
317 if ((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) {
318 FunctionList functionsList = new FunctionList();
319 List<String> functions = functionsList.getFunction();
320 functions.addAll(values);
321 organization.setFunctions(functionsList);
323 if ((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) {
324 HistoryNoteList historyNotesList = new HistoryNoteList();
325 List<String> historyNotes = historyNotesList.getHistoryNote();
326 historyNotes.addAll(values);
327 organization.setHistoryNotes(historyNotesList);
330 PoxPayloadOut multipart = new PoxPayloadOut(OrganizationClient.SERVICE_ITEM_PAYLOAD_NAME);
331 PayloadOutputPart commonPart = multipart.addPart(organization,
332 MediaType.APPLICATION_XML_TYPE);
333 commonPart.setLabel(headerLabel);
335 if(logger.isDebugEnabled()){
336 logger.debug("to be created, organization common ", organization, OrganizationsCommon.class);
343 * Returns an error message indicating that the status code returned by a
344 * specific call to a service does not fall within a set of valid status
345 * codes for that service.
347 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
349 * @param statusCode The invalid status code that was returned in the response,
350 * from submitting that type of request to the service.
352 * @return An error message.
354 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
355 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
356 requestType.validStatusCodesAsString();
365 public static String extractId(Response res) {
366 MultivaluedMap<String, Object> mvm = res.getMetadata();
367 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
368 if(logger.isDebugEnabled()){
369 logger.info("extractId:uri=" + uri);
371 String[] segments = uri.split("/");
372 String id = segments[segments.length - 1];
373 if(logger.isDebugEnabled()){
374 logger.debug("id=" + id);
380 * Creates the org auth ref name.
382 * @param shortId the orgAuthority shortIdentifier
383 * @param displaySuffix displayName to be appended, if non-null
387 public static String createOrgAuthRefName(String shortId, String displaySuffix) {
388 String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name("
390 if(displaySuffix!=null&&!displaySuffix.isEmpty())
391 refName += "'"+displaySuffix+"'";
397 * Creates the organization ref name.
399 * @param orgAuthRefName the org auth ref name
400 * @param shortId the person shortIdentifier
401 * @param displaySuffix displayName to be appended, if non-null
405 public static String createOrganizationRefName(
406 String orgAuthRefName, String shortId, String displaySuffix) {
407 String refName = orgAuthRefName+":organization:name("+shortId+")";
408 if(displaySuffix!=null&&!displaySuffix.isEmpty())
409 refName += "'"+displaySuffix+"'";
415 * Produces a default displayName from the basic name and foundingPlace fields.
416 * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which
417 * duplicates this logic, until we define a service-general utils package
418 * that is neither client nor service specific.
420 * @param foundingPlace
424 public static String prepareDefaultDisplayName(
425 String shortName, String foundingPlace ) {
426 StringBuilder newStr = new StringBuilder();
427 final String sep = " ";
428 boolean firstAdded = false;
429 if(null != shortName ) {
430 newStr.append(shortName);
433 // Now we add the place
434 if(null != foundingPlace ) {
438 newStr.append(foundingPlace);
440 return newStr.toString();
443 public static List<OrgTermGroup> getTermGroupInstance(String identifier) {
444 if (Tools.isBlank(identifier)) {
445 identifier = getGeneratedIdentifier();
447 List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();
448 OrgTermGroup term = new OrgTermGroup();
449 term.setTermDisplayName(identifier);
450 term.setTermName(identifier);
455 private static String getGeneratedIdentifier() {
456 return "id" + new Date().getTime();