~~CLOSETOC~~
<html><font color=#990000 size="+2"><b>Event Trigger User's Guide</b></font></html>

The <color green>Service Application Engine™</color> Provides a mechanism for writing programs that react to data changes and service calls.  

<html><font color=#990000 size="+1"><b>Trigger Concepts</b></font></html>

Some Basics here

====Triggers Internals====

===Source Events===

===Actionable Events===

===Old and New Data===

====Triggers Event Scope====

====Triggers and Event Streams====


====System Function Libraries====

====User-Defined Function Libraries====

====Basic Syntax====
This document describes event triggers and includes the following:
  - create event trigger slang operation
  - event trigger script syntax description
  - event trigger script functions description
  - samples
  
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>
    }

EVENT TRIGGER SCRIPT SYNTAX
===============================
Trigger script syntax is like java syntax.
  * Unordered List Item
  * Syntax is case sensitive.
  * 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, mapentry, final, 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 cannt 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.
  * primitive types
    * char
    * byte
    * short
    * int 
    * long
    * float
    * double 
    * decimal
    * bigint
    * boolean
    * string
    * date
    * object
    * event
    * void
    * []

  * collection types
    * map
    * mapentry
    * list
    * set
    * queue

  * complex types
    * SqlTimestamp
    * SqlDate
    * RowSet
    * Row
    * RowArray
    * semantic types registered in runtime
   
  * dataspace collection interfaces
    * BlockingQueue
    * EventQueue
    * AuditQueue
    * MessageQueue
    * ProcessQueue
    * Table
    * EventTable
    * FileTable
    * VirtualTable
    * Directory
    * View
    * SourceStream
    * Map

  * Component types
    * Dataspace
    * Service
  * Operations: <nowiki>−,+,−−,++,∗,⁄,=, +=, −=, ⁄=, ∗= new</nowiki>
  * 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
    * events
    * trigger
    * file
    * log
    * sys
    * 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 examle:
<code>
  string name = select name from MyTable where id = 1;
  date currentDate = getCurrentDate();
</code>

Raise statements description
  * raise event <someEvent> [on [<onEventId>]]
    Raises specified event. If onEventId eventId is specified, someEvent.setEventId(onEventId) is done before rasing. 
  * raise advisory
    Raises EventTriggerAdvisory based on incoming event, component and trigger type/model
  * raise exception <exceptionEvent>
    raises exception

Variable declaration
<code>
  int a;
  int b = 1;
  string s = 'value';
  final string finalString = 'fanalvalue';
</code>

Array declaration and using
<code>
  int[] intArray;                     // without initialization
  RowSet[] rowSet = new RowSet[10];   // with initialization
  intArray = new int[5];
  intArray[0] = 10;
  int length = intArray.length;
</code>
  
Map declaration and using
<code>
  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 (mapentry entry : m1.entrySet()) {
    keySum3 += entry.getKey();
    valueSum3 += entry.getValue();
  }
</code>
  
List declaration and using
<code>
  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;
  }
</code>
    
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 tragetEvent)
Description
  Copies Event Identity Management elements(correlationId, eventKey and eventGroupId) from sourceEvent to targetEvent.
Arguments
  sourceEvent - source event
  tragetEvent - 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 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 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
  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
  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

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. Datasapce name should be constant

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

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

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 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
  void commit()
Description
  Commits transaction in invoked dataspace. Can be replaced with DSQL query 'commit'.
Arguments
  None

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 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
  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
  object lookupCollection(string collectionName)
Description
  Lookups specified colletion in dataspace. Returns reference to collection if found, othewise 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 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 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


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

<code>
    //  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.aduit.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 ;
</code>

Trigger samples

<code>
  // 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 default
      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 employyes list from incoming event
        if (employees == null) {                          // if employees not set raise one audit event
          event auditEvent = new [event.aduit.employee];   // create aduit event without function
          auditEvent.data = 'employees is null';
          auditEvent.severity = Severity.INFO;
          events.copyEIM(e, auditEvent);                   // copy EIM info, we can use the followinf 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.aduit.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 ## ;
    /**
     * Acknowlege trigger raises AcknowlegementEvent with action depends on incoming event properties.
    */
    create event trigger AcknowlegeTrigger
      event scope default
      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.booleanPropery1)
        {
          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 default
      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 ## ;
    /**
     * Reraises incoming event on the same event id.
     */
    create event trigger EventPublisherTrigger 
      event scope default
      after event [event.response.employees]
      as
      {
        raise event this.getCurrentEvent();
      }
    ##
    set delimiter ; ##
      
    set delimiter ## ;
    /**
     * Reraises incoming event on the new event id.
     */
    create event trigger EventPublisherTriggerOn
      event scope default
      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 default
      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 default
      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 Employyes from incomming event into dataspace Map.
      */
    create event trigger EmployeePutTrigger
      event scope default
      after event [event.response.employees]
      as
      {
        event e = this.getCurrentEvent();
        Dataspace ds = sys.lookup('MyDataspace');
        Map employyeMap = ds.lookupCollection('EmployeeMap');
        for (Employee employee : (list)e.data.employees) {
          employyeMap.put(employee.getName(), employee);
        }
      }
    ##
    set delimiter ; ##

    set delimiter ## ;
    /**
     * Puts all Employyes from incomming event into dataspace table.
     */
    create event trigger EmployeePutTrigger1
      event scope default
      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 avarage age of employees.
      */
    create event trigger EmployeeCalculateAvarageTrigger
      event scope default
      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 avarage age of employees.
     */
    create event trigger EmployeeCalculateAvarageTrigger1
      event scope default
      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 ; ##
</code>

====DSQL in Triggers====

====SLANG in Triggers====

\\

<html><font color=#990000 size="+1"><b>Runtime Triggers</b></font></html>

Some Basics here

^Event Id ^Description ^
| sys.big.oops | Some error.. |
| sys.alert    | Some alert.. | 

====Working with Runtime Triggers====

\\

<html><font color=#990000 size="+1"><b>Service Triggers</b></font></html>

Some Basics here

====Working with Service Triggers====

\\

<html><font color=#990000 size="+1"><b>Dataspace Collection Triggers</b></font></html>

Some Basics here

====Working with Dataspace Triggers====

\\

<html><font color=#990000 size="+1"><b>Examples</b></font></html>

Some explanation here here

====Runtime Triggers====

====Service Triggers====

====Dataspace Triggers====