This document describes event triggers and includes the following:
  - create event trigger slang operation
  - samples
  
See RPL Script document for syntax description.
  
create event trigger OPERATION
===============================
Event triggers can be created with 'create event trigger' slang operation.
This operations located in service context and has the following syntax:

  create event trigger <TriggerName>
    [event scope {default | local | OBSERVABLE | GLOBAL | CLUSTER}]
    {BEFORE EVENT HANDLER <HandlerName> | after event <ActionableEventId>}
    [SOURCE EVENT AS <alias>]
    [ACTIONABLE EVENT AS <alias>]
    [WHEN (<RPL Selector>)]
    as 
    {
      <RPL script>
    }
   [enable | disable]

EVENT TRIGGER SCRIPT SYNTAX
===============================
Trigger script syntax is like java syntax.
  -	Syntax is case insensitive except identifiers and semantic types.
  - Comments // - oneline, /* multiline */
  -	Script should be enclosed in curly brackets. Part of script enclosed inside curly brackets is named as 'block'.
  - Variables are visible inside block where variable is declared and inside nested blocks.
  - Reserved words: all simple types, for, if, else, while, raise, event, object, exception, advisory, 
    list, set, collection, queue, iterable, map, entry, final, transient, true, false, new, null, return, break, continue
    try, catch, finally
  - Reserved words and semantic type names cannot be used as variable names
  - If variable declared as final its value should be assigned on declaration and cannot be changed later.
    Final variable can be used in functions that requires constant expression as arguments. 
    For example createAuditEvent(string eventId,...) requires constant eventId can be replaced with final string variable.
  - If variable declared as transient this variable initialized only once during variable declaration when trigger executed first time.
    Transient variable will be destroyed on when trigger will be disabled.  
  - primitive types
    + char
    + byte
    + short
    + int, integer
    + long
    + float
    + double 
    + decimal
    + bigint, biginteger
    + boolean
    + string
    + date
    + object
    + event
    + void
    + []

  - collection types
    + map
    + entry
    + list
    + set
    + queue

  - complex types
    + SqlTimestamp
    + SqlDate
    + RowSet
    + Row
    + RowArray
    + semantic types registered in runtime with ancestor=complex and user sem types
   
  - dataspace collection interfaces
    + BlockingQueue
    + EventQueue
    + AuditQueue
    + MessageQueue
    + ProcessQueue
    + Table
    + EventTable
    + FileTable
    + VirtualTable
    + Directory
    + View
    + SourceStream
    + Map

  - Component types
    + Dataspace
    + Service
    + Runtime
  -	Operations: -,+,--,++,*,/,=, +=, -=, /=, *= new
  -	Conditions: ==,!=, <,>,<=,>=, ||, &&
  -	Statements: if-else, for, while, return, break, continue, raise event, raise exception ,raise advisory
  -	Dynamic casts: (<type>)<variable>
  -	Fields and methods access in semantic types with dot notation. Semantic type field access performed by direct access to the field.
  -	Event field and properties access with dot notation. Event field access performed by calling corresponding get/set method
  -	Build-in functions contained in units
    o this
    o events
    o file
    o log
    o sys
    o ds

By default all SQL operations and functions are available from SYS dataspace. 
If no SQL functions called JDBC connection not opened. JDBC connection to default dataspace opened once any SQL statement or query is called and closed when trigged is disabled.
Default dataspace can be set with function this.setCurrentDataspace('MyDataspace');
If dataspace is got by call sys.lookup('MyDataspace') JDBC connection is closed when trigger execution ends.
For example:
  string name = select name from MyTable where id = 1;
  date currentDate = getCurrentDate();

Raise statements description
  - raise [event] <someEvent> [on [<onEventId>]]
    Raises specified event. If onEventId eventId is specified, someEvent.setEventId(onEventId) is done before rasing. 
  - raise exception <someExceptionEvent> [on [<onEventId>]]
    Raises specified exception event. If onEventId eventId is specified, someExceptionEvent.setEventId(onEventId) is done before rasing. 
  - raise advisory <someAdvisoryEvent> [on [<onEventId>]]
    Raises specified advisory event. If onEventId eventId is specified, someAdvisoryEvent.setEventId(onEventId) is done before rasing. 
  - raise advisory
    Raises EventTriggerAdvisory based on incoming event, component and trigger type/model
