1 package org.collectionspace.services.nuxeo.elasticsearch;
3 import java.io.IOException;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.Calendar;
7 import java.util.Collections;
8 import java.util.GregorianCalendar;
9 import java.util.HashSet;
10 import java.util.Iterator;
11 import java.util.List;
15 import javax.ws.rs.core.HttpHeaders;
17 import org.apache.commons.lang3.StringUtils;
18 import org.codehaus.jackson.JsonGenerator;
19 import org.codehaus.jackson.JsonNode;
20 import org.codehaus.jackson.map.ObjectMapper;
21 import org.codehaus.jackson.node.IntNode;
22 import org.codehaus.jackson.node.ObjectNode;
23 import org.codehaus.jackson.node.TextNode;
24 import org.collectionspace.services.common.api.RefNameUtils;
25 import org.nuxeo.ecm.automation.jaxrs.io.documents.JsonESDocumentWriter;
26 import org.nuxeo.ecm.core.api.CoreSession;
27 import org.nuxeo.ecm.core.api.DocumentModel;
28 import org.nuxeo.ecm.core.api.DocumentModelList;
30 public class DefaultESDocumentWriter extends JsonESDocumentWriter {
31 private static ObjectMapper objectMapper = new ObjectMapper();
34 public void writeDoc(JsonGenerator jg, DocumentModel doc, String[] schemas,
35 Map<String, String> contextParameters, HttpHeaders headers)
38 ObjectNode denormValues = getDenormValues(doc);
40 jg.writeStartObject();
42 writeSystemProperties(jg, doc);
43 writeSchemas(jg, doc, schemas);
44 writeContextParameters(jg, doc, contextParameters);
45 writeDenormValues(jg, doc, denormValues);
51 public ObjectNode getDenormValues(DocumentModel doc) {
52 ObjectNode denormValues = objectMapper.createObjectNode();
53 String docType = doc.getType();
55 if (docType.startsWith("CollectionObject")) {
56 CoreSession session = doc.getCoreSession();
57 String csid = doc.getName();
58 String tenantId = (String) doc.getProperty("collectionspace_core", "tenantId");
60 denormMediaRecords(session, csid, tenantId, denormValues);
61 denormAcquisitionRecords(session, csid, tenantId, denormValues);
62 denormExhibitionRecords(session, csid, tenantId, denormValues);
63 denormConceptFields(doc, denormValues);
64 denormMaterialFields(doc, denormValues);
65 denormObjectNameFields(doc, denormValues);
67 // Compute the title of the record for the public browser, and store it so that it can
68 // be used for sorting ES query results.
70 String title = computeTitle(doc);
73 denormValues.put("title", title);
76 // Create a list of production years from the production date structured dates.
78 List<Map<String, Object>> prodDateGroupList = (List<Map<String, Object>>) doc.getProperty("collectionobjects_common", "objectProductionDateGroupList");
80 denormValues.putArray("prodYears").addAll(structDatesToYearNodes(prodDateGroupList));
86 public void writeDenormValues(JsonGenerator jg, DocumentModel doc, ObjectNode denormValues) throws IOException {
87 if (denormValues != null && denormValues.size() > 0) {
88 if (jg.getCodec() == null) {
89 jg.setCodec(objectMapper);
92 Iterator<Map.Entry<String, JsonNode>> entries = denormValues.getFields();
94 while (entries.hasNext()) {
95 Map.Entry<String, JsonNode> entry = entries.next();
97 jg.writeFieldName("collectionspace_denorm:" + entry.getKey());
98 jg.writeTree(entry.getValue());
103 private void denormMediaRecords(CoreSession session, String csid, String tenantId, ObjectNode denormValues) {
104 // Store the csid and alt text of media records that are related to this object.
106 String relatedRecordQuery = String.format("SELECT * FROM Relation WHERE relations_common:subjectCsid = '%s' AND relations_common:objectDocumentType = 'Media' AND ecm:currentLifeCycleState = 'project' AND collectionspace_core:tenantId = '%s'", csid, tenantId);
107 DocumentModelList relationDocs = session.query(relatedRecordQuery);
108 List<JsonNode> mediaCsids = new ArrayList<JsonNode>();
109 List<JsonNode> mediaAltTexts = new ArrayList<JsonNode>();
111 if (relationDocs.size() > 0) {
112 Iterator<DocumentModel> iterator = relationDocs.iterator();
114 while (iterator.hasNext()) {
115 DocumentModel relationDoc = iterator.next();
116 String mediaCsid = (String) relationDoc.getProperty("relations_common", "objectCsid");
117 DocumentModel mediaDoc = getRecordByCsid(session, tenantId, "Media", mediaCsid);
119 if (isMediaPublished(mediaDoc)) {
120 mediaCsids.add(new TextNode(mediaCsid));
122 String altText = (String) mediaDoc.getProperty("media_common", "altText");
124 if (altText == null) {
128 mediaAltTexts.add(new TextNode(altText));
133 denormValues.putArray("mediaCsid").addAll(mediaCsids);
134 denormValues.putArray("mediaAltText").addAll(mediaAltTexts);
135 denormValues.put("hasMedia", mediaCsids.size() > 0);
138 private void denormAcquisitionRecords(CoreSession session, String csid, String tenantId, ObjectNode denormValues) {
139 // Store the credit lines of acquisition records that are related to this object.
141 String relatedRecordQuery = String.format("SELECT * FROM Relation WHERE relations_common:subjectCsid = '%s' AND relations_common:objectDocumentType = 'Acquisition' AND ecm:currentLifeCycleState = 'project' AND collectionspace_core:tenantId = '%s'", csid, tenantId);
142 DocumentModelList relationDocs = session.query(relatedRecordQuery);
143 List<JsonNode> creditLines = new ArrayList<JsonNode>();
145 if (relationDocs.size() > 0) {
146 Iterator<DocumentModel> iterator = relationDocs.iterator();
148 while (iterator.hasNext()) {
149 DocumentModel relationDoc = iterator.next();
150 String acquisitionCsid = (String) relationDoc.getProperty("relations_common", "objectCsid");
151 String creditLine = getCreditLine(session, tenantId, acquisitionCsid);
153 if (creditLine != null && creditLine.length() > 0) {
154 creditLines.add(new TextNode(creditLine));
159 denormValues.putArray("creditLine").addAll(creditLines);
162 private void denormExhibitionRecords(CoreSession session, String csid, String tenantId, ObjectNode denormValues) {
163 // Store the title, general note, and curatorial note of exhibition records that are published, and related to this object.
165 String relatedRecordQuery = String.format("SELECT * FROM Relation WHERE relations_common:subjectCsid = '%s' AND relations_common:objectDocumentType = 'Exhibition' AND ecm:currentLifeCycleState = 'project' AND collectionspace_core:tenantId = '%s'", csid, tenantId);
166 DocumentModelList relationDocs = session.query(relatedRecordQuery);
167 List<JsonNode> exhibitions = new ArrayList<JsonNode>();
169 if (relationDocs.size() > 0) {
170 Iterator<DocumentModel> iterator = relationDocs.iterator();
172 while (iterator.hasNext()) {
173 DocumentModel relationDoc = iterator.next();
174 String exhibitionCsid = (String) relationDoc.getProperty("relations_common", "objectCsid");
175 DocumentModel exhibitionDoc = getRecordByCsid(session, tenantId, "Exhibition", exhibitionCsid);
177 if (exhibitionDoc != null && isExhibitionPublished(exhibitionDoc)) {
178 ObjectNode exhibitionNode = objectMapper.createObjectNode();
180 String title = (String) exhibitionDoc.getProperty("exhibitions_common", "title");
181 String generalNote = (String) exhibitionDoc.getProperty("exhibitions_common", "generalNote");
182 String curatorialNote = (String) exhibitionDoc.getProperty("exhibitions_common", "curatorialNote");
184 exhibitionNode.put("title", title);
185 exhibitionNode.put("generalNote", generalNote);
186 exhibitionNode.put("curatorialNote", curatorialNote);
188 exhibitions.add(exhibitionNode);
193 denormValues.putArray("exhibition").addAll(exhibitions);
197 * Denormalize the material group list for a collectionobject in order to index the controlled or uncontrolled term
199 * @param doc the collectionobject document
200 * @param denormValues the json node for denormalized fields
202 private void denormMaterialFields(DocumentModel doc, ObjectNode denormValues) {
203 List<Map<String, Object>> materialGroupList =
204 (List<Map<String, Object>>) doc.getProperty("collectionobjects_common", "materialGroupList");
206 List<JsonNode> denormMaterials = new ArrayList<>();
207 for (Map<String, Object> materialGroup : materialGroupList) {
208 String controlledMaterial = (String) materialGroup.get("materialControlled");
209 if (controlledMaterial != null) {
210 final ObjectNode node = objectMapper.createObjectNode();
211 node.put("material", RefNameUtils.getDisplayName(controlledMaterial));
212 denormMaterials.add(node);
215 String material = (String) materialGroup.get("material");
216 if (material != null) {
217 final ObjectNode node = objectMapper.createObjectNode();
218 node.put("material", material);
219 denormMaterials.add(node);
223 denormValues.putArray("materialGroupList").addAll(denormMaterials);
227 * Denormalize the object name group list for a collectionobject in order to index the controlled and
230 * @param doc the collectionobject document
231 * @param denormValues the json node for denormalized fields
233 private void denormObjectNameFields(DocumentModel doc, ObjectNode denormValues) {
234 List<Map<String, Object>> objectNameList =
235 (List<Map<String, Object>>) doc.getProperty("collectionobjects_common", "objectNameList");
237 List<JsonNode> denormObjectNames = new ArrayList<>();
238 for (Map<String, Object> objectNameGroup : objectNameList) {
239 String controlledName = (String) objectNameGroup.get("objectNameControlled");
240 if (controlledName != null) {
241 final ObjectNode node = objectMapper.createObjectNode();
242 node.put("objectName", RefNameUtils.getDisplayName(controlledName));
243 denormObjectNames.add(node);
246 String objectName = (String) objectNameGroup.get("objectName");
247 if (objectName != null) {
248 final ObjectNode node = objectMapper.createObjectNode();
249 node.put("objectName", objectName);
250 denormObjectNames.add(node);
254 denormValues.putArray("objectNameList").addAll(denormObjectNames);
258 * Denormalize the content concept, content event, content person, and content organization
259 * fields for a collectionobject so that they are indexed under a single field
261 * @param doc the collectionobject document
262 * @param denormValues the json node for denormalized fields
264 private void denormConceptFields(final DocumentModel doc, final ObjectNode denormValues) {
265 final List<JsonNode> denormContentSubject = new ArrayList<>();
266 final List<String> fields = Arrays.asList("contentConcepts",
269 "contentOrganizations");
271 for (String field : fields) {
272 List<String> contentList = (List<String>) doc.getProperty("collectionobjects_common", field);
274 for (String content : contentList) {
275 if (content != null) {
276 final ObjectNode node = objectMapper.createObjectNode();
277 node.put("subject", RefNameUtils.getDisplayName(content));
278 denormContentSubject.add(node);
283 denormValues.putArray("contentSubjectList").addAll(denormContentSubject);
287 * Compute a title for the public browser. This needs to be indexed in ES so that it can
288 * be used for sorting. (Even if it's just extracting the primary value.)
290 protected String computeTitle(DocumentModel doc) {
291 List<Map<String, Object>> titleGroups = (List<Map<String, Object>>) doc.getProperty("collectionobjects_common", "titleGroupList");
292 String primaryTitle = null;
294 if (titleGroups.size() > 0) {
295 Map<String, Object> primaryTitleGroup = titleGroups.get(0);
296 primaryTitle = (String) primaryTitleGroup.get("title");
299 if (StringUtils.isNotEmpty(primaryTitle)) {
303 List<Map<String, Object>> objectNameGroups = (List<Map<String, Object>>) doc.getProperty("collectionobjects_common", "objectNameList");
304 String primaryObjectName = null;
306 if (objectNameGroups.size() > 0) {
307 Map<String, Object> primaryObjectNameGroup = objectNameGroups.get(0);
308 primaryObjectName = (String) primaryObjectNameGroup.get("objectNameControlled");
309 if (primaryObjectName == null) {
310 primaryObjectName = (String) primaryObjectNameGroup.get("objectName");
313 // The object might be a refname in some profiles/tenants. If it is, use only the display name.
316 String displayName = RefNameUtils.getDisplayName(primaryObjectName);
318 if (displayName != null) {
319 primaryObjectName = displayName;
322 catch (Exception e) {}
325 return primaryObjectName;
328 private boolean isPublished(DocumentModel doc, String publishedFieldPart, String publishedFieldName) {
329 boolean isPublished = false;
332 List<String> publishToValues = (List<String>) doc.getProperty(publishedFieldPart, publishedFieldName);
334 if (publishToValues != null) {
335 for (int i=0; i<publishToValues.size(); i++) {
336 String value = publishToValues.get(i);
337 String shortId = RefNameUtils.getItemShortId(value);
339 if (shortId.equals("all") || shortId.equals("cspacepub")) {
351 private boolean isMediaPublished(DocumentModel mediaDoc) {
352 return isPublished(mediaDoc, "media_common", "publishToList");
355 private boolean isExhibitionPublished(DocumentModel exhibitionDoc) {
356 return isPublished(exhibitionDoc, "exhibitions_common", "publishToList");
359 private String getCreditLine(CoreSession session, String tenantId, String acquisitionCsid) {
360 String creditLine = null;
361 DocumentModel acquisitionDoc = getRecordByCsid(session, tenantId, "Acquisition", acquisitionCsid);
363 if (acquisitionDoc != null) {
364 creditLine = (String) acquisitionDoc.getProperty("acquisitions_common", "creditLine");
370 protected DocumentModel getRecordByCsid(CoreSession session, String tenantId, String recordType, String csid) {
371 String getRecordQuery = String.format("SELECT * FROM %s WHERE ecm:name = '%s' AND ecm:currentLifeCycleState = 'project' AND collectionspace_core:tenantId = '%s'", recordType, csid, tenantId);
373 DocumentModelList docs = session.query(getRecordQuery);
375 if (docs != null && docs.size() > 0) {
382 protected List<JsonNode> structDateToYearNodes(Map<String, Object> structDate) {
383 return structDatesToYearNodes(Arrays.asList(structDate));
386 protected List<JsonNode> structDatesToYearNodes(List<Map<String, Object>> structDates) {
387 Set<Integer> years = new HashSet<Integer>();
389 for (Map<String, Object> structDate : structDates) {
390 if (structDate != null) {
391 GregorianCalendar earliestCalendar = (GregorianCalendar) structDate.get("dateEarliestScalarValue");
392 GregorianCalendar latestCalendar = (GregorianCalendar) structDate.get("dateLatestScalarValue");
394 if (earliestCalendar != null && latestCalendar != null) {
395 // Grr @ latest scalar value historically being exclusive.
396 // Subtract one day to make it inclusive.
397 latestCalendar.add(Calendar.DATE, -1);
399 Integer earliestYear = earliestCalendar.get(Calendar.YEAR);
400 Integer latestYear = latestCalendar.get(Calendar.YEAR);;
402 for (int year = earliestYear; year <= latestYear; year++) {
409 List<Integer> yearList = new ArrayList<Integer>(years);
410 Collections.sort(yearList);
412 List<JsonNode> yearNodes = new ArrayList<JsonNode>();
414 for (Integer year : yearList) {
415 yearNodes.add(new IntNode(year));