]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
433ada0badc222b560d58c104e2f9d4b624d197e
[tmp/jakarta-migration.git] /
1 package org.collectionspace.services.listener;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.InputStreamReader;
7 import java.sql.Connection;
8 import java.sql.ResultSet;
9 import java.sql.SQLException;
10 import java.sql.Statement;
11 import java.util.ArrayList;
12 import java.util.List;
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
15 import org.collectionspace.services.client.workflow.WorkflowClient;
16 import org.collectionspace.services.common.api.RefNameUtils;
17 import org.collectionspace.services.common.api.Tools;
18 import org.collectionspace.services.common.storage.JDBCTools;
19 import org.collectionspace.services.movement.nuxeo.MovementConstants;
20 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
21 import org.nuxeo.ecm.core.api.ClientException;
22 import org.nuxeo.ecm.core.api.CoreSession;
23 import org.nuxeo.ecm.core.api.DocumentModel;
24 import org.nuxeo.ecm.core.api.DocumentModelList;
25 import org.nuxeo.ecm.core.event.Event;
26 import org.nuxeo.ecm.core.event.EventContext;
27 import org.nuxeo.ecm.core.event.EventListener;
28 import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
29
30 public class UpdateObjectLocationOnMove implements EventListener {
31
32     // FIXME: We might experiment here with using log4j instead of Apache Commons Logging;
33     // am using the latter to follow Ray's pattern for now
34     final Log logger = LogFactory.getLog(UpdateObjectLocationOnMove.class);
35     private final String DATABASE_RESOURCE_DIRECTORY_NAME = "db";
36     // FIXME: Currently hard-coded; get this database name value from JDBC utilities or equivalent
37     private final String DATABASE_SYSTEM_NAME = "postgresql";
38     private final static String STORED_FUNCTION_NAME = "computecurrentlocation";
39     private final static String SQL_FILENAME_EXTENSION = ".sql";
40     private final String SQL_RESOURCE_PATH =
41             DATABASE_RESOURCE_DIRECTORY_NAME + "/"
42             + DATABASE_SYSTEM_NAME + "/"
43             + STORED_FUNCTION_NAME + SQL_FILENAME_EXTENSION;
44     // The name of the relevant column in the JDBC ResultSet is currently identical
45     // to the function name, regardless of the 'SELECT ... AS' clause in the SQL query.
46     private final static String COMPUTED_CURRENT_LOCATION_COLUMN = STORED_FUNCTION_NAME;
47     // FIXME: Get this line separator value from already-declared constant elsewhere, if available
48     private final String LINE_SEPARATOR = System.getProperty("line.separator");
49     private final static String RELATIONS_COMMON_SCHEMA = "relations_common"; // FIXME: Get from external constant
50     final String RELATION_DOCTYPE = "Relation"; // FIXME: Get from external constant
51     private final static String OBJECT_CSID_PROPERTY = "objectCsid"; // FIXME: Get from external constant
52     private final static String COLLECTIONOBJECTS_COMMON_SCHEMA = "collectionobjects_common"; // FIXME: Get from external constant
53     final String COLLECTIONOBJECT_DOCTYPE = "CollectionObject"; // FIXME: Get from external constant
54     final String COMPUTED_CURRENT_LOCATION_PROPERTY = "computedCurrentLocation"; // FIXME: Create and then get from external constant
55
56     // ####################################################################
57     // FIXME: Per Rick, what happens if a relation record is updated,
58     // that either adds or removes a relation between a Movement
59     // record and a CollectionObject record?  Do we need to listen
60     // for that event as well and update the CollectionObject record's
61     // computedCurrentLocation accordingly?
62     //
63     // The following code is currently only handling create and
64     // update events affecting Movement records.
65     // ####################################################################
66     @Override
67     public void handleEvent(Event event) throws ClientException {
68
69         logger.trace("In handleEvent in UpdateObjectLocationOnMove ...");
70
71         // FIXME: Check for database product type here.
72         // If our database type is one for which we don't yet
73         // have tested SQL code to perform this operation, return here.
74
75         EventContext eventContext = event.getContext();
76         if (eventContext == null) {
77             return;
78         }
79         DocumentEventContext docEventContext = (DocumentEventContext) eventContext;
80         DocumentModel docModel = docEventContext.getSourceDocument();
81
82         // If this event does not involve an active Movement Document,
83         // return without further handling the event.
84         if (!(isMovementDocument(docModel) && isActiveDocument(docModel))) {
85             return;
86         }
87
88         logger.debug("A create or update event for an active Movement document was received by UpdateObjectLocationOnMove ...");
89
90         // Test whether a SQL function exists to supply the computed
91         // current location of a CollectionObject.
92         //
93         // If the function does not exist in the database, load the
94         // SQL command to create that function from a resource
95         // available to this class, and run a JDBC command to create
96         // that function in the database.
97         //
98         // For now, assume this function will be created in the
99         // 'nuxeo' database.
100         //
101         // FIXME: Future work to create per-tenant repositories will
102         // likely require that our JDBC statements connect to the
103         // appropriate tenant-specific database.
104         //
105         // It doesn't appear we can reliably create this function via
106         // 'ant create_nuxeo db' during the build process, because
107         // there's a substantial likelihood at that point that
108         // tables referred to by the function (e.g. movements_common
109         // and collectionobjects_common) will not yet exist.
110         // (PostgreSQL will not permit the function to be created if
111         // any of its referred-to tables do not exist.)
112         if (!storedFunctionExists(STORED_FUNCTION_NAME)) {
113             logger.debug("Stored function " + STORED_FUNCTION_NAME + " does NOT exist.");
114             String sql = getStringFromResource(SQL_RESOURCE_PATH);
115             if (Tools.isBlank(sql)) {
116                 logger.warn("Could not obtain SQL command to create stored function.");
117                 logger.warn("Actions in this event listener will NOT be performed, as a result of a previous error.");
118                 return;
119             }
120
121             int result = -1;
122             try {
123                 result = JDBCTools.executeUpdate(JDBCTools.getDataSource(JDBCTools.NUXEO_REPOSITORY_NAME), sql);
124             } catch (Exception e) {
125                 // Do nothing here
126                 // FIXME: Need to verify that the original '-1' value is preserved if an Exception is caught here.
127             }
128             logger.debug("Result of executeUpdate=" + result);
129             if (result < 0) {
130                 logger.warn("Could not create stored function.");
131                 logger.warn("Actions in this event listener will NOT be performed, as a result of a previous error.");
132                 return;
133             } else {
134                 logger.debug("Stored function " + STORED_FUNCTION_NAME + " was successfully created.");
135             }
136         } else {
137             logger.debug("Stored function " + STORED_FUNCTION_NAME + " exists.");
138         }
139
140         String movementCsid = NuxeoUtils.getCsid(docModel);
141         logger.debug("Movement record CSID=" + movementCsid);
142
143         // Find CollectionObject records that are related to this Movement record:
144         //
145         // Via an NXQL query, get a list of (non-deleted) relation records where:
146         // * This movement record's CSID is the subject CSID of the relation.
147         // * The object document type is a CollectionObject doctype.
148         //
149         // Note: this assumes that every such relation is captured by
150         // relations with Movement-as-subject and CollectionObject-as-object,
151         // logic that matches that of the SQL function to obtain the computed
152         // current location of the CollectionObject.
153         //
154         // That may NOT always be the case; it's possible some such relations may
155         // exist only with CollectionObject-as-subject and Movement-as-object.
156         CoreSession coreSession = docEventContext.getCoreSession();
157         String query = String.format(
158                 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
159                 + "(relations_common:subjectCsid = '%2$s' "
160                 + "AND relations_common:objectDocumentType = '%3$s') "
161                 + "AND (ecm:currentLifeCycleState <> 'deleted') "
162                 + "AND ecm:isProxy = 0 "
163                 + "AND ecm:isCheckedInVersion = 0", RELATION_DOCTYPE, movementCsid, COLLECTIONOBJECT_DOCTYPE);
164         DocumentModelList relatedDocModels = coreSession.query(query);
165         if (relatedDocModels == null || relatedDocModels.isEmpty()) {
166             return;
167         } else {
168             logger.debug("Found " + relatedDocModels.size() + " related documents.");
169         }
170
171         // Iterate through the list of Relation records found and build
172         // a list of CollectionObject CSIDs, by extracting the object CSIDs
173         // from those Relation records.
174
175         // FIXME: The following code might be refactored into a generic 'get property
176         // values from a list of document models' method, if this doesn't already exist.
177         String csid = "";
178         List<String> collectionObjectCsids = new ArrayList<String>();
179         for (DocumentModel relatedDocModel : relatedDocModels) {
180             csid = (String) relatedDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
181             if (Tools.notBlank(csid)) {
182                 collectionObjectCsids.add(csid);
183             }
184         }
185         if (collectionObjectCsids == null || collectionObjectCsids.isEmpty()) {
186             return;
187         } else {
188             logger.debug("Found " + collectionObjectCsids.size() + " CollectionObject CSIDs.");
189         }
190
191         // Iterate through the list of CollectionObject CSIDs found.
192         DocumentModel collectionObjectDocModel = null;
193         String computedCurrentLocationRefName = "";
194         for (String collectionObjectCsid : collectionObjectCsids) {
195
196             // Verify that the CollectionObject record is active.
197             collectionObjectDocModel = getDocModelFromCsid(coreSession, collectionObjectCsid);
198             if (!isActiveDocument(collectionObjectDocModel)) {
199                 continue;
200             }
201
202             // Via a JDBC call, invoke the SQL function to obtain the computed
203             // current location of that CollectionObject.
204             computedCurrentLocationRefName = computeCurrentLocation(collectionObjectCsid);
205             logger.debug("computedCurrentLocation refName=" + computedCurrentLocationRefName);
206
207             // Check that the value returned from the SQL function, which
208             // is expected to be a reference (refName) to a storage location
209             // authority term, is, at a minimum:
210             // * Non-null and non-blank. (We need to verify this assumption; can a
211             //   CollectionObject's computed current location meaningfully be 'un-set'?)
212             // * Capable of being successfully parsed by an authority item parser;
213             //   that is, returning a non-null parse result.
214             if ((Tools.notBlank(computedCurrentLocationRefName)
215                     && (RefNameUtils.parseAuthorityTermInfo(computedCurrentLocationRefName) != null))) {
216                 logger.debug("refName passes basic validation tests.");
217
218                 // If the value returned from the function passes validation,
219                 // compare that value to the value in the computedCurrentLocation
220                 // field of that CollectionObject
221                 //
222                 // If the CollectionObject does not already have a
223                 // computedCurrentLocation value, or if the two values differ,
224                 // update the CollectionObject record's computedCurrentLocation
225                 // field with the value returned from the SQL function.
226                 String existingComputedCurrentLocationRefName =
227                         (String) collectionObjectDocModel.getProperty(COLLECTIONOBJECTS_COMMON_SCHEMA, COMPUTED_CURRENT_LOCATION_PROPERTY);
228                 if (Tools.isBlank(existingComputedCurrentLocationRefName)
229                         || !computedCurrentLocationRefName.equals(existingComputedCurrentLocationRefName)) {
230                     logger.debug("Existing computedCurrentLocation refName=" + existingComputedCurrentLocationRefName);
231                     logger.debug("computedCurrentLocation refName requires updating.");
232                     // FIXME: Add update code here
233                 } else {
234                     logger.debug("computedCurrentLocation refName does NOT require updating.");
235                 }
236
237             }
238
239         }
240
241     }
242
243     /**
244      * Identifies whether a document is a Movement document
245      *
246      * @param docModel a document model
247      * @return true if the document is a Movement document; false if it is not.
248      */
249     private boolean isMovementDocument(DocumentModel docModel) {
250         return documentMatchesType(docModel, MovementConstants.NUXEO_DOCTYPE);
251     }
252
253     // FIXME: Generic methods like many of those below might be split off,
254     // into an event utilities class, base classes, or otherwise. - ADR 2012-12-05
255     //
256     // FIXME: Identify whether the equivalent of the documentMatchesType utility
257     // method is already implemented and substitute a call to the latter if so.
258     // This may well already exist.
259     /**
260      * Identifies whether a document matches a supplied document type.
261      *
262      * @param docModel a document model.
263      * @param docType a document type string.
264      * @return true if the document matches the supplied document type; false if
265      * it does not.
266      */
267     private boolean documentMatchesType(DocumentModel docModel, String docType) {
268         if (docModel == null || Tools.isBlank(docType)) {
269             return false;
270         }
271         if (docModel.getType().startsWith(docType)) {
272             return true;
273         } else {
274             return false;
275         }
276     }
277
278     /**
279      * Identifies whether a document is an active document; that is, if it is
280      * not a versioned record; not a proxy (symbolic link to an actual record);
281      * and not in the 'deleted' workflow state.
282      *
283      * (A note relating the latter: Nuxeo appears to send 'documentModified'
284      * events even on workflow transitions, such when records are 'soft deleted'
285      * by being transitioned to the 'deleted' workflow state.)
286      *
287      * @param docModel
288      * @return true if the document is an active document; false if it is not.
289      */
290     private boolean isActiveDocument(DocumentModel docModel) {
291         if (docModel == null) {
292             return false;
293         }
294         boolean isActiveDocument = false;
295         try {
296             if (!docModel.isVersion()
297                     && !docModel.isProxy()
298                     && !docModel.getCurrentLifeCycleState().equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
299                 isActiveDocument = true;
300             }
301         } catch (ClientException ce) {
302             logger.warn("Error while identifying whether document is an active document: ", ce);
303         }
304         return isActiveDocument;
305     }
306
307     // FIXME: The following method is specific to PostgreSQL, because of
308     // the SQL command executed; it may need to be generalized.
309     // Note: It may be necessary in some cases to provide additional
310     // parameters beyond a function name (such as a function signature)
311     // to uniquely identify a function. So far, however, this need
312     // hasn't arisen in our specific use case here.
313     /**
314      * Identifies whether a stored function exists in a database.
315      *
316      * @param functionname the name of the function.
317      * @return true if the function exists in the database; false if it does
318      * not.
319      */
320     private boolean storedFunctionExists(String functionname) {
321         if (Tools.isBlank(functionname)) {
322             return false;
323         }
324         boolean storedFunctionExists = false;
325         String sql = "SELECT proname FROM pg_proc WHERE proname='" + functionname + "'";
326         Connection conn = null;
327         Statement stmt = null;
328         ResultSet rs = null;
329         try {
330             conn = JDBCTools.getConnection(JDBCTools.getDataSource(JDBCTools.NUXEO_REPOSITORY_NAME));
331             stmt = conn.createStatement();
332             rs = stmt.executeQuery(sql);
333             if (rs.next()) {
334                 storedFunctionExists = true;
335             }
336             rs.close();
337             stmt.close();
338             conn.close();
339         } catch (Exception e) {
340             logger.debug("Error when identifying whether stored function " + functionname + "exists :", e);
341         } finally {
342             try {
343                 if (rs != null) {
344                     rs.close();
345                 }
346                 if (stmt != null) {
347                     stmt.close();
348                 }
349                 if (conn != null) {
350                     conn.close();
351                 }
352             } catch (SQLException sqle) {
353                 logger.debug("SQL Exception closing statement/connection in "
354                         + "UpdateObjectLocationOnMove.storedFunctionExists: "
355                         + sqle.getLocalizedMessage());
356             }
357         }
358         return storedFunctionExists;
359     }
360
361     /**
362      * Returns the computed current location of a CollectionObject (aka
363      * Cataloging) record.
364      *
365      * @param csid the CSID of a CollectionObject record.
366      * @return the computed current location of the CollectionObject record.
367      */
368     private String computeCurrentLocation(String csid) {
369         String computedCurrentLocation = "";
370         if (Tools.isBlank(csid)) {
371             return computedCurrentLocation;
372         }
373         String sql = String.format("SELECT %1$s('%2$s')", STORED_FUNCTION_NAME, csid);
374         Connection conn = null;
375         Statement stmt = null;
376         ResultSet rs = null;
377         try {
378             conn = JDBCTools.getConnection(JDBCTools.getDataSource(JDBCTools.NUXEO_REPOSITORY_NAME));
379             stmt = conn.createStatement();
380             rs = stmt.executeQuery(sql);
381             if (rs.next()) {
382                 computedCurrentLocation = rs.getString(COMPUTED_CURRENT_LOCATION_COLUMN);
383             }
384             rs.close();
385             stmt.close();
386             conn.close();
387         } catch (Exception e) {
388             logger.debug("Error when attempting to obtain the computed current location of an object :", e);
389         } finally {
390             try {
391                 if (rs != null) {
392                     rs.close();
393                 }
394                 if (stmt != null) {
395                     stmt.close();
396                 }
397                 if (conn != null) {
398                     conn.close();
399                 }
400             } catch (SQLException sqle) {
401                 logger.debug("SQL Exception closing statement/connection in "
402                         + "UpdateObjectLocationOnMove.computeCurrentLocation: "
403                         + sqle.getLocalizedMessage());
404             }
405         }
406         return computedCurrentLocation;
407     }
408
409     /**
410      * Returns a string representation of the contents of an input stream.
411      *
412      * @param instream an input stream.
413      * @return a string representation of the contents of the input stream.
414      * @throws an IOException if an error occurs when reading the input stream.
415      */
416     private String stringFromInputStream(InputStream instream) throws IOException {
417         if (instream == null) {
418         }
419         BufferedReader bufreader = new BufferedReader(new InputStreamReader(instream));
420         StringBuilder sb = new StringBuilder();
421         String line = "";
422         while (line != null) {
423             sb.append(line);
424             line = bufreader.readLine();
425             sb.append(LINE_SEPARATOR);
426         }
427         return sb.toString();
428     }
429
430     /**
431      * Returns a string representation of a resource available to the current
432      * class.
433      *
434      * @param resourcePath a path to the resource.
435      * @return a string representation of the resource. Returns null if the
436      * resource cannot be read, or if it cannot be successfully represented as a
437      * string.
438      */
439     private String getStringFromResource(String resourcePath) {
440         String str = "";
441         ClassLoader classLoader = getClass().getClassLoader();
442         InputStream instream = classLoader.getResourceAsStream(resourcePath);
443         if (instream == null) {
444             logger.warn("Could not read from resource from path " + resourcePath);
445             return null;
446         }
447         try {
448             str = stringFromInputStream(instream);
449         } catch (IOException ioe) {
450             logger.warn("Could not create string from stream: ", ioe);
451             return null;
452         }
453         return str;
454     }
455
456     private DocumentModel getDocModelFromCsid(CoreSession coreSession, String collectionObjectCsid) {
457         DocumentModelList collectionObjectDocModels = null;
458         try {
459             final String query = "SELECT * FROM "
460                     + NuxeoUtils.BASE_DOCUMENT_TYPE
461                     + " WHERE "
462                     + NuxeoUtils.getByNameWhereClause(collectionObjectCsid);
463             collectionObjectDocModels = coreSession.query(query);
464         } catch (Exception e) {
465             logger.warn("Exception in query to get document model for CollectionObject: ", e);
466         }
467         if (collectionObjectDocModels == null || collectionObjectDocModels.isEmpty()) {
468             logger.warn("Could not get document models for CollectionObject(s).");
469         } else if (collectionObjectDocModels.size() != 1) {
470             logger.debug("Found more than 1 document with CSID=" + collectionObjectCsid);
471         }
472         return collectionObjectDocModels.get(0);
473     }
474 }