If raise failed exception is throws and trigger will be unloaded and invalidated. 

Variable declaration
  int a;
  int b = 1;
  string s = 'value';
  final string finalString = 'somevalue';
    
Array declaration and using
  int[] intArray;                     // without initialization
  RowSet[] rowSet = new RowSet[10];   // with initialization
  intArray = new int[5];
  intArray[0] = 10;
  int length = intArray.length;
  
Map declaration and using
  map m1 = new map();
  m1.put(1,11);
  m1.put(2,22);
                      
  // calculating keys, values sum with three different ways
  int keySum1 = 0;
  int valueSum1 = 0;
  for (int i : m1.keySet()) {
    keySum1 += i;
    valueSum1 += m1.get(i);
  }
                      
  int valueSum2 = 0;
  for (int i : m1.values())
    valueSum2 += i;

  int keySum3 = 0;
  int valueSum3 = 0;
  for (entry e : m1.entrySet()) {
    keySum3 += e.getKey();
    valueSum3 += e.getValue();
  }
  
List declaration and using
  list l = new list();
  l1.add(1);
  l1.add(null);
  l1.add(2);

  int sum = 0;
  for ( int i = 0; i < l1.size(); i++)
  {
    int v = (int)l1.get(i);
    if (v != null)
      sum += v;
  }

try-catch statement
  If some statements/exception wrapped to try-catch then any exception thrown in try-catch block is wrapped to LanguageException
  and passed to catch block. LanguageException is exception event with id [exception.Language] and has the following properties
   - type - parent exception type, by default 'script'. If parent exception is SQL type is 'sql'
   - name - parent exception class name
    

EVENT TRIGGER SCRIPT FUNCTIONS
===============================

events unit
------------

Signature
  BytesEvent createFileContent(string bytesEventId, {string | FileEvent } filepathOrFileEvent)
Description
  Creates and returns an instance of an BytesEvent initialized with provided file data.
  If second argument is FileEvent EIM information is copied to BytesEvent.
Arguments
  bytesEventId        - result BytesEvent id, should be constant string
  filepathOrFileEvent - filepath or FileEvent

Signature
  event createMailEvent(string mailEventId, string subject, string body, string contentType, string toRecipients[, string ccRecipients][, event baseEvent])
Description
  Creates and returns an instance of a mail event datagram based on specified arguments.
  If baseEvent is specified then Event Identity Management elements from the header are copied into the result mailEvent.
Arguments
  mailEventId  - result MailEvent id, should be constant string
  subject      - mail subject
  body         - mail body
  contentType  - mail content type, if null then 'text/html' type is used
  toRecipients - list of comma separated recipient mail addresses
  ccRecipients - list of comma separated cc mail addresses
  baseEvent    - if set EIM info copied to the result MailEvent

Signature
  AcknowledgementEvent createAck(event event, boolean withSourceData[, AcknowledgeAction onAcknowledgeAction])
Description
  Creates and returns an instance of an AcknowledgementEvent datagram based on the supplied Source Event Datagram and action.
  It is expected that Event Identity Management elements from the header are copied into the acknowledgement to allow correlation between an event and it's acknowledgement.
  If withSourceData flag is true data from source event are set to AcknowledgeEvent.
Arguments
  event               - event for which AcknowledgementEvent is created
  withSourceData      - if true data from source event are set to result AcknowledgementEvent
  onAcknowledgeAction - acknowledge action, default action is AcknowledgeAction.ACKNOWLEDGE
                        the following actions are allowed:
                          AcknowledgeAction.ACKNOWLEDGE             - Acknowledges an event datagram but takes no further action.
                          AcknowledgeAction.ACKNOWLEDGE_AND_FORWARD - Acknowledges the event datagram and forwards it to its next destination specified by ForwardTo.
                          AcknowledgeAction.ACKNOWLEDGE_AND_DISCARD - Acknowledges the event datagram and discards it.
                                                                      If an eventgram is queued up it is removed from the queue. This is how a standard message queue functions.
                          AcknowledgeAction.ACKNOWLEDGE_AND_EXPIRE  - Acknowledges the event datagram and specifies that this datagram should be expired by the processor.
                          AcknowledgeAction.ACKNOWLEDGE_UNDELIVERED - Acknowledges the event datagram as not delivered to its destination.
                          AcknowledgeAction.ACKNOWLEDGE_AND_SUSPEND - Acknowledges the event datagram and instructs the recipient that all further processing of this eventId should be suspended.

