(Native) Java Hooks

Java Hooks are the fastest hooks. Write a Java Hook if you need the best performance on execution. Look at Hooks for more information.

The ORecordHook interface

A hook is an implementation of the interface ORecordHook:

  1. public interface ORecordHook {
  2. public enum TYPE {
  3. ANY,
  4. BEFORE_CREATE, BEFORE_READ, BEFORE_UPDATE, BEFORE_DELETE,
  5. AFTER_CREATE, AFTER_READ, AFTER_UPDATE, AFTER_DELETE
  6. };
  7. public void onTrigger(TYPE iType, ORecord<?> iRecord);
  8. }

The ORecordHookAbstract abstract class

OrientDB comes with an abstract implementation of the ORecordHook interface called ORecordHookAbstract.java. It switches the callback event, calling separate methods for each one:

  1. public abstract class ORecordHookAbstract implements ORecordHook {
  2. public void onRecordBeforeCreate(ORecord<?> iRecord){}
  3. public void onRecordAfterCreate(ORecord<?> iRecord){}
  4. public void onRecordBeforeRead(ORecord<?> iRecord){}
  5. public void onRecordAfterRead(ORecord<?> iRecord){}
  6. public void onRecordBeforeUpdate(ORecord<?> iRecord){}
  7. public void onRecordAfterUpdate(ORecord<?> iRecord){}
  8. public void onRecordBeforeDelete(ORecord<?> iRecord){}
  9. public void onRecordAfterDelete(ORecord<?> iRecord){}
  10. ...
  11. }

The ODocumentHookAbstract abstract class

When you want to catch an event from a Document only, the best way to create a hook is to extend the ODocumentHookAbstract abstract class. You can specify what classes you’re interested in. In this way the callbacks will be called only on documents of the specified classes. Classes are polymorphic so filtering works against specified classes and all sub-classes.

You can specify only the class you’re interested or the classes you want to exclude. Example to include only the Client and Provider classes:

  1. public class MyHook extends ODocumentHookAbstract {
  2. public MyHook() {
  3. setIncludeClasses("Client", "Provider");
  4. }
  5. }

Example to get called for all the changes on documents of any class but Log:

  1. public class MyHook extends ODocumentHookAbstract {
  2. public MyHook() {
  3. setExcludeClasses("Log");
  4. }
  5. }

Access to the modified fields

In Hook methods you can access dirty fields and the original values. Example:

  1. for( String field : document.getDirtyFields() ) {
  2. Object originalValue = document.getOriginalValue( field );
  3. ...
  4. }

Self registration

Hooks can be installed on certain database instances, but in most cases you’ll need to register it for each instance. To do this programmatically you can intercept the onOpen() and onCreate() callbacks from OrientDB to install hooks. All you need is to implement the ODatabaseLifecycleListener interface. Example:

  1. public class MyHook extends ODocumentHookAbstract implements ODatabaseLifecycleListener {
  2. public MyHook() {
  3. // REGISTER MYSELF AS LISTENER TO THE DATABASE LIFECYCLE
  4. Orient.instance().addDbLifecycleListener(this);
  5. }
  6. ...
  7. @Override
  8. public void onOpen(final ODatabase iDatabase) {
  9. // REGISTER THE HOOK
  10. ((ODatabaseComplex<?>)iDatabase).registerHook(this);
  11. }
  12. @Override
  13. public void onCreate(final ODatabase iDatabase) {
  14. // REGISTER THE HOOK
  15. ((ODatabaseComplex<?>)iDatabase).registerHook(this);
  16. }
  17. @Override
  18. public void onClose(final ODatabase iDatabase) {
  19. // REGISTER THE HOOK
  20. ((ODatabaseComplex<?>)iDatabase).unregisterHook(this);
  21. }
  22. ...
  23. public RESULT onRecordBeforeCreate(final ODocument iDocument) {
  24. // DO SOMETHING BEFORE THE DOCUMENT IS CREATED
  25. ...
  26. }
  27. ...
  28. }

Hook example

