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();
62 ClientResponse<String> res = client.read(csid);
64 int statusCode = res.getStatus();
65 if(!READ_REQ.isValidStatusCode(statusCode)
66 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
67 throw new RuntimeException("Invalid status code returned: "+statusCode);
69 //FIXME: remove the following try catch once Aron fixes signatures
71 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
72 OrgauthoritiesCommon orgAuthority =
73 (OrgauthoritiesCommon) CollectionSpaceClientUtils.extractPart(input,
74 client.getCommonPartName(), OrgauthoritiesCommon.class);
75 if(orgAuthority==null) {
76 throw new RuntimeException("Null orgAuthority returned from service.");
78 return orgAuthority.getRefName();
79 } catch (Exception e) {
80 throw new RuntimeException(e);
83 res.releaseConnection();
88 * @param inAuthority the ID of the parent OrgAuthority
89 * @param csid the ID of the Organization
90 * @param client if null, creates a new client
93 public static String getOrgRefName(String inAuthority, String csid, OrgAuthorityClient client){
95 client = new OrgAuthorityClient();
96 ClientResponse<String> res = client.readItem(inAuthority, csid);
98 int statusCode = res.getStatus();
99 if(!READ_REQ.isValidStatusCode(statusCode)
100 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
101 throw new RuntimeException("Invalid status code returned: "+statusCode);
103 //FIXME: remove the following try catch once Aron fixes signatures
105 PoxPayloadIn input = new PoxPayloadIn(res.getEntity());
106 OrganizationsCommon org =
107 (OrganizationsCommon) CollectionSpaceClientUtils.extractPart(input,
108 client.getItemCommonPartName(), OrganizationsCommon.class);
110 throw new RuntimeException("Null Organization returned from service.");
112 return org.getRefName();
113 } catch (Exception e) {
114 throw new RuntimeException(e);
117 res.releaseConnection();
122 * Creates the org authority instance.
124 * @param displayName the display name
125 * @param shortIdentifier the short Id
126 * @param headerLabel the header label
127 * @return the multipart output
129 public static PoxPayloadOut createOrgAuthorityInstance(
130 String displayName, String shortIdentifier, String headerLabel ) {
131 OrgauthoritiesCommon orgAuthority = new OrgauthoritiesCommon();
132 orgAuthority.setDisplayName(displayName);
133 orgAuthority.setShortIdentifier(shortIdentifier);
134 //String refName = createOrgAuthRefName(shortIdentifier, displayName);
135 //orgAuthority.setRefName(refName);
136 orgAuthority.setVocabType("OrgAuthority");
137 PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_PAYLOAD_NAME);
138 PayloadOutputPart commonPart = multipart.addPart(orgAuthority, MediaType.APPLICATION_XML_TYPE);
139 commonPart.setLabel(headerLabel);
141 if(logger.isDebugEnabled()){
142 logger.debug("to be created, orgAuthority common ",
143 orgAuthority, OrgauthoritiesCommon.class);
150 * Creates the item in authority.
152 * @param inAuthority the owning authority
153 * @param orgAuthorityRefName the owning Authority ref name
154 * @param orgInfo the org info. OrganizationJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
155 * @param client the client
158 public static String createItemInAuthority( String inAuthority,
159 String orgAuthorityRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
160 Map<String, List<String>> orgRepeatablesInfo, OrgAuthorityClient client) {
161 // Expected status code: 201 Created
162 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
163 // Type of service request being tested
164 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
166 String displayName = "";
167 if ((terms !=null) && (! terms.isEmpty())) {
168 displayName = terms.get(0).getTermDisplayName();
171 if(logger.isDebugEnabled()){
172 logger.debug("Import: Create Item: \""+displayName
173 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\"");
175 PoxPayloadOut multipart =
176 createOrganizationInstance(orgAuthorityRefName,
177 orgInfo, terms, orgRepeatablesInfo, client.getItemCommonPartName());
179 ClientResponse<Response> res = client.createItem(inAuthority, multipart);
182 int statusCode = res.getStatus();
184 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
185 throw new RuntimeException("Could not create Item: \""+orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
186 +"\" in orgAuthority: \"" + orgAuthorityRefName
187 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
189 if(statusCode != EXPECTED_STATUS_CODE) {
190 throw new RuntimeException("Unexpected Status when creating Item: \""+ orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
191 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\", Status:"+ statusCode);
194 result = extractId(res);
196 res.releaseConnection();
203 * Creates the organization instance.
205 * @param orgAuthRefName the owning Authority ref name
206 * @param orgInfo the org info
207 * @param headerLabel the header label
208 * @return the multipart output
210 public static PoxPayloadOut createOrganizationInstance(
211 String orgAuthRefName,
212 Map<String, String> orgInfo,
213 List<OrgTermGroup> terms,
214 String headerLabel) {
215 final Map<String, List<String>> EMPTY_ORG_REPEATABLES_INFO = new HashMap<String, List<String>>();
216 return createOrganizationInstance(orgAuthRefName, orgInfo, terms,
217 EMPTY_ORG_REPEATABLES_INFO, headerLabel);
221 * Creates the organization instance.
223 * @param orgAuthRefName the owning Authority ref name
224 * @param orgInfo the org info
225 * @param orgRepeatablesInfo names and values of repeatable scalar
226 * fields in the Organization record
227 * @param headerLabel the header label
228 * @return the multipart output
230 public static PoxPayloadOut createOrganizationInstance(
231 String orgAuthRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
232 Map<String, List<String>> orgRepeatablesInfo, String headerLabel){
233 OrganizationsCommon organization = new OrganizationsCommon();
234 String shortId = orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER);
235 if (shortId == null || shortId.isEmpty()) {
236 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
238 organization.setShortIdentifier(shortId);
240 List<String> values = null;
242 // Set values in the Term Information Group
243 OrgTermGroupList termList = new OrgTermGroupList();
244 if (terms == null || terms.isEmpty()) {
245 terms = getTermGroupInstance(getGeneratedIdentifier());
247 termList.getOrgTermGroup().addAll(terms);
248 organization.setOrgTermGroupList(termList);
250 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) {
251 ContactNameList contactsList = new ContactNameList();
252 List<String> contactNames = contactsList.getContactName();
253 contactNames.addAll(values);
254 organization.setContactNames(contactsList);
256 if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null) {
257 StructuredDateGroup foundingDate = new StructuredDateGroup();
258 foundingDate.setDateDisplayDate(value);
259 organization.setFoundingDateGroup(foundingDate);
261 if((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null) {
262 StructuredDateGroup dissolutionDate = new StructuredDateGroup();
263 dissolutionDate.setDateDisplayDate(value);
264 organization.setDissolutionDateGroup(dissolutionDate);
266 if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null)
267 organization.setFoundingPlace(value);
268 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) {
269 GroupList groupsList = new GroupList();
270 List<String> groups = groupsList.getGroup();
271 groups.addAll(values);
272 organization.setGroups(groupsList);
274 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) {
275 FunctionList functionsList = new FunctionList();
276 List<String> functions = functionsList.getFunction();
277 functions.addAll(values);
278 organization.setFunctions(functionsList);
280 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) {
281 HistoryNoteList historyNotesList = new HistoryNoteList();
282 List<String> historyNotes = historyNotesList.getHistoryNote();
283 historyNotes.addAll(values);
284 organization.setHistoryNotes(historyNotesList);
287 PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
288 PayloadOutputPart commonPart = multipart.addPart(organization,
289 MediaType.APPLICATION_XML_TYPE);
290 commonPart.setLabel(headerLabel);
292 if(logger.isDebugEnabled()){
293 logger.debug("to be created, organization common ", organization, OrganizationsCommon.class);
300 * Returns an error message indicating that the status code returned by a
301 * specific call to a service does not fall within a set of valid status
302 * codes for that service.
304 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
306 * @param statusCode The invalid status code that was returned in the response,
307 * from submitting that type of request to the service.
309 * @return An error message.
311 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
312 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
313 requestType.validStatusCodesAsString();
322 public static String extractId(ClientResponse<Response> res) {
323 MultivaluedMap<String, Object> mvm = res.getMetadata();
324 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
325 if(logger.isDebugEnabled()){
326 logger.info("extractId:uri=" + uri);
328 String[] segments = uri.split("/");
329 String id = segments[segments.length - 1];
330 if(logger.isDebugEnabled()){
331 logger.debug("id=" + id);
337 * Creates the org auth ref name.
339 * @param shortId the orgAuthority shortIdentifier
340 * @param displaySuffix displayName to be appended, if non-null
344 public static String createOrgAuthRefName(String shortId, String displaySuffix) {
345 String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name("
347 if(displaySuffix!=null&&!displaySuffix.isEmpty())
348 refName += "'"+displaySuffix+"'";
354 * Creates the organization ref name.
356 * @param orgAuthRefName the org auth ref name
357 * @param shortId the person shortIdentifier
358 * @param displaySuffix displayName to be appended, if non-null
362 public static String createOrganizationRefName(
363 String orgAuthRefName, String shortId, String displaySuffix) {
364 String refName = orgAuthRefName+":organization:name("+shortId+")";
365 if(displaySuffix!=null&&!displaySuffix.isEmpty())
366 refName += "'"+displaySuffix+"'";
372 * Produces a default displayName from the basic name and foundingPlace fields.
373 * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which
374 * duplicates this logic, until we define a service-general utils package
375 * that is neither client nor service specific.
377 * @param foundingPlace
381 public static String prepareDefaultDisplayName(
382 String shortName, String foundingPlace ) {
383 StringBuilder newStr = new StringBuilder();
384 final String sep = " ";
385 boolean firstAdded = false;
386 if(null != shortName ) {
387 newStr.append(shortName);
390 // Now we add the place
391 if(null != foundingPlace ) {
395 newStr.append(foundingPlace);
397 return newStr.toString();
400 public static List<OrgTermGroup> getTermGroupInstance(String identifier) {
401 if (Tools.isBlank(identifier)) {
402 identifier = getGeneratedIdentifier();
404 List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();
405 OrgTermGroup term = new OrgTermGroup();
406 term.setTermDisplayName(identifier);
407 term.setTermName(identifier);
412 private static String getGeneratedIdentifier() {
413 return "id" + new Date().getTime();