Signature
  object convert(string converterName, object object)
Description
  Executes converter plugin with specified 'converterName' and specified 'object'.
  Returns converted object. Converter name should be constant.
Arguments
  converterName - name of converter plugin, should be constant string
  object        - object to convert

Signature
  void copyEIM(event sourceEvent, event targetEvent)
Description
  Copies Event Identity Management elements(correlationId, eventKey and eventGroupId) from sourceEvent to targetEvent.
Arguments
  sourceEvent - source event
  targetEvent - target event

Signature
  event createAuditEvent(string auditEventId, string auditMessage, Severity severity[, event baseEvent])
Description
  Creates and returns an instance of an audit event datagram based on specified auditEventId, auditMessage and severity.
  If baseEvent is specified then Event Identity Management elements from the header are copied into the result auditEvent.
Arguments
  auditEventId - result AuditEvent id can be set to real eventId or to 'default', 'sql', 'process' or 'user' that cast to event.audit.{default|sql|process|user} event ids
  auditMessage - audit message that set to the result AuditEvent
  severity     - severity that set to the result AuditEvent, possible values: Severity.SERVE, Severity.WARNING, Severity.INFO, Severity.GENERIC
  baseEvent    - if set EIM info copied to the result AuditEvent

Signature
  ExceptionEvent[event.exception] createExceptionEvent(string errorMessage[, int errorCode][, Severity severity][, event baseEvent])
Description
  Creates and returns an instance of an ExceptionEvent initialized with specified message, code and severity.
  If baseEvent is specified then Event Identity Management elements from the header are copied into the result exception event.
Arguments
  errorMessage - error message
  errorCode    - error code
  severity     - severity, possible values: Severity.SERVE, Severity.WARNING, Severity.INFO, Severity.GENERIC
  baseEvent    - base event, if specified EIM copies to result event

Signature
  event createFileEvent(string fileEventId, string filepath)
Description
  Creates and returns an instance of file event datagram based on specified filepath.
Arguments
  fileEventId - result FileEvent id, should be constant string
  filepath    - file path

file unit
------------

Signature
  void zip(string sourceFile, string resultZipFile)
Description
  Compresses file 'sourceFile' and creates ZIP archive 'resultZipFile'.
Arguments
  sourceFile    - source file path
  resultZipFile - result zip file path

Signature
  void rename({string | FileEvent } sourceFile, string targetPath)
Description
  Rename file 'sourceFile' to 'targetPath'.
Arguments
  sourceFile - source file path or FileEvent
  targetPath - target file path

Signature
  void unzip(string sourceFile, string resultPath)
Description
  Uncompresses file 'sourceFile' and extracts it to 'resultPath'.
Arguments
  sourceFile - source ZIP file path
  resultPath - result path

Signature
  void delete({string | FileEvent } sourceFile)
Description
  Removes file 'sourceFile'.
Arguments
  sourceFile - source file path or FileEvent

Signature
  void move({string | FileEvent } sourceFile, string targetPath)
Description
  Moves file 'sourceFile' to 'targetPath'.
Arguments
  sourceFile - source file path or FileEvent
  targetPath - target file dir path

Signature
  void copy({string | FileEvent } sourceFile, string targetPath)
Description
  Copies file 'sourceFile' to 'targetPath'.
Arguments
  sourceFile - source file path or FileEvent
  targetPath - target file dir path

sys unit
------------

Signature
  string getType(object object)
Description
  Deifnes semantic type of specified object. If no semantic type exists or value is null returns 'undefined'.
Arguments
  object - any object

Signature
  RowSet query(string query)
