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;
24 import javax.ws.rs.core.MediaType;
25 import javax.ws.rs.core.MultivaluedMap;
26 import javax.ws.rs.core.Response;
27 import org.collectionspace.services.OrganizationJAXBSchema;
28 import org.collectionspace.services.client.test.ServiceRequestType;
29 import org.collectionspace.services.common.api.Tools;
30 import org.collectionspace.services.organization.ContactNameList;
31 import org.collectionspace.services.organization.FunctionList;
32 import org.collectionspace.services.organization.GroupList;
33 import org.collectionspace.services.organization.HistoryNoteList;
34 import org.collectionspace.services.organization.OrganizationsCommon;
35 import org.collectionspace.services.organization.OrgauthoritiesCommon;
36 import org.collectionspace.services.organization.OrgTermGroup;
37 import org.collectionspace.services.organization.OrgTermGroupList;
38 import org.jboss.resteasy.client.ClientResponse;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import org.collectionspace.services.organization.StructuredDateGroup;
45 * OrgAuthorityClientUtils.
47 public class OrgAuthorityClientUtils {
49 /** The Constant logger. */
50 private static final Logger logger =
51 LoggerFactory.getLogger(OrgAuthorityClientUtils.class);
52 private static final ServiceRequestType READ_REQ = ServiceRequestType.READ;
55 * @param csid the id of the OrgAuthority
56 * @param client if null, creates a new client
59 public static String getAuthorityRefName(String csid, OrgAuthorityClient client){
61 client = new OrgAuthorityClient();
64 Response res = client.read(csid);
66 int statusCode = res.getStatus();
67 if (!READ_REQ.isValidStatusCode(statusCode) || statusCode != CollectionSpaceClientUtils.STATUS_OK) {
68 throw new RuntimeException("Invalid status code returned: "+statusCode);
70 //FIXME: remove the following try catch once Aron fixes signatures
72 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
73 OrgauthoritiesCommon orgAuthority =
74 (OrgauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
75 client.getCommonPartName(), OrgauthoritiesCommon.class);
76 if(orgAuthority==null) {
77 throw new RuntimeException("Null orgAuthority returned from service.");
79 return orgAuthority.getRefName();
80 } catch (Exception e) {
81 throw new RuntimeException(e);
89 * @param inAuthority the ID of the parent OrgAuthority
90 * @param csid the ID of the Organization
91 * @param client if null, creates a new client
94 public static String getOrgRefName(String inAuthority, String csid, OrgAuthorityClient client){
96 client = new OrgAuthorityClient();
99 Response res = client.readItem(inAuthority, csid);
101 int statusCode = res.getStatus();
102 if(!READ_REQ.isValidStatusCode(statusCode)
103 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
104 throw new RuntimeException("Invalid status code returned: "+statusCode);
106 //FIXME: remove the following try catch once Aron fixes signatures
108 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
109 OrganizationsCommon org =
110 (OrganizationsCommon) CollectionSpaceClientUtils.extractPart(input,
111 client.getItemCommonPartName(), OrganizationsCommon.class);
113 throw new RuntimeException("Null Organization returned from service.");
115 return org.getRefName();
116 } catch (Exception e) {
117 throw new RuntimeException(e);
125 * Creates the org authority instance.
127 * @param displayName the display name
128 * @param shortIdentifier the short Id
129 * @param headerLabel the header label
130 * @return the multipart output
132 public static PoxPayloadOut createOrgAuthorityInstance(
133 String displayName, String shortIdentifier, String headerLabel ) {
134 OrgauthoritiesCommon orgAuthority = new OrgauthoritiesCommon();
135 orgAuthority.setDisplayName(displayName);
136 orgAuthority.setShortIdentifier(shortIdentifier);
137 //String refName = createOrgAuthRefName(shortIdentifier, displayName);
138 //orgAuthority.setRefName(refName);
139 orgAuthority.setVocabType("OrgAuthority");
140 PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_PAYLOAD_NAME);
141 PayloadOutputPart commonPart = multipart.addPart(orgAuthority, MediaType.APPLICATION_XML_TYPE);
142 commonPart.setLabel(headerLabel);
144 if(logger.isDebugEnabled()){
145 logger.debug("to be created, orgAuthority common ",
146 orgAuthority, OrgauthoritiesCommon.class);
153 * Creates the item in authority.
155 * @param inAuthority the owning authority
156 * @param orgAuthorityRefName the owning Authority ref name
157 * @param orgInfo the org info. OrganizationJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
158 * @param client the client
161 public static String createItemInAuthority( String inAuthority,
162 String orgAuthorityRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
163 Map<String, List<String>> orgRepeatablesInfo, OrgAuthorityClient client) {
164 // Expected status code: 201 Created
165 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
166 // Type of service request being tested
167 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
169 String displayName = "";
170 if ((terms !=null) && (! terms.isEmpty())) {
171 displayName = terms.get(0).getTermDisplayName();
174 if(logger.isDebugEnabled()){
175 logger.debug("Import: Create Item: \""+displayName
176 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\"");
178 PoxPayloadOut multipart =
179 createOrganizationInstance(orgAuthorityRefName,
180 orgInfo, terms, orgRepeatablesInfo, client.getItemCommonPartName());
182 Response res = client.createItem(inAuthority, multipart);
185 int statusCode = res.getStatus();
187 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
188 throw new RuntimeException("Could not create Item: \""+orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
189 +"\" in orgAuthority: \"" + orgAuthorityRefName
190 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
192 if(statusCode != EXPECTED_STATUS_CODE) {
193 throw new RuntimeException("Unexpected Status when creating Item: \""+ orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
194 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\", Status:"+ statusCode);
197 result = extractId(res);
206 * Creates the organization instance.
208 * @param orgAuthRefName the owning Authority ref name
209 * @param orgInfo the org info
210 * @param headerLabel the header label
211 * @return the multipart output
213 public static PoxPayloadOut createOrganizationInstance(
214 String orgAuthRefName,
215 Map<String, String> orgInfo,
216 List<OrgTermGroup> terms,
217 String headerLabel) {
218 final Map<String, List<String>> EMPTY_ORG_REPEATABLES_INFO = new HashMap<String, List<String>>();
219 return createOrganizationInstance(orgAuthRefName, orgInfo, terms,
220 EMPTY_ORG_REPEATABLES_INFO, headerLabel);
224 * Creates the organization instance.
226 * @param orgAuthRefName the owning Authority ref name
227 * @param orgInfo the org info
228 * @param orgRepeatablesInfo names and values of repeatable scalar
229 * fields in the Organization record
230 * @param headerLabel the header label
231 * @return the multipart output
233 public static PoxPayloadOut createOrganizationInstance(
234 String orgAuthRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
235 Map<String, List<String>> orgRepeatablesInfo, String headerLabel){
236 OrganizationsCommon organization = new OrganizationsCommon();
237 String shortId = orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER);
238 if (shortId == null || shortId.isEmpty()) {
239 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
241 organization.setShortIdentifier(shortId);
243 List<String> values = null;
245 // Set values in the Term Information Group
246 OrgTermGroupList termList = new OrgTermGroupList();
247 if (terms == null || terms.isEmpty()) {
248 terms = getTermGroupInstance(getGeneratedIdentifier());
250 termList.getOrgTermGroup().addAll(terms);
251 organization.setOrgTermGroupList(termList);
253 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) {
254 ContactNameList contactsList = new ContactNameList();
255 List<String> contactNames = contactsList.getContactName();
256 contactNames.addAll(values);
257 organization.setContactNames(contactsList);
259 if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null) {
260 StructuredDateGroup foundingDate = new StructuredDateGroup();
261 foundingDate.setDateDisplayDate(value);
262 organization.setFoundingDateGroup(foundingDate);
264 if((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null) {
265 StructuredDateGroup dissolutionDate = new StructuredDateGroup();
266 dissolutionDate.setDateDisplayDate(value);
267 organization.setDissolutionDateGroup(dissolutionDate);
269 if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null)
270 organization.setFoundingPlace(value);
271 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) {
272 GroupList groupsList = new GroupList();
273 List<String> groups = groupsList.getGroup();
274 groups.addAll(values);
275 organization.setGroups(groupsList);
277 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) {
278 FunctionList functionsList = new FunctionList();
279 List<String> functions = functionsList.getFunction();
280 functions.addAll(values);
281 organization.setFunctions(functionsList);
283 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) {
284 HistoryNoteList historyNotesList = new HistoryNoteList();
285 List<String> historyNotes = historyNotesList.getHistoryNote();
286 historyNotes.addAll(values);
287 organization.setHistoryNotes(historyNotesList);
290 PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
291 PayloadOutputPart commonPart = multipart.addPart(organization,
292 MediaType.APPLICATION_XML_TYPE);
293 commonPart.setLabel(headerLabel);
295 if(logger.isDebugEnabled()){
296 logger.debug("to be created, organization common ", organization, OrganizationsCommon.class);
303 * Returns an error message indicating that the status code returned by a
304 * specific call to a service does not fall within a set of valid status
305 * codes for that service.
307 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
309 * @param statusCode The invalid status code that was returned in the response,
310 * from submitting that type of request to the service.
312 * @return An error message.
314 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
315 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
316 requestType.validStatusCodesAsString();
325 public static String extractId(Response res) {
326 MultivaluedMap<String, Object> mvm = res.getMetadata();
327 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
328 if(logger.isDebugEnabled()){
329 logger.info("extractId:uri=" + uri);
331 String[] segments = uri.split("/");
332 String id = segments[segments.length - 1];
333 if(logger.isDebugEnabled()){
334 logger.debug("id=" + id);
340 * Creates the org auth ref name.
342 * @param shortId the orgAuthority shortIdentifier
343 * @param displaySuffix displayName to be appended, if non-null
347 public static String createOrgAuthRefName(String shortId, String displaySuffix) {
348 String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name("
350 if(displaySuffix!=null&&!displaySuffix.isEmpty())
351 refName += "'"+displaySuffix+"'";
357 * Creates the organization ref name.
359 * @param orgAuthRefName the org auth ref name
360 * @param shortId the person shortIdentifier
361 * @param displaySuffix displayName to be appended, if non-null
365 public static String createOrganizationRefName(
366 String orgAuthRefName, String shortId, String displaySuffix) {
367 String refName = orgAuthRefName+":organization:name("+shortId+")";
368 if(displaySuffix!=null&&!displaySuffix.isEmpty())
369 refName += "'"+displaySuffix+"'";
375 * Produces a default displayName from the basic name and foundingPlace fields.
376 * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which
377 * duplicates this logic, until we define a service-general utils package
378 * that is neither client nor service specific.
380 * @param foundingPlace
384 public static String prepareDefaultDisplayName(
385 String shortName, String foundingPlace ) {
386 StringBuilder newStr = new StringBuilder();
387 final String sep = " ";
388 boolean firstAdded = false;
389 if(null != shortName ) {
390 newStr.append(shortName);
393 // Now we add the place
394 if(null != foundingPlace ) {
398 newStr.append(foundingPlace);
400 return newStr.toString();
403 public static List<OrgTermGroup> getTermGroupInstance(String identifier) {
404 if (Tools.isBlank(identifier)) {
405 identifier = getGeneratedIdentifier();
407 List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();
408 OrgTermGroup term = new OrgTermGroup();
409 term.setTermDisplayName(identifier);
410 term.setTermName(identifier);
415 private static String getGeneratedIdentifier() {
416 return "id" + new Date().getTime();