In this example the events before-create and after-delete are called during the save() of the Profile object where:

  • before-create is used to check custom validation rules
  • after-delete is used to maintain the references valid
  1. public class HookTest extends ORecordHookAbstract {
  2. public saveProfile(){
  3. ODatabaseObjectTx database = new ODatabaseObjectTx("remote:localhost/demo");
  4. database.open("writer", "writer");
  5. // REGISTER MYSELF AS HOOK
  6. database.registerHook(this);
  7. ...
  8. p = new Profile("Luca");
  9. p.setAge(10000);
  10. database.save(p);
  11. ...
  12. }
  13. /**
  14. * Custom validation rules
  15. */
  16. @Override
  17. public void onRecordBeforeCreate(ORecord<?> iRecord){
  18. if( iRecord instanceof ODocument ){
  19. ODocument doc = (ODocument) iRecord;
  20. Integer age = doc .field( "age" );
  21. if( age != null && age > 130 )
  22. throw new OValidationException("Invalid age");
  23. }
  24. }
  25. /**
  26. * On deletion removes the reference back.
  27. */
  28. @Override
  29. public void onRecordAfterDelete(ORecord<?> iRecord){
  30. if( iRecord instanceof ODocument ){
  31. ODocument doc = (ODocument) iRecord;
  32. Set<OIdentifiable> friends = doc.field( "friends" );
  33. if( friends != null ){
  34. for( OIdentifiable friend : friends ){
  35. Set<OIdentifiable> otherFriends = ((ODocument)friend.getRecord()).field("friends");
  36. if( friends != null )
  37. friends.remove( iRecord );
  38. }
  39. }
  40. }
  41. }
  42. }

For more information take a look to the HookTest.java source code.

Install server-side hooks

To let a hook be executed in the Server space you have to register it in the server orientdb-server-config.xml configuration file.

Write your hook

Example of a hook to execute custom validation rules:

  1. public class CustomValidationRules implements ORecordHook{
  2. /**
  3. * Apply custom validation rules
  4. */
  5. public boolean onTrigger(final TYPE iType, final ORecord<?> iRecord) {
  6. if( iRecord instanceof ODocument ){
  7. ODocument doc = (ODocument) iRecord;
  8. switch( iType ){
  9. case BEFORE_CREATE:
  10. case BEFORE_UPDATE: {
  11. if( doc.getClassName().equals("Customer") ){
  12. Integer age = doc .field( "age" );
  13. if( age != null && age > 130 )
  14. throw new OValidationException("Invalid age");
  15. }
  16. break;
  17. }
  18. case BEFORE_DELETE: {
  19. if( doc.getClassName().equals("Customer") ){
  20. final ODatabaseRecord db = ODatabaseRecordThreadLocal.INSTANCE.get();
  21. if( !db.getUser().getName().equals( "admin" ) )
  22. throw new OSecurityException("Only admin can delete customers");
  23. }
  24. break;
  25. }
  26. }
  27. }
  28. }

Deploy the hook

Once implemented create a .jar file containing your class and put it under the $ORIENTDB_HOME/lib directory.

Register it in the server configuration

Change the orientdb-server-config.xml file adding your hook inside the <hooks> tag. The position can be one of following values FIRST, EARLY, REGULAR, LATE, LAST:

  1. <hook class="org.orientdb.test.MyHook" position="REGULAR"/>

Configurable hooks

If your hook must be configurable with external parameters write the parameters in the orientdb-server-config.xml file:

  1. <hook class="org.orientdb.test.MyHook" position="REGULAR">
  2. <parameters>
  3. <parameter name="userCanDelete" value="admin" />
  4. </parameters>
  5. </hook>

And in your Java class implement the config() method to read the parameter:

  1. private String userCanDelete;
  2. ...
  3. public void config(OServer oServer, OServerParameterConfiguration[] iParams) {
  4. for (OServerParameterConfiguration param : iParams) {
  5. if (param.name.equalsIgnoreCase("userCanDelete")) {
  6. userCanDelete = param.value;
  7. }
  8. }
  9. }
  10. ...