Description
  Executes slang query(queries) in runtime context. RowSet result of last query returned. If result is error result exception thrown.
  If result is not RowSet then RowSet with one column Response and one row returned.
Arguments
  query - slang query or semicolon delimited queries 

Signature
  string getHostname([int index])
Description
  Returns value of system property 'hostname' or interface with specified index.
  If function has argument then it determines interface index, otherwise it determines value of system property 'hostname'.
Arguments
  index - interface index

Signature
  boolean setGlobalVariable(string name, string value)
Description
  Sets a value of system variable. Returns true if set was success, false otherwise.
Arguments
  name  - name of global variable in format [PoolName].[VariableName]
  value - value of global variable

Signature
  string getGlobalVariable(string name)
Description
  Returns a value of global variable, or null if such variable does not exist.
Arguments
  name - name of global variable in format [PoolName].[VariableName].

Signature
  object lookup(string name)
Description
  Finds and returns reference to Dataspace/Service component with specified name. Type of this component depends on variable type in assignment operation.
Arguments
  name - name of Service or Dataspace in format <NodeName>://<Type>.<Name>, NodeName and Type are optional

Signature
  string getSystemVariable(string name)
Description
  Returns a value of system variable, or null if such variable does not exist.
Arguments
  name - name of system variable

runtime unit
------------

Signature
  object query(string query)
Description
  Invokes slang query.
Arguments
  query - Slang query

date unit
------------

Signature
  string toString(date dateObj, string pattern)
Description
  Formats date object into string using provided pattern.
Arguments
  dateObj - date object
  pattern - date pattern

Signature
  date fromString(string dateRep, string pattern)
Description
  Converts string representation of the data into java object using provided pattern.
Arguments
  dateRep - date representation in string format
  pattern - date pattern

log unit
------------

Signature
  void error(string message[, {event | object } eventOrObject][, string encodeAsXmlOrJson])
Description
  Logs to error trace specified message and event/object encoded in xml(default) or json.
Arguments
  message           - message to log
  eventOrObject     - object to log
  encodeAsXmlOrJson - format to log object(xml or json), xml by default

Signature
  void debug(string message[, {event | object } eventOrObject][, string encodeAsXmlOrJson])
Description
  Logs to debug trace specified message and event/object encoded in xml(default) or json.
Arguments
  message           - message to log
  eventOrObject     - object to log
  encodeAsXmlOrJson - format to log object(xml or json), xml by default

Signature
  void info(string message[, {event | object } eventOrObject][, string encodeAsXmlOrJson])
Description
  Logs to info trace specified message and event/object encoded in xml(default) or json.
Arguments
  message           - message to log
  eventOrObject     - object to log
  encodeAsXmlOrJson - format to log object(xml or json), xml by default

this unit
------------

Signature
  boolean hasCurrentEvent()
Description
  Returns true if current event is present.
Arguments
  None

Signature
  void setCurrentEvent(event event)
Description
  Updates current event value. eventId should not be changed.
Arguments
  event - new current event

Signature
  void setCurrentDataspace(string dataspaceName)
Description
  Sets specified dataspace as current.
Arguments
  dataspaceName - dataspace name in format <NodeName>://<Type>.<Name>, NodeName and Type are optional. Dataspace name should be constant.

Signature
  Dataspace getCurrentDataspace()
Description
  Returns reference to the current dataspace.
Arguments
  None

Signature
  void disable()
Description
  Disables trigger.
Arguments
  None

Signature
  event getCurrentEvent()
Description
  Returns a reference to current event, null if current event is not set.
Arguments
  None

Signature
  void invalidate(string error)
Description
  Unloads and invalidates trigger.
Arguments
  error - error description

ds unit
------------

Signature
  void setAutocommit(boolean isAutocommit)
Description
  Enables/disable autocommit in invoked dataspace. Can be replaced with DSQL query 'set autocommit {true | false}'.
Arguments
  isAutocommit - true/false

Signature
  int getFetchSize()
Description
  Returns fetch size in invoked dataspace.
Arguments
  None

Signature
  void commit()
Description
  Commits transaction in invoked dataspace. Can be replaced with DSQL query 'commit'.
Arguments
  None

Signature
  void savepoint(string savepointName)
