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();
97 Response res = client.readItem(inAuthority, csid);
99 int statusCode = res.getStatus();
100 if(!READ_REQ.isValidStatusCode(statusCode)
101 ||(statusCode != CollectionSpaceClientUtils.STATUS_OK)) {
102 throw new RuntimeException("Invalid status code returned: "+statusCode);
104 //FIXME: remove the following try catch once Aron fixes signatures
106 PoxPayloadIn input = new PoxPayloadIn(res.readEntity(String.class));
107 OrganizationsCommon org =
108 (OrganizationsCommon) CollectionSpaceClientUtils.extractPart(input,
109 client.getItemCommonPartName(), OrganizationsCommon.class);
111 throw new RuntimeException("Null Organization returned from service.");
113 return org.getRefName();
114 } catch (Exception e) {
115 throw new RuntimeException(e);
123 * Creates the org authority instance.
125 * @param displayName the display name
126 * @param shortIdentifier the short Id
127 * @param headerLabel the header label
128 * @return the multipart output
130 public static PoxPayloadOut createOrgAuthorityInstance(
131 String displayName, String shortIdentifier, String headerLabel ) {
132 OrgauthoritiesCommon orgAuthority = new OrgauthoritiesCommon();
133 orgAuthority.setDisplayName(displayName);
134 orgAuthority.setShortIdentifier(shortIdentifier);
135 //String refName = createOrgAuthRefName(shortIdentifier, displayName);
136 //orgAuthority.setRefName(refName);
137 orgAuthority.setVocabType("OrgAuthority");
138 PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_PAYLOAD_NAME);
139 PayloadOutputPart commonPart = multipart.addPart(orgAuthority, MediaType.APPLICATION_XML_TYPE);
140 commonPart.setLabel(headerLabel);
142 if(logger.isDebugEnabled()){
143 logger.debug("to be created, orgAuthority common ",
144 orgAuthority, OrgauthoritiesCommon.class);
151 * Creates the item in authority.
153 * @param inAuthority the owning authority
154 * @param orgAuthorityRefName the owning Authority ref name
155 * @param orgInfo the org info. OrganizationJAXBSchema.SHORT_IDENTIFIER is REQUIRED.
156 * @param client the client
159 public static String createItemInAuthority( String inAuthority,
160 String orgAuthorityRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
161 Map<String, List<String>> orgRepeatablesInfo, OrgAuthorityClient client) {
162 // Expected status code: 201 Created
163 int EXPECTED_STATUS_CODE = Response.Status.CREATED.getStatusCode();
164 // Type of service request being tested
165 ServiceRequestType REQUEST_TYPE = ServiceRequestType.CREATE;
167 String displayName = "";
168 if ((terms !=null) && (! terms.isEmpty())) {
169 displayName = terms.get(0).getTermDisplayName();
172 if(logger.isDebugEnabled()){
173 logger.debug("Import: Create Item: \""+displayName
174 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\"");
176 PoxPayloadOut multipart =
177 createOrganizationInstance(orgAuthorityRefName,
178 orgInfo, terms, orgRepeatablesInfo, client.getItemCommonPartName());
180 Response res = client.createItem(inAuthority, multipart);
183 int statusCode = res.getStatus();
185 if(!REQUEST_TYPE.isValidStatusCode(statusCode)) {
186 throw new RuntimeException("Could not create Item: \""+orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
187 +"\" in orgAuthority: \"" + orgAuthorityRefName
188 +"\" "+ invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
190 if(statusCode != EXPECTED_STATUS_CODE) {
191 throw new RuntimeException("Unexpected Status when creating Item: \""+ orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER)
192 +"\" in orgAuthority: \"" + orgAuthorityRefName +"\", Status:"+ statusCode);
195 result = extractId(res);
204 * Creates the organization instance.
206 * @param orgAuthRefName the owning Authority ref name
207 * @param orgInfo the org info
208 * @param headerLabel the header label
209 * @return the multipart output
211 public static PoxPayloadOut createOrganizationInstance(
212 String orgAuthRefName,
213 Map<String, String> orgInfo,
214 List<OrgTermGroup> terms,
215 String headerLabel) {
216 final Map<String, List<String>> EMPTY_ORG_REPEATABLES_INFO = new HashMap<String, List<String>>();
217 return createOrganizationInstance(orgAuthRefName, orgInfo, terms,
218 EMPTY_ORG_REPEATABLES_INFO, headerLabel);
222 * Creates the organization instance.
224 * @param orgAuthRefName the owning Authority ref name
225 * @param orgInfo the org info
226 * @param orgRepeatablesInfo names and values of repeatable scalar
227 * fields in the Organization record
228 * @param headerLabel the header label
229 * @return the multipart output
231 public static PoxPayloadOut createOrganizationInstance(
232 String orgAuthRefName, Map<String, String> orgInfo, List<OrgTermGroup> terms,
233 Map<String, List<String>> orgRepeatablesInfo, String headerLabel){
234 OrganizationsCommon organization = new OrganizationsCommon();
235 String shortId = orgInfo.get(OrganizationJAXBSchema.SHORT_IDENTIFIER);
236 if (shortId == null || shortId.isEmpty()) {
237 throw new IllegalArgumentException("shortIdentifier cannot be null or empty");
239 organization.setShortIdentifier(shortId);
241 List<String> values = null;
243 // Set values in the Term Information Group
244 OrgTermGroupList termList = new OrgTermGroupList();
245 if (terms == null || terms.isEmpty()) {
246 terms = getTermGroupInstance(getGeneratedIdentifier());
248 termList.getOrgTermGroup().addAll(terms);
249 organization.setOrgTermGroupList(termList);
251 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.CONTACT_NAMES))!=null) {
252 ContactNameList contactsList = new ContactNameList();
253 List<String> contactNames = contactsList.getContactName();
254 contactNames.addAll(values);
255 organization.setContactNames(contactsList);
257 if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_DATE))!=null) {
258 StructuredDateGroup foundingDate = new StructuredDateGroup();
259 foundingDate.setDateDisplayDate(value);
260 organization.setFoundingDateGroup(foundingDate);
262 if((value = (String)orgInfo.get(OrganizationJAXBSchema.DISSOLUTION_DATE))!=null) {
263 StructuredDateGroup dissolutionDate = new StructuredDateGroup();
264 dissolutionDate.setDateDisplayDate(value);
265 organization.setDissolutionDateGroup(dissolutionDate);
267 if((value = (String)orgInfo.get(OrganizationJAXBSchema.FOUNDING_PLACE))!=null)
268 organization.setFoundingPlace(value);
269 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.GROUPS))!=null) {
270 GroupList groupsList = new GroupList();
271 List<String> groups = groupsList.getGroup();
272 groups.addAll(values);
273 organization.setGroups(groupsList);
275 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.FUNCTIONS))!=null) {
276 FunctionList functionsList = new FunctionList();
277 List<String> functions = functionsList.getFunction();
278 functions.addAll(values);
279 organization.setFunctions(functionsList);
281 if((values = (List<String>)orgRepeatablesInfo.get(OrganizationJAXBSchema.HISTORY_NOTES))!=null) {
282 HistoryNoteList historyNotesList = new HistoryNoteList();
283 List<String> historyNotes = historyNotesList.getHistoryNote();
284 historyNotes.addAll(values);
285 organization.setHistoryNotes(historyNotesList);
288 PoxPayloadOut multipart = new PoxPayloadOut(OrgAuthorityClient.SERVICE_ITEM_PAYLOAD_NAME);
289 PayloadOutputPart commonPart = multipart.addPart(organization,
290 MediaType.APPLICATION_XML_TYPE);
291 commonPart.setLabel(headerLabel);
293 if(logger.isDebugEnabled()){
294 logger.debug("to be created, organization common ", organization, OrganizationsCommon.class);
301 * Returns an error message indicating that the status code returned by a
302 * specific call to a service does not fall within a set of valid status
303 * codes for that service.
305 * @param serviceRequestType A type of service request (e.g. CREATE, DELETE).
307 * @param statusCode The invalid status code that was returned in the response,
308 * from submitting that type of request to the service.
310 * @return An error message.
312 public static String invalidStatusCodeMessage(ServiceRequestType requestType, int statusCode) {
313 return "Status code '" + statusCode + "' in response is NOT within the expected set: " +
314 requestType.validStatusCodesAsString();
323 public static String extractId(Response res) {
324 MultivaluedMap<String, Object> mvm = res.getMetadata();
325 String uri = (String) ((ArrayList<Object>) mvm.get("Location")).get(0);
326 if(logger.isDebugEnabled()){
327 logger.info("extractId:uri=" + uri);
329 String[] segments = uri.split("/");
330 String id = segments[segments.length - 1];
331 if(logger.isDebugEnabled()){
332 logger.debug("id=" + id);
338 * Creates the org auth ref name.
340 * @param shortId the orgAuthority shortIdentifier
341 * @param displaySuffix displayName to be appended, if non-null
345 public static String createOrgAuthRefName(String shortId, String displaySuffix) {
346 String refName = "urn:cspace:org.collectionspace.demo:orgauthority:name("
348 if(displaySuffix!=null&&!displaySuffix.isEmpty())
349 refName += "'"+displaySuffix+"'";
355 * Creates the organization ref name.
357 * @param orgAuthRefName the org auth ref name
358 * @param shortId the person shortIdentifier
359 * @param displaySuffix displayName to be appended, if non-null
363 public static String createOrganizationRefName(
364 String orgAuthRefName, String shortId, String displaySuffix) {
365 String refName = orgAuthRefName+":organization:name("+shortId+")";
366 if(displaySuffix!=null&&!displaySuffix.isEmpty())
367 refName += "'"+displaySuffix+"'";
373 * Produces a default displayName from the basic name and foundingPlace fields.
374 * @see OrgAuthorityDocumentModelHandler.prepareDefaultDisplayName() which
375 * duplicates this logic, until we define a service-general utils package
376 * that is neither client nor service specific.
378 * @param foundingPlace
382 public static String prepareDefaultDisplayName(
383 String shortName, String foundingPlace ) {
384 StringBuilder newStr = new StringBuilder();
385 final String sep = " ";
386 boolean firstAdded = false;
387 if(null != shortName ) {
388 newStr.append(shortName);
391 // Now we add the place
392 if(null != foundingPlace ) {
396 newStr.append(foundingPlace);
398 return newStr.toString();
401 public static List<OrgTermGroup> getTermGroupInstance(String identifier) {
402 if (Tools.isBlank(identifier)) {
403 identifier = getGeneratedIdentifier();
405 List<OrgTermGroup> terms = new ArrayList<OrgTermGroup>();
406 OrgTermGroup term = new OrgTermGroup();
407 term.setTermDisplayName(identifier);
408 term.setTermName(identifier);
413 private static String getGeneratedIdentifier() {
414 return "id" + new Date().getTime();