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;
32 import org.collectionspace.services.organization.ContactNameList;
33 import org.collectionspace.services.organization.FunctionList;
34 import org.collectionspace.services.organization.GroupList;
35 import org.collectionspace.services.organization.HistoryNoteList;
36 import org.collectionspace.services.organization.OrganizationsCommon;
37 import org.collectionspace.services.organization.OrgauthoritiesCommon;
38 import org.collectionspace.services.organization.OrgTermGroup;
39 import org.collectionspace.services.organization.OrgTermGroupList;
40 import org.jboss.resteasy.client.ClientResponse;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.collectionspace.services.organization.StructuredDateGroup;
46 * OrgAuthorityClientUtils.
48 public class OrgAuthorityClientUtils {
50 /** The Constant logger. */
51 private static final Logger logger =
52 LoggerFactory.getLogger(OrgAuthorityClientUtils.class);
53 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
56 * @param csid the id of the OrgAuthority
57 * @param client if null, creates a new client
61 public static String getAuthorityRefName(String csid, OrgAuthorityClient client) throws Exception{
63 client = new OrgAuthorityClient();
66 Response res = client.read(csid);
68 int statusCode = res.getStatus();
69 if (!READ_REQ.isValidStatusCode(statusCode) || statusCode != CollectionSpaceClientUtils.STATUS_OK) {
70 throw new RuntimeException("Invalid status code returned: "+statusCode);
72 //FIXME: remove the following try catch once Aron fixes signatures
74 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
75 OrgauthoritiesCommon orgAuthority =
76 (OrgauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
77 client.getCommonPartName(), OrgauthoritiesCommon.class);
78 if(orgAuthority==null) {
79 throw new RuntimeException("Null orgAuthority returned from service.");
81 return orgAuthority.getRefName();
82 } catch (Exception e) {
83 throw new RuntimeException(e);
91 * @param inAuthority the ID of the parent OrgAuthority
92 * @param csid the ID of the Organization
93 * @param client if null, creates a new client
97 public static String getOrgRefName(String inAuthority, String csid, OrgAuthorityClient client) throws Exception{
99 client = new OrgAuthorityClient();
102 Response res = client.readItem(inAuthority, csid);
104 int statusCode = res.getStatus();
105 if(!READ_REQ.isValidStatusCode(statusCode)
106 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
107 throw new RuntimeException("Invalid status code returned: "+statusCode);
109 //FIXME: remove the following try catch once Aron fixes signatures
111 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
112 OrganizationsCommon org =
113 (OrganizationsCommon) CollectionSpaceClientUtils.extractPart(input,
114 client.getItemCommonPartName(), OrganizationsCommon.class);
116 throw new RuntimeException("Null Organization returned from service.");
118 return org.getRefName();
119 } catch (Exception e) {
120 throw new RuntimeException(e);
128 * Creates the org authority instance.
130 * @param displayName the display name
131 * @param shortIdentifier the short Id
132 * @param headerLabel the header label
133 * @return the multipart output
135 public static PoxPayloadOut createOrgAuthorityInstance(
136 String displayName, String shortIdentifier, String headerLabel ) {
137 OrgauthoritiesCommon orgAuthority = new OrgauthoritiesCommon();
138 orgAuthority.setDisplayName(displayName);
139 orgAuthority.setShortIdentifier(shortIdentifier);
140 //String refName = createOrgAuthRefName(shortIdentifier, displayName);
141 //orgAuthority.setRefName(refName);
142 orgAuthority.setVocabType("OrgAuthority");
143 PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_PAYLOAD_NAME);
144 PayloadOutputPart commonPart = multipart.addPart(orgAuthority, MediaType.APPLICATION_XML_TYPE);
145 commonPart.setLabel(headerLabel);
147 if(logger.isDebugEnabled()){
148 logger.debug("to be created, orgAuthority common ",
149 orgAuthority, OrgauthoritiesCommon.class);
156 * Creates the item in authority.
158 * @param inAuthority the owning authority
159 * @param orgAuthorityRefName the owning Authority ref name
160 * @param orgInfo the org info. OrganizationJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
161 * @param client the client
164 public static String createItemInAuthority( String inAuthority,
165 String orgAuthorityRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
166 Map<String, List<String>> orgRepeatablesInfo, OrgAuthorityClient client) {
167 // Expected status code: 201 Created
168 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
169 // Type of service request being tested
170 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
172 String displayName = "";
173 if ((terms !=null) && (! terms.isEmpty())) {
174 displayName = terms.get(0).getTermDisplayName();
177 if(logger.isDebugEnabled()){
178 logger.debug("Import: Create Item: \""+displayName
179 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\"");
181 PoxPayloadOut multipart =
182 createOrganizationInstance(orgAuthorityRefName,
183 orgInfo, terms, orgRepeatablesInfo, client.getItemCommonPartName());
185 Response res = client.createItem(inAuthority, multipart);
188 int statusCode = res.getStatus();
190 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
191 throw new RuntimeException("Could not create Item: \""+orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
192 +"\" in orgAuthority: \"" + orgAuthorityRefName
193 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
195 if(statusCode != EXPECTED_STATUS_CODE) {
196 throw new RuntimeException("Unexpected Status when creating Item: \""+ orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
197 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\", Status:"+ statusCode);
200 result = extractId(res);
209 * Creates the organization instance.
211 * @param orgAuthRefName the owning Authority ref name
212 * @param orgInfo the org info
213 * @param headerLabel the header label
214 * @return the multipart output
216 public static PoxPayloadOut createOrganizationInstance(
217 String orgAuthRefName,
218 Map<String, String> orgInfo,
219 List<OrgTermGroup> terms,
220 String headerLabel) {
221 final Map<String, List<String>> EMPTY_ORG_REPEATABLES_INFO = new HashMap<String, List<String>>();
222 return createOrganizationInstance(orgAuthRefName, orgInfo, terms,
223 EMPTY_ORG_REPEATABLES_INFO, headerLabel);
227 * Creates the organization instance.
229 * @param orgAuthRefName the owning Authority ref name
230 * @param orgInfo the org info
231 * @param orgRepeatablesInfo names and values of repeatable scalar
232 * fields in the Organization record
233 * @param headerLabel the header label
234 * @return the multipart output
236 public static PoxPayloadOut createOrganizationInstance(
237 String orgAuthRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
238 Map<String, List<String>> orgRepeatablesInfo, String headerLabel){
239 OrganizationsCommon organization = new OrganizationsCommon();
240 String shortId = orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER);
241 if (shortId == null || shortId.isEmpty()) {
242 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
244 organization.setShortIdentifier(shortId);
246 List<String> values = null;
248 // Set values in the Term Information Group
249 OrgTermGroupList termList = new OrgTermGroupList();
250 if (terms == null || terms.isEmpty()) {
251 terms = getTermGroupInstance(getGeneratedIdentifier());
253 termList.getOrgTermGroup().addAll(terms);
254 organization.setOrgTermGroupList(termList);
256 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) {
257 ContactNameList contactsList = new ContactNameList();
258 List<String> contactNames = contactsList.getContactName();
259 contactNames.addAll(values);
260 organization.setContactNames(contactsList);
262 if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null) {
263 StructuredDateGroup foundingDate = new StructuredDateGroup();
264 foundingDate.setDateDisplayDate(value);
265 organization.setFoundingDateGroup(foundingDate);
267 if((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null) {
268 StructuredDateGroup dissolutionDate = new StructuredDateGroup();
269 dissolutionDate.setDateDisplayDate(value);
270 organization.setDissolutionDateGroup(dissolutionDate);
272 if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null)
273 organization.setFoundingPlace(value);
274 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) {
275 GroupList groupsList = new GroupList();
276 List<String> groups = groupsList.getGroup();
277 groups.addAll(values);
278 organization.setGroups(groupsList);
280 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) {
281 FunctionList functionsList = new FunctionList();
282 List<String> functions = functionsList.getFunction();
283 functions.addAll(values);
284 organization.setFunctions(functionsList);
286 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) {
287 HistoryNoteList historyNotesList = new HistoryNoteList();
288 List<String> historyNotes = historyNotesList.getHistoryNote();
289 historyNotes.addAll(values);
290 organization.setHistoryNotes(historyNotesList);
293 PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
294 PayloadOutputPart commonPart = multipart.addPart(organization,
295 MediaType.APPLICATION_XML_TYPE);
296 commonPart.setLabel(headerLabel);
298 if(logger.isDebugEnabled()){
299 logger.debug("to be created, organization common ", organization, OrganizationsCommon.class);
306 * Returns an error message indicating that the status code returned by a
307 * specific call to a service does not fall within a set of valid status
308 * codes for that service.
310 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
312 * @param statusCode The invalid status code that was returned in the response,
313 * from submitting that type of request to the service.
315 * @return An error message.
317 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
318 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
319 requestType.validStatusCodesAsString();
328 public static String extractId(Response res) {
329 MultivaluedMap<String, Object> mvm = res.getMetadata();
330 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
331 if(logger.isDebugEnabled()){
332 logger.info("extractId:uri=" + uri);
334 String[] segments = uri.split("/");
335 String id = segments[segments.length - 1];
336 if(logger.isDebugEnabled()){
337 logger.debug("id=" + id);
343 * Creates the org auth ref name.
345 * @param shortId the orgAuthority shortIdentifier
346 * @param displaySuffix displayName to be appended, if non-null
350 public static String createOrgAuthRefName(String shortId, String displaySuffix) {
351 String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name("
353 if(displaySuffix!=null&&!displaySuffix.isEmpty())
354 refName += "'"+displaySuffix+"'";
360 * Creates the organization ref name.
362 * @param orgAuthRefName the org auth ref name
363 * @param shortId the person shortIdentifier
364 * @param displaySuffix displayName to be appended, if non-null
368 public static String createOrganizationRefName(
369 String orgAuthRefName, String shortId, String displaySuffix) {
370 String refName = orgAuthRefName+":organization:name("+shortId+")";
371 if(displaySuffix!=null&&!displaySuffix.isEmpty())
372 refName += "'"+displaySuffix+"'";
378 * Produces a default displayName from the basic name and foundingPlace fields.
379 * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which
380 * duplicates this logic, until we define a service-general utils package
381 * that is neither client nor service specific.
383 * @param foundingPlace
387 public static String prepareDefaultDisplayName(
388 String shortName, String foundingPlace ) {
389 StringBuilder newStr = new StringBuilder();
390 final String sep = " ";
391 boolean firstAdded = false;
392 if(null != shortName ) {
393 newStr.append(shortName);
396 // Now we add the place
397 if(null != foundingPlace ) {
401 newStr.append(foundingPlace);
403 return newStr.toString();
406 public static List<OrgTermGroup> getTermGroupInstance(String identifier) {
407 if (Tools.isBlank(identifier)) {
408 identifier = getGeneratedIdentifier();
410 List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();
411 OrgTermGroup term = new OrgTermGroup();
412 term.setTermDisplayName(identifier);
413 term.setTermName(identifier);
418 private static String getGeneratedIdentifier() {
419 return "id" + new Date().getTime();