Description
  Sets savepoint with specified name in invoked dataspace. Can be replaced with DSQL query 'savepoint <savepoint>'.
Arguments
  savepointName - savepoint name

Signature
  object query(string query[, object ...params])
Description
  Executes dataspace query. Variables can be referenced in query as @variable_name or as comma separated parameters(in this case in query thay should be marked as ?).
  If query returns updateCount function returns int.
  If query returns ResultSet function result depends on result columns count and cast or assignment variable type:
     - if columns count more than 1 RowSet returned
     - if columns count is zero null returned
     - if result is casted to RowSet then RowSet returned
     - if rows count more than 1 and columns count is 1 List returned
     - if rows count is zero empty and columns count is 1 List returned
     - if rows count is 1 and columns count is 1 and result is casted to any type(except List and RowSet) single value returned.
Arguments
  query  - DSQL query
  params - DQL query params, comma separated

Signature
  void startTransaction()
Description
  Starts transaction in invoked dataspace. Can be replaced with DSQL query 'start transaction'.
Arguments
  None

Signature
  void rollback([string savepointName])
Description
  Rollbacks transaction in invoked dataspace. Can be replaced with DSQL query 'rollback {to savepoint <savepoint>}'.
Arguments
  savepointName - savepoint name

Signature
  void setFetchSize(int fetchSize)
Description
  Sets fetch size in invoked dataspace. Fetch size works if RowSet returned only. If List returned all data will loaded.
Arguments
  fetchSize - fetch rows count, default is 0

Signature
  DataCollection lookupCollection(string collectionName)
Description
  Finds specified collection in dataspace. Returns reference to collection if found, otherwise null.
  The following collection references can be get: Queue, EventQueue, AuditQueue, MessageQueue, ProcessQueue, Table, EventTable, FileTable, VirtualTable, Directory, View, SourceStream.
Arguments
  collectionName - collection name

Signature
  boolean getAutocommit()
Description
  Returns true if autocommit is enabled in invoked dataspace.
Arguments
  None

scheduler unit
------------

Signature
  object getIterations()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object purgeJobs()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getTimeWindows()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object hashCode()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object wait()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getRemoteJobs()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getRemoteIterations()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getContext()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getJob()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object createGroupJob()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getRemoteJob()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object setTimeWindow()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getContextType()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object listJobs()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object notify()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object existsJob()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object notifyAll()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getClass()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getTimeWindow()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object clone()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object listTimeWindows()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getIterationsNumber()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object equals()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object createRepeatingJob()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object existsTimeWindow()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getSerialVersionUID()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object dropJob()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getRemoteIterationsNumber()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object listRemoteJobs()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object removeTimeWindow()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object existsRemoteJob()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object getJobs()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object createJob()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object purgeIterations()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object toString()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object createRepeatingGroupJob()
Description
  See Scheduler javadoc.
Arguments
  None

Signature
  object addTimeWindow()
Description
  See Scheduler javadoc.
Arguments
  None

repository unit
------------

Signature
  object lookup(string namespace, string name)
Description
  Finds the specified object in the specified namespace of the repository.
Arguments
  namespace - namespace of the object to lookup
  name      - name of the object to lookup


SAMPLES
=====================================
Assume we have the following semantic types, prototypes and service

    //  SLANG script
    set delimiter ##;
    create sdo EmployeeAddress
    as
    {
      long sip;
      string state;
    }
    NAMESPACE com.trigger.sample
    REPLACE ARCHIVE triggersamplesdo
    REPLACE PACKAGE triggersamplesdo
    DESCRIPTION 'Employee address'
    ##

    create sdo Employee
    as
    {
       string          name;
       int             age;
       EmployeeAddress address;
    }
    NAMESPACE com.trigger.sample
    REPLACE ARCHIVE triggersamplesdo
    REPLACE PACKAGE triggersamplesdo
    DESCRIPTION 'Employee object'
    ##

    create sdo Employees
    as
    {
       list(Employee) employees;
    }
    NAMESPACE com.trigger.sample
    REPLACE ARCHIVE triggersamplesdo
    REPLACE PACKAGE triggersamplesdo
    DESCRIPTION 'Employees object'
    ##
    set delimiter ; ##

    create event prototype [event.response.employee] model DataEvent semantic_type Employee;
    create event prototype [event.request.employees] model DataEvent semantic_type Employees;
    create event prototype [event.response.employees] model DataEvent semantic_type Employees 
      properties(intProperty1 Integer, doubleProperty1 Double, stringProperty1 String, booleanPropery1 Boolean);
    create event prototype [event.new.response.employees] model DataEvent semantic_type Employees 
      properties(intProperty1 Integer, doubleProperty1 Double, stringProperty1 String, booleanPropery1 Boolean);
    create event prototype [event.audit.employee] model AuditEvent
      properties(intProperty1 Integer, doubleProperty1 Double, stringProperty1 String);
    
    create service type TriggerSampleService class com.streamscape.trigger.sample.SampleService
    invoke_mode direct
    handlers 
    (
      processEmployees method createForm request(event [event.request.employees] type Employees) response(event [event.response.employees] type Employees)
    );

    generate service type TriggerSampleService archive reporting-1.0.jar source at './tmp'  build native abstract;
    create service instance TriggerSampleService.Default;
    register service TriggerSampleService.Default autostart true;
    start service TriggerSampleService.Default ;


  use TriggerSampleService.Default ;

Trigger samples

  // Auditor trigger
  set delimiter ##
    /**
     *  Auditor trigger accepts [event.response.employees] event and raises audit event depends on employees data.
     */
    create event trigger AuditorTrigger
      event scope inherited
      after event [event.response.employees]
      as
      {
        event e = this.getCurrentEvent();                 // get incoming event and store it in local variable e
        list employees = e.data.employees;                // get data and employees list from incoming event
        if (employees == null) {                          // if employees not set raise one audit event
          event auditEvent = new [event.audit.employee];   // create audit event without function
          auditEvent.data = 'employees is null';
          auditEvent.severity = Severity.INFO;
          events.copyEIM(e, auditEvent);                   // copy EIM info, we can use the following assignment instead of function : auditEvent.eventGroupId = e.eventGroupId;
          auditEvent.correlationIdAsBytes= e.correlationIdAsBytes; 
          auditEvent.eventKey = e.eventKey;
          raise event auditEvent;
          return;
        }
        for (Employee employee : employees) {             // if employees are set raise one audit event for each employee
          string auditMessage = 'employee name : ' + employee.name + ' age: ' + employee.age;
          event auditEvent = events.createAuditEvent('event.audit.employee', auditMessage, Severity.GENERIC, e); // use function for audit event creation
          auditEvent.stringProperty1 = employee.name;     // set some properties, if needed
          auditEvent.intProperty1 = employee.age;
          auditEvent.doubleProperty1 = e.intProperty1;
          raise event auditEvent;
        };
        raise advisory;                                   // raise advisory if needed
      }
    ##
    set delimiter

  // Acknowledge trigger
    set delimiter ##
    /**
     * Acknowledge trigger raises AcknowledgementEvent with action depends on incoming event properties.
    */
    create event trigger AcknowledgeTrigger
      event scope inherited
      after event [event.response.employees]
      as
      {
        event e = this.getCurrentEvent();
        event ackEvent = events.createAck(e, true, AcknowledgeAction.ACKNOWLEDGE);
        if (e.intProperty1 == 1)
          ackEvent.onAcknowledgeAction = AcknowledgeAction.ACKNOWLEDGE_AND_FORWARD;
        else if (e.intProperty1 == 2)
          ackEvent.onAcknowledgeAction = AcknowledgeAction.ACKNOWLEDGE_AND_DISCARD;
          
        // set properties if needed
        if (e.booleanProperty1)
        {
          ackEvent.recipientId = 'qwe';                                   
          ackEvent.correlationEventExpiration = 100;
          ackEvent.correlationEventTimeStamp = getCurrentDate();
          ackEvent.correlationEventId = 'event.id1'; 
        }
        
        raise event ackEvent;
      }
    ##
    set delimiter

   
    // Logger trigger
    set delimiter ##
    /**
     *   Logger trigger
     */
     create event trigger LoggerTrigger
      event scope inherited
      after event [event.response.employees]
      as
      {
        event e = this.getCurrentEvent();
        string text = 'sample header message';
        log.error(text, e, 'xml');
        log.debug(text, e, 'xml');
        log.info(text, e, 'xml');

        log.error(text, e, 'json');
        log.debug(text, e, 'json');
        log.info(text, e, 'json');

        log.error(text, e.data, 'xml');
        log.debug(text, e.data, 'json');
        log.info(text, e.data, 'xml');
      }
    ##
    set delimiter
      
    // Event publisher trigger
    set delimiter ##
    /**
     * Re-raises incoming event on the same event id.
     */
    create event trigger EventPublisherTrigger 
      event scope inherited
      after event [event.response.employees]
      as
      {
        raise event this.getCurrentEvent();
      }
    ##
    set delimiter
      
    set delimiter ##
    /**
     * Re-raises incoming event on the new event id.
     */
    create event trigger EventPublisherTriggerOn
      event scope inherited
      after event [event.response.employees]
      as
      {
        raise event this.getCurrentEvent() on [event.new.response.employees];
      }
    ##
    set delimiter
      
    set delimiter ##
    /**
     * Raises employee events based on incoming event employees
     */
    create event trigger EventPublisherTriggerMulti
      event scope inherited
      after event [event.response.employees]
      as
      {
        event e = this.getCurrentEvent();
        for (Employee employee : (list)e.data.employees) {
          event event1 = new [event.response.employee];
          events.copyEIM(e, event1);
          event1.data = employee;
          raise event event1;
        }
      }
    ##
    set delimiter

  // try-catch-finally
    set delimiter ##
    create event trigger TryCatchSampleTrigger
      event scope inherited
      after event [event.response.employees]
      as
      {
        event e = this.getCurrentEvent();
        try 
	      {
	         start transaction;
           for (Employee employee : (list)e.data.employees)
	           insert into employees values(employee);
           commit;
	      }
	      catch(excep)
	      {
	         rollback;
           raise exception excep;
           log.error('Failed to update employees. Cause: ' + excep.getMessage());
	      }
      }
    ##
    set delimiter

    // Using dataspace functions
    set delimiter ##
    /**
      * Puts all Employees from incoming event into dataspace Map.
      */
    create event trigger EmployeePutTrigger
      event scope inherited
      after event [event.response.employees]
      as
      {
        event e = this.getCurrentEvent();
        Dataspace ds = sys.lookup('MyDataspace');
        Map employeeMap = ds.lookupCollection('EmployeeMap');
        for (Employee employee : (list)e.data.employees) {
          employeeMap.put(employee.getName(), employee);
        }
      }
    ##
    set delimiter

    set delimiter ##
    /**
     * Puts all Employees from incoming event into dataspace table.
     */
    create event trigger EmployeePutTrigger1
      event scope inherited
      after event [event.response.employees]
      as
      {
        event e = this.getCurrentEvent();
        Dataspace ds = sys.lookup('MyDataspace');
        for (Employee employee : (list)e.data.employees) {
          ds.query('insert into Employees values(@employee)');
        }
      }
    ##
    set delimiter
      
    set delimiter ##
    /**
      * Calculates average age of employees.
      */
    create event trigger EmployeeCalculateAverageTrigger
      event scope inherited
      after event [event.response.employees]
      as
      {
        Dataspace ds = sys.lookup('MyDataspace');
        RowSet r = ds.query('select * from EmployeeMap');
        int average = 0, i = 0;
        while(r.next()) {
          Employee employee = (Employee)r.getObject(1);
          average += employee.age;
          i++;
        }
        average /= i;
      }
    ##
    set delimiter

    set delimiter ##
    /**
     * Calculates average age of employees.
     */
    create event trigger EmployeeCalculateAverageTrigger1
      event scope inherited
      after event [event.response.employees]
      as
      {
        Dataspace ds = sys.lookup('MyDataspace');
        list employees = ds.query('select employee from employees');
        int average = 0, i = 0;
        for(Employee employee : employees) {
          average += employee.age;
          i++;
        }
        average /= i;
      }
    ##
    set delimiter