Server side implementation of event groups. Fixes #NX-1102
authorEriks Jenkevics <eriks@netxms.org>
Wed, 16 Aug 2017 14:19:41 +0000 (17:19 +0300)
committerEriks Jenkevics <eriks@netxms.org>
Wed, 16 Aug 2017 15:05:46 +0000 (18:05 +0300)
40 files changed:
include/netxmsdb.h
include/nxconfig.h
sql/schema.in
src/java/client/netxms-client/src/main/java/org/netxms/client/NXCSession.java
src/java/client/netxms-client/src/main/java/org/netxms/client/events/EventGroup.java [new file with mode: 0644]
src/java/client/netxms-client/src/main/java/org/netxms/client/events/EventObject.java [new file with mode: 0644]
src/java/client/netxms-client/src/main/java/org/netxms/client/events/EventTemplate.java
src/java/client/netxms-client/src/test/java/org/netxms/client/ConnectionTest.java
src/java/client/netxms-client/src/test/java/org/netxms/client/EventDatabaseSyncTest.java
src/java/netxms-eclipse/Core/src/org/netxms/ui/eclipse/jobs/LoginJob.java
src/java/netxms-eclipse/DataCollection/src/org/netxms/ui/eclipse/datacollection/ThresholdLabelProvider.java
src/java/netxms-eclipse/DataCollection/src/org/netxms/ui/eclipse/datacollection/propertypages/helpers/TableThresholdLabelProvider.java
src/java/netxms-eclipse/EPP/src/org/netxms/ui/eclipse/epp/propertypages/RuleEvents.java
src/java/netxms-eclipse/EPP/src/org/netxms/ui/eclipse/epp/views/EventProcessingPolicyEditor.java
src/java/netxms-eclipse/EPP/src/org/netxms/ui/eclipse/epp/widgets/RuleEditor.java
src/java/netxms-eclipse/EventManager/src/org/netxms/ui/eclipse/eventmanager/dialogs/EventSelectionDialog.java
src/java/netxms-eclipse/EventManager/src/org/netxms/ui/eclipse/eventmanager/views/EventConfigurator.java
src/java/netxms-eclipse/EventManager/src/org/netxms/ui/eclipse/eventmanager/views/helpers/EventTemplateComparator.java
src/java/netxms-eclipse/EventManager/src/org/netxms/ui/eclipse/eventmanager/views/helpers/EventTemplateLabelProvider.java
src/java/netxms-eclipse/EventManager/src/org/netxms/ui/eclipse/eventmanager/widgets/EventSelector.java
src/java/netxms-eclipse/LogViewer/src/org/netxms/ui/eclipse/logviewer/views/helpers/LogLabelProvider.java
src/java/netxms-eclipse/LogViewer/src/org/netxms/ui/eclipse/logviewer/widgets/EventConditionEditor.java
src/java/netxms-eclipse/SNMP/src/org/netxms/ui/eclipse/snmp/views/helpers/SnmpTrapComparator.java
src/java/netxms-eclipse/SNMP/src/org/netxms/ui/eclipse/snmp/views/helpers/SnmpTrapLabelProvider.java
src/java/netxms-eclipse/ServerConfig/src/org/netxms/ui/eclipse/serverconfig/dialogs/helpers/SnmpTrapComparator.java
src/java/netxms-eclipse/ServerConfig/src/org/netxms/ui/eclipse/serverconfig/dialogs/helpers/SnmpTrapFilter.java
src/java/netxms-eclipse/ServerConfig/src/org/netxms/ui/eclipse/serverconfig/dialogs/helpers/TrapListLabelProvider.java
src/java/netxms-eclipse/ServerConfig/src/org/netxms/ui/eclipse/serverconfig/views/ExportFileBuilder.java
src/java/netxms-eclipse/ServerConfig/src/org/netxms/ui/eclipse/serverconfig/widgets/helpers/LogParserRuleEditor.java
src/libnetxms/config.cpp
src/server/core/dcitem.cpp
src/server/core/ef.cpp
src/server/core/epp.cpp
src/server/core/events.cpp
src/server/core/import.cpp
src/server/core/session.cpp
src/server/core/syslogd.cpp
src/server/include/nms_core.h
src/server/include/nms_events.h
src/server/tools/nxdbmgr/upgrade.cpp

index 2fe7b15..b94ded4 100644 (file)
@@ -23,6 +23,6 @@
 #ifndef _netxmsdb_h
 #define _netxmsdb_h
 
-#define DB_FORMAT_VERSION   458
+#define DB_FORMAT_VERSION   459
 
 #endif
index b57f3a9..12ea678 100644 (file)
@@ -177,6 +177,8 @@ public:
 
    void setAlias(const TCHAR *alias, const TCHAR *value) { if (alias != NULL) m_aliases.set(alias, value); else m_aliases.remove(alias); }
    const TCHAR *getAlias(const TCHAR *alias) const { return m_aliases.get(alias); }
+
+   bool isExpansionAllowed() { return m_allowMacroExpansion; }
 };
 
 
index 2a45ef5..b42e24f 100644 (file)
@@ -841,8 +841,6 @@ CREATE TABLE event_groups
   id integer not null,
   name varchar(63) not null,
   description varchar(255) not null,
-  range_start integer not null,
-  range_end integer not null,
   PRIMARY KEY(id)
 ) TABLE_TYPE;
 
index fa9ca9f..10459ca 100644 (file)
@@ -100,6 +100,7 @@ import org.netxms.client.events.AlarmComment;
 import org.netxms.client.events.BulkAlarmStateChangeData;
 import org.netxms.client.events.Event;
 import org.netxms.client.events.EventInfo;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.events.EventProcessingPolicy;
 import org.netxms.client.events.EventProcessingPolicyRule;
 import org.netxms.client.events.EventTemplate;
@@ -322,9 +323,9 @@ public class NXCSession
    // Users
    private Map<Long, AbstractUserObject> userDB = new HashMap<Long, AbstractUserObject>();
 
-   // Event templates
-   private Map<Long, EventTemplate> eventTemplates = new HashMap<Long, EventTemplate>();
-   private boolean eventTemplatesNeedSync = false;
+   // Event objects
+   private Map<Long, EventObject> eventObjects = new HashMap<Long, EventObject>();
+   private boolean eventObjectsNeedSync = false;
    
    // Alarm categories
    private Map<Long, AlarmCategory> alarmCategories = new HashMap<Long, AlarmCategory>();
@@ -693,9 +694,9 @@ public class NXCSession
                strictAlarmStatusFlow = ((int)data != 0);
                break;
             case SessionNotification.RELOAD_EVENT_DB:
-               if (eventTemplatesNeedSync)
+               if (eventObjectsNeedSync)
                {
-                  resyncEventTemplates();
+                  resyncEventObjects();
                }
                break;
             case SessionNotification.SESSION_KILLED:
@@ -851,18 +852,18 @@ public class NXCSession
       {
          int code = msg.getFieldAsInt32(NXCPCodes.VID_NOTIFICATION_CODE) + SessionNotification.NOTIFY_BASE;
          long eventCode = msg.getFieldAsInt64(NXCPCodes.VID_EVENT_CODE);
-         EventTemplate et = (code != SessionNotification.EVENT_TEMPLATE_DELETED) ? new EventTemplate(msg) : null;
-         if (eventTemplatesNeedSync)
+         EventTemplate et = (code != SessionNotification.EVENT_TEMPLATE_DELETED) ? new EventTemplate(msg, NXCPCodes.VID_ELEMENT_LIST_BASE) : null;
+         if (eventObjectsNeedSync)
          {
-            synchronized(eventTemplates)
+            synchronized(eventObjects)
             {
                if (code == SessionNotification.EVENT_TEMPLATE_DELETED)
                {
-                  eventTemplates.remove(eventCode);
+                  eventObjects.remove(eventCode);
                }
                else
                {
-                  eventTemplates.put(eventCode, et);
+                  eventObjects.put(eventCode, et);
                }
             }
          }
@@ -2118,7 +2119,7 @@ public class NXCSession
       objectList.clear();
       objectListGUID.clear();
       zoneList.clear();
-      eventTemplates.clear();
+      eventObjects.clear();
       userDB.clear();
       alarmCategories.clear();
    }
@@ -6148,24 +6149,24 @@ public class NXCSession
     * @throws IOException  if socket I/O error occurs
     * @throws NXCException if NetXMS server returns an error or operation was timed out
     */
-   public void syncEventTemplates() throws IOException, NXCException
+   public void syncEventObjects() throws IOException, NXCException
    {
-      List<EventTemplate> templates = getEventTemplates();
-      synchronized(eventTemplates)
+      List<EventObject> objects = getEventObjects();
+      synchronized(eventObjects)
       {
-         eventTemplates.clear();
-         for(EventTemplate t : templates)
+         eventObjects.clear();
+         for(EventObject o : objects)
          {
-            eventTemplates.put(t.getCode(), t);
+            eventObjects.put(o.getCode(), o);
          }
-         eventTemplatesNeedSync = true;
+         eventObjectsNeedSync = true;
       }
    }
    
    /**
     * Re-synchronize event templaytes in background
     */
-   private void resyncEventTemplates()
+   private void resyncEventObjects()
    {
       new Thread(new Runnable() {
          @Override
@@ -6173,11 +6174,11 @@ public class NXCSession
          {
             try
             {
-               syncEventTemplates();
+               syncEventObjects();
             }
             catch(Exception e)
             {
-               Logger.error("NXCSession.resyncEventTemplates", "Exception in worker thread", e);
+               Logger.error("NXCSession.resyncEventObjects", "Exception in worker thread", e);
             }
          }
       }).start();
@@ -6188,12 +6189,12 @@ public class NXCSession
     *
     * @return List of event templates cached by client library
     */
-   public EventTemplate[] getCachedEventTemplates()
+   public EventTemplate[] getCachedEventObjects()
    {
       EventTemplate[] events = null;
-      synchronized(eventTemplates)
+      synchronized(eventObjects)
       {
-         events = eventTemplates.values().toArray(new EventTemplate[eventTemplates.size()]);
+         events = eventObjects.values().toArray(new EventTemplate[eventObjects.size()]);
       }
       return events;
    }
@@ -6201,22 +6202,22 @@ public class NXCSession
    /**
     * Find event template by name in event template database internally
     * maintained by session object. You must call
-    * NXCSession.syncEventTemplates() first to make local copy of event template
+    * NXCSession.syncEventObjects() first to make local copy of event template
     * database.
     *
     * @param name Event name
     * @return Event template object or null if not found
     */
-   public EventTemplate findEventTemplateByName(String name)
+   public EventObject findEventObjectByName(String name)
    {
-      EventTemplate result = null;
-      synchronized(eventTemplates)
+      EventObject result = null;
+      synchronized(eventObjects)
       {
-         for(EventTemplate e : eventTemplates.values())
+         for(EventObject o : eventObjects.values())
          {
-            if (e.getName().equalsIgnoreCase(name))
+            if (o.getName().equalsIgnoreCase(name))
             {
-               result = e;
+               result = o;
                break;
             }
          }
@@ -6232,9 +6233,9 @@ public class NXCSession
     */
    public String getEventName(long code)
    {
-      synchronized(eventTemplates)
+      synchronized(eventObjects)
       {
-         EventTemplate e = eventTemplates.get(code);
+         EventObject e = eventObjects.get(code);
          return (e != null) ? e.getName() : ("[" + Long.toString(code) + "]");
       }
    }
@@ -6242,38 +6243,38 @@ public class NXCSession
    /**
     * Find event template by code in event template database internally
     * maintained by session object. You must call
-    * NXCSession.syncEventTemplates() first to make local copy of event template
+    * NXCSession.syncEventObjects() first to make local copy of event template
     * database.
     *
     * @param code Event code
     * @return Event template object or null if not found
     */
-   public EventTemplate findEventTemplateByCode(long code)
+   public EventObject findEventObjectByCode(long code)
    {
-      synchronized(eventTemplates)
+      synchronized(eventObjects)
       {
-         return eventTemplates.get(code);
+         return eventObjects.get(code);
       }
    }
 
    /**
     * Find multiple event templates by event codes in event template database
     * internally maintained by session object. You must call
-    * NXCSession.syncEventTemplates() first to make local copy of event template
+    * NXCSession.syncEventObjects() first to make local copy of event template
     * database.
     *
     * @param codes List of event codes
     * @return List of found event templates
     */
-   public List<EventTemplate> findMultipleEventTemplates(final Long[] codes)
+   public List<EventObject> findMultipleEventObjects(final Long[] codes)
    {
-      List<EventTemplate> list = new ArrayList<EventTemplate>();
-      synchronized(eventTemplates)
+      List<EventObject> list = new ArrayList<EventObject>();
+      synchronized(eventObjects)
       {
          for(long code : codes)
          {
-            EventTemplate e = eventTemplates.get(code);
-            if (e != null) list.add(e);
+            EventObject o = eventObjects.get(code);
+            if (o != null) list.add(o);
          }
       }
       return list;
@@ -6282,45 +6283,45 @@ public class NXCSession
    /**
     * Find multiple event templates by event codes in event template database
     * internally maintained by session object. You must call
-    * NXCSession.syncEventTemplates() first to make local copy of event template
+    * NXCSession.syncEventObjects() first to make local copy of event template
     * database.
     *
     * @param codes List of event codes
     * @return List of found event templates
     */
-   public List<EventTemplate> findMultipleEventTemplates(final long[] codes)
+   public List<EventObject> findMultipleEventObjects(final long[] codes)
    {
-      List<EventTemplate> list = new ArrayList<EventTemplate>();
-      synchronized(eventTemplates)
+      List<EventObject> list = new ArrayList<EventObject>();
+      synchronized(eventObjects)
       {
          for(long code : codes)
          {
-            EventTemplate e = eventTemplates.get(code);
-            if (e != null) list.add(e);
+            EventObject o = eventObjects.get(code);
+            if (o != null) list.add(o);
          }
       }
       return list;
    }
 
    /**
-    * Get event templates from server
+    * Get event objects from server
     *
-    * @return List of configured event templates
+    * @return List of configured event objects
     * @throws IOException  if socket I/O error occurs
     * @throws NXCException if NetXMS server returns an error or operation was timed out
     */
-   public List<EventTemplate> getEventTemplates() throws IOException, NXCException
+   public List<EventObject> getEventObjects() throws IOException, NXCException
    {
       NXCPMessage msg = newMessage(NXCPCodes.CMD_LOAD_EVENT_DB);
       sendMessage(msg);
-      waitForRCC(msg.getMessageId());
-      ArrayList<EventTemplate> list = new ArrayList<EventTemplate>();
-      while(true)
+      final NXCPMessage response = waitForRCC(msg.getMessageId());
+      int count = response.getFieldAsInt32(NXCPCodes.VID_NUM_EVENTS);
+      long base = NXCPCodes.VID_ELEMENT_LIST_BASE;
+      ArrayList<EventObject> list = new ArrayList<EventObject>();
+      for(int i = 0; i < count; i++)
       {
-         final NXCPMessage response = waitForMessage(NXCPCodes.CMD_EVENT_DB_RECORD, msg.getMessageId());
-         if (response.isEndOfSequence()) 
-            break;
-         list.add(new EventTemplate(response));
+         list.add(EventObject.createFromMessage(response, base));
+         base += 10;
       }
       return list;
    }
@@ -6371,6 +6372,7 @@ public class NXCSession
       msg.setField(NXCPCodes.VID_NAME, evt.getName());
       msg.setField(NXCPCodes.VID_MESSAGE, evt.getMessage());
       msg.setField(NXCPCodes.VID_DESCRIPTION, evt.getDescription());
+      
       sendMessage(msg);
       waitForRCC(msg.getMessageId());
    }
diff --git a/src/java/client/netxms-client/src/main/java/org/netxms/client/events/EventGroup.java b/src/java/client/netxms-client/src/main/java/org/netxms/client/events/EventGroup.java
new file mode 100644 (file)
index 0000000..a4ef813
--- /dev/null
@@ -0,0 +1,34 @@
+package org.netxms.client.events;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import org.netxms.base.NXCPMessage;
+
+public class EventGroup extends EventObject
+{
+   private List<Long> eventCodeList;
+
+   /**
+    * Create new empty event group
+    * 
+    * @param code event code
+    */
+   public EventGroup(long code)
+   {
+      super(code);
+      eventCodeList = new ArrayList<Long>();
+   }
+   
+   /**
+    * Create event group from NXCP message
+    * 
+    * @param msg NXCPMessage
+    * @param base base field id
+    */
+   public EventGroup(NXCPMessage msg, long base)
+   {
+      super(msg, base);
+      eventCodeList = Arrays.asList(msg.getFieldAsUInt32ArrayEx(base + 4));
+   }
+}
diff --git a/src/java/client/netxms-client/src/main/java/org/netxms/client/events/EventObject.java b/src/java/client/netxms-client/src/main/java/org/netxms/client/events/EventObject.java
new file mode 100644 (file)
index 0000000..50b7bf8
--- /dev/null
@@ -0,0 +1,124 @@
+package org.netxms.client.events;
+
+import org.netxms.base.NXCPMessage;
+
+public class EventObject
+{
+   public static final int FLAG_WRITE_TO_LOG = 0x0001;
+   public static final int FLAG_EVENT_GROUP = 0x0002;
+   
+   private static final long GROUP_ID_FLAG = 0x80000000L;
+   
+   protected long code;
+   protected String name;
+   protected String description;
+   
+   /**
+    * Create either event template or event group from message
+    * 
+    * @param msg NXCPMessage
+    * @param base bas field id
+    * @return EventObject
+    */
+   public static EventObject createFromMessage(NXCPMessage msg, long base)
+   {
+      if ((msg.getFieldAsInt64(base + 1) & GROUP_ID_FLAG) != 0)
+         return new EventGroup(msg, base);
+      else
+         return new EventTemplate(msg, base);
+   }
+   
+   /**
+    * Copy constructor.
+    * 
+    * @param src Original event object
+    */
+   protected EventObject(final EventObject src)
+   {
+      setAll(src);
+   }
+   
+   /**
+    * Create new empty event object
+    * @param code event object code
+    */
+   protected EventObject(long code)
+   {
+      this.code = code;
+      name = "";
+      description = "";
+   }
+   
+   /**
+    * Create event object from NXCP message
+    * 
+    * @param msg NXCPMessage
+    * @param base base field id
+    */
+   protected EventObject(final NXCPMessage msg, long base)
+   {
+      code = msg.getFieldAsInt64(base + 1);
+      description = msg.getFieldAsString(base + 2);
+      name = msg.getFieldAsString(base + 3);
+   }   
+
+   /**
+    * @return the name
+    */
+   public String getName()
+   {
+      return name;
+   }
+
+   /**
+    * @param name the name to set
+    */
+   public void setName(String name)
+   {
+      this.name = name;
+   }   
+
+   /**
+    * @return the description
+    */
+   public String getDescription()
+   {
+      return description;
+   }
+
+   /**
+    * @param description the description to set
+    */
+   public void setDescription(String description)
+   {
+      this.description = description;
+   }   
+
+   /**
+    * @return the code
+    */
+   public long getCode()
+   {
+      return code;
+   }
+
+   /**
+    * @param code the code to set
+    */
+   public void setCode(long code)
+   {
+      this.code = code;
+   }
+
+   /**
+    * Set all attributes from another event object.
+    * 
+    * @param src Original event object
+    */
+   public void setAll(EventObject src)
+   {
+      code = src.code;
+      name = src.name;
+      description = src.description;
+   }
+}
index 4dacda2..83c9848 100644 (file)
  */
 package org.netxms.client.events;
 
-import org.netxms.base.NXCPCodes;
 import org.netxms.base.NXCPMessage;
 import org.netxms.client.constants.Severity;
 
 /**
  * Event template
  */
-public class EventTemplate
+public class EventTemplate extends EventObject
 {
-       public static final int FLAG_WRITE_TO_LOG = 0x0001;
-       
-       private long code;
-       private String name;
        private Severity severity;
        private int flags;
        private String message;
-       private String description;
        
        /**
         * Create new empty event template.
@@ -43,27 +37,24 @@ public class EventTemplate
         */
        public EventTemplate(long code)
        {
-               this.code = code;
-               name = "";
+          super(code);
                severity = Severity.NORMAL;
                flags = FLAG_WRITE_TO_LOG;
                message = "";
-               description = "";
        }
        
        /**
         * Create event template object from NXCP message.
         * 
         * @param msg NXCP message
+    * @param base base field id
         */
-       public EventTemplate(final NXCPMessage msg)
+       public EventTemplate(final NXCPMessage msg, long base)
        {
-               code = msg.getFieldAsInt64(NXCPCodes.VID_EVENT_CODE);
-               severity = Severity.getByValue(msg.getFieldAsInt32(NXCPCodes.VID_SEVERITY));
-               flags = msg.getFieldAsInt32(NXCPCodes.VID_FLAGS);
-               name = msg.getFieldAsString(NXCPCodes.VID_NAME);
-               message = msg.getFieldAsString(NXCPCodes.VID_MESSAGE);
-               description = msg.getFieldAsString(NXCPCodes.VID_DESCRIPTION);
+          super(msg, base);
+               severity = Severity.getByValue(msg.getFieldAsInt32(base + 4));
+               flags = msg.getFieldAsInt32(base + 5);
+               message = msg.getFieldAsString(base + 6);
        }
        
        /**
@@ -73,6 +64,7 @@ public class EventTemplate
         */
        public EventTemplate(final EventTemplate src)
        {
+          super(src);
                setAll(src);
        }
        
@@ -83,28 +75,9 @@ public class EventTemplate
         */
        public void setAll(final EventTemplate src)
        {
-               code = src.code;
                severity = src.severity;
                flags = src.flags;
-               name = src.name;
                message = src.message;
-               description = src.description;
-       }
-
-       /**
-        * @return the name
-        */
-       public String getName()
-       {
-               return name;
-       }
-
-       /**
-        * @param name the name to set
-        */
-       public void setName(String name)
-       {
-               this.name = name;
        }
 
        /**
@@ -154,36 +127,4 @@ public class EventTemplate
        {
                this.message = message;
        }
-
-       /**
-        * @return the description
-        */
-       public String getDescription()
-       {
-               return description;
-       }
-
-       /**
-        * @param description the description to set
-        */
-       public void setDescription(String description)
-       {
-               this.description = description;
-       }
-
-       /**
-        * @return the code
-        */
-       public long getCode()
-       {
-               return code;
-       }
-
-       /**
-        * @param code the code to set
-        */
-       public void setCode(long code)
-       {
-               this.code = code;
-       }
 }
index e19f274..54836a7 100644 (file)
@@ -92,7 +92,7 @@ public class ConnectionTest extends AbstractSessionTest
                   final NXCSession session = connect(true);
                   
                   session.syncObjects();
-                  session.syncEventTemplates();
+                  session.syncEventObjects();
                   session.syncUserDatabase();
 
                   Thread.sleep(rand.nextInt(60000) + 10000);
index 3e115b9..94a45e2 100644 (file)
@@ -27,9 +27,9 @@ public class EventDatabaseSyncTest extends AbstractSessionTest
        {
                final NXCSession session = connect();
                
-               assertNull(session.findEventTemplateByCode(1L));
-               session.syncEventTemplates();
-               assertNotNull(session.findEventTemplateByCode(1L));
+               assertNull(session.findEventObjectByCode(1L));
+               session.syncEventObjects();
+               assertNotNull(session.findEventObjectByCode(1L));
                
                session.disconnect();
        }
index 3b0998f..86eb867 100644 (file)
@@ -130,7 +130,7 @@ public class LoginJob implements IRunnableWithProgress
          monitor.setTaskName(Messages.get().LoginJob_sync_event_db);
          try
          {
-            session.syncEventTemplates();
+            session.syncEventObjects();
          }
          catch(NXCException e)
          {
index 6cbc244..3825a6e 100644 (file)
@@ -53,7 +53,7 @@ public class ThresholdLabelProvider extends LabelProvider implements ITableLabel
                        case Thresholds.COLUMN_OPERATION:
                                return thresholdIcon;
                        case Thresholds.COLUMN_EVENT:
-                               final EventTemplate event = session.findEventTemplateByCode(((Threshold)element).getFireEvent());
+                               final EventTemplate event = (EventTemplate)session.findEventObjectByCode(((Threshold)element).getFireEvent());
                                return StatusDisplayInfo.getStatusImage((event != null) ? event.getSeverity() : Severity.UNKNOWN);
                }
                return null;
@@ -80,7 +80,7 @@ public class ThresholdLabelProvider extends LabelProvider implements ITableLabel
                                }
                                return text.toString();
                        case Thresholds.COLUMN_EVENT:
-                               final EventTemplate event = session.findEventTemplateByCode(((Threshold)element).getFireEvent());
+                               final EventTemplate event = (EventTemplate)session.findEventObjectByCode(((Threshold)element).getFireEvent());
                                return eventLabelProvider.getText(event);
                }
                return null;
index 06b3e32..6a4ce09 100644 (file)
@@ -51,12 +51,12 @@ public class TableThresholdLabelProvider extends LabelProvider implements ITable
                                return thresholdIcon;
                        case 2:
                        {
-                               final EventTemplate event = session.findEventTemplateByCode(((TableThreshold)element).getActivationEvent());
+                               final EventTemplate event = (EventTemplate)session.findEventObjectByCode(((TableThreshold)element).getActivationEvent());
                                return StatusDisplayInfo.getStatusImage((event != null) ? event.getSeverity() : Severity.UNKNOWN);
                        }
                        case 3:
                        {
-                               final EventTemplate event = session.findEventTemplateByCode(((TableThreshold)element).getDeactivationEvent());
+                               final EventTemplate event = (EventTemplate)session.findEventObjectByCode(((TableThreshold)element).getDeactivationEvent());
                                return StatusDisplayInfo.getStatusImage((event != null) ? event.getSeverity() : Severity.UNKNOWN);
                        }
                }
@@ -77,12 +77,12 @@ public class TableThresholdLabelProvider extends LabelProvider implements ITable
                           return Integer.toString(((TableThreshold)element).getSampleCount());
                        case 2:
                        {
-                               final EventTemplate event = session.findEventTemplateByCode(((TableThreshold)element).getActivationEvent());
+                               final EventTemplate event = (EventTemplate)session.findEventObjectByCode(((TableThreshold)element).getActivationEvent());
                                return eventLabelProvider.getText(event);
                        }
                        case 3:
                        {
-                               final EventTemplate event = session.findEventTemplateByCode(((TableThreshold)element).getDeactivationEvent());
+                               final EventTemplate event = (EventTemplate)session.findEventObjectByCode(((TableThreshold)element).getDeactivationEvent());
                                return eventLabelProvider.getText(event);
                        }
                }
index 0a9ac05..88c422c 100644 (file)
@@ -42,6 +42,7 @@ import org.eclipse.swt.widgets.Control;
 import org.eclipse.ui.dialogs.PropertyPage;
 import org.eclipse.ui.model.WorkbenchLabelProvider;
 import org.netxms.client.NXCSession;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.events.EventProcessingPolicyRule;
 import org.netxms.client.events.EventTemplate;
 import org.netxms.ui.eclipse.epp.Messages;
@@ -61,7 +62,7 @@ public class RuleEvents extends PropertyPage
        private RuleEditor editor;
        private EventProcessingPolicyRule rule;
        private SortableTableViewer viewer;
-       private Map<Long, EventTemplate> events = new HashMap<Long, EventTemplate>();
+       private Map<Long, EventObject> events = new HashMap<Long, EventObject>();
        private Button addButton;
        private Button deleteButton;
        private Button checkInverted;
@@ -102,8 +103,8 @@ public class RuleEvents extends PropertyPage
                        }
       });
 
-      for(EventTemplate e : session.findMultipleEventTemplates(rule.getEvents().toArray(new Long[0])))
-       events.put(e.getCode(), e);
+      for(EventObject o : session.findMultipleEventObjects(rule.getEvents().toArray(new Long[0])))
+       events.put(o.getCode(), o);
       viewer.setInput(events.values().toArray());
       
       GridData gridData = new GridData();
index 1e3e65c..7343428 100644 (file)
@@ -62,6 +62,7 @@ import org.netxms.client.ServerAction;
 import org.netxms.client.SessionListener;
 import org.netxms.client.SessionNotification;
 import org.netxms.client.events.AlarmCategory;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.events.EventProcessingPolicy;
 import org.netxms.client.events.EventProcessingPolicyRule;
 import org.netxms.client.events.EventTemplate;
@@ -1291,8 +1292,8 @@ public class EventProcessingPolicyEditor extends ViewPart implements ISaveablePa
       // check event names
       for(Long code : rule.getEvents())
       {
-         EventTemplate evt = session.findEventTemplateByCode(code);
-         if ((evt != null) && evt.getName().toLowerCase().contains(filterText))
+         EventObject evo = session.findEventObjectByCode(code);
+         if ((evo != null) && evo.getName().toLowerCase().contains(filterText))
             return true;
       }
 
index bd1bb56..032b7a5 100644 (file)
@@ -545,7 +545,7 @@ public class RuleEditor extends Composite
          List<EventTemplate> sortedEvents = new ArrayList<EventTemplate>(rule.getEvents().size());
          for(Long code : rule.getEvents())
          {
-            EventTemplate event = session.findEventTemplateByCode(code);
+            EventTemplate event = (EventTemplate)session.findEventObjectByCode(code);
             if (event == null)
             {
                event = new EventTemplate(code);
index 2f9ba8f..5d2b3ff 100644 (file)
@@ -122,7 +122,7 @@ public class EventSelectionDialog extends Dialog
                if (filterString != null)
                        filter.setFilterString(filterString);
                eventList.addFilter(filter);
-               eventList.setInput(ConsoleSharedData.getSession().getCachedEventTemplates());
+               eventList.setInput(ConsoleSharedData.getSession().getCachedEventObjects());
                gd = new GridData();
                gd.grabExcessHorizontalSpace = true;
                gd.horizontalAlignment = SWT.FILL;
index 18bd8ad..7f5387b 100644 (file)
@@ -37,7 +37,6 @@ import org.eclipse.jface.viewers.IDoubleClickListener;
 import org.eclipse.jface.viewers.ISelectionChangedListener;
 import org.eclipse.jface.viewers.IStructuredSelection;
 import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
 import org.eclipse.jface.window.Window;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.events.DisposeEvent;
@@ -60,6 +59,7 @@ import org.eclipse.ui.part.ViewPart;
 import org.netxms.client.NXCSession;
 import org.netxms.client.SessionListener;
 import org.netxms.client.SessionNotification;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.events.EventTemplate;
 import org.netxms.ui.eclipse.actions.RefreshAction;
 import org.netxms.ui.eclipse.console.resources.SharedIcons;
@@ -95,7 +95,7 @@ public class EventConfigurator extends ViewPart implements SessionListener
        public static final int COLUMN_MESSAGE = 4;
        public static final int COLUMN_DESCRIPTION = 5;
 
-       private HashMap<Long, EventTemplate> eventTemplates;
+       private HashMap<Long, EventObject> eventObjects;
        private SortableTableViewer viewer;
    private FilterText filterControl;
        private Action actionNew;
@@ -227,17 +227,17 @@ public class EventConfigurator extends ViewPart implements SessionListener
                        @Override
                        protected void runInternal(IProgressMonitor monitor) throws Exception
                        {
-                               final List<EventTemplate> list = session.getEventTemplates();
+                               final List<EventObject> list = session.getEventObjects();
                                runInUIThread(new Runnable() {
                                        @Override
                                        public void run()
                                        {
-                                               eventTemplates = new HashMap<Long, EventTemplate>(list.size());
-                                               for(final EventTemplate t: list)
+                                               eventObjects = new HashMap<Long, EventObject>(list.size());
+                                               for(final EventObject o: list)
                                                {
-                                                       eventTemplates.put(t.getCode(), t);
+                                                       eventObjects.put(o.getCode(), o);
                                                }
-                                               viewer.setInput(eventTemplates.values().toArray());
+                                               viewer.setInput(eventObjects.values().toArray());
                                        }
                                });
                        }
@@ -257,16 +257,16 @@ public class EventConfigurator extends ViewPart implements SessionListener
                                        @Override
                                        public void run()
                                        {
-                                               EventTemplate oldTmpl = eventTemplates.get(n.getSubCode());
-                                               if (oldTmpl != null)
+                                               EventObject oldObj = eventObjects.get(n.getSubCode());
+                                               if (oldObj != null)
                                                {
-                                                       oldTmpl.setAll((EventTemplate)n.getObject());
-                                                       viewer.update(oldTmpl, null);
+                                                  oldObj.setAll((EventObject)n.getObject());
+                                                       viewer.update(oldObj, null);
                                                }
                                                else
                                                {
-                                                       eventTemplates.put(n.getSubCode(), (EventTemplate)n.getObject());
-                                                       viewer.setInput(eventTemplates.values().toArray());
+                                                       eventObjects.put(n.getSubCode(), (EventTemplate)n.getObject());
+                                                       viewer.setInput(eventObjects.values().toArray());
                                                }
                                        }
                                });
@@ -276,8 +276,8 @@ public class EventConfigurator extends ViewPart implements SessionListener
                                        @Override
                                        public void run()
                                        {
-                                               eventTemplates.remove(n.getSubCode());
-                                               viewer.setInput(eventTemplates.values().toArray());
+                                               eventObjects.remove(n.getSubCode());
+                                               viewer.setInput(eventObjects.values().toArray());
                                        }
                                });
                                break;
@@ -456,18 +456,7 @@ public class EventConfigurator extends ViewPart implements SessionListener
                                @Override
                                protected void runInternal(IProgressMonitor monitor) throws Exception
                                {
-                                       long code = session.generateEventCode();
-                                       etmpl.setCode(code);
                                        session.modifyEventTemplate(etmpl);
-                                       runInUIThread(new Runnable() {
-                                               @Override
-                                               public void run()
-                                               {
-                                                       eventTemplates.put(etmpl.getCode(), etmpl);
-                                                       viewer.setInput(eventTemplates.values().toArray());
-                                                       viewer.setSelection(new StructuredSelection(etmpl), true);
-                                               }
-                                       });
                                }
                        }.start();
                }
@@ -497,15 +486,6 @@ public class EventConfigurator extends ViewPart implements SessionListener
                                protected void runInternal(IProgressMonitor monitor) throws Exception
                                {
                                        session.modifyEventTemplate(etmpl);
-                                       runInUIThread(new Runnable() {
-                                               @Override
-                                               public void run()
-                                               {
-                                                       eventTemplates.put(etmpl.getCode(), etmpl);
-                                                       viewer.setInput(eventTemplates.values());
-                                                       viewer.setSelection(new StructuredSelection(etmpl));
-                                               }
-                                       });
                                }
                        }.start();
                }
index c848ea5..48a9d2e 100644 (file)
@@ -21,6 +21,7 @@ package org.netxms.ui.eclipse.eventmanager.views.helpers;
 import org.eclipse.jface.viewers.Viewer;
 import org.eclipse.jface.viewers.ViewerComparator;
 import org.eclipse.swt.SWT;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.events.EventTemplate;
 import org.netxms.ui.eclipse.eventmanager.views.EventConfigurator;
 import org.netxms.ui.eclipse.widgets.SortableTableViewer;
@@ -41,22 +42,31 @@ public class EventTemplateComparator extends ViewerComparator
                switch((Integer)((SortableTableViewer)viewer).getTable().getSortColumn().getData("ID")) //$NON-NLS-1$
                {
                        case EventConfigurator.COLUMN_CODE:
-                               result = (int)(((EventTemplate)e1).getCode() - ((EventTemplate)e2).getCode());
+                               result = (int)(((EventObject)e1).getCode() - ((EventObject)e2).getCode());
                                break;
                        case EventConfigurator.COLUMN_NAME:
-                               result = ((EventTemplate)e1).getName().compareToIgnoreCase(((EventTemplate)e2).getName());
+                               result = ((EventObject)e1).getName().compareToIgnoreCase(((EventObject)e2).getName());
                                break;
                        case EventConfigurator.COLUMN_SEVERITY:
-                               result = ((EventTemplate)e1).getSeverity().compareTo(((EventTemplate)e2).getSeverity());
+                          if (e1 instanceof EventTemplate && e2 instanceof EventTemplate)
+                             result = ((EventTemplate)e1).getSeverity().compareTo(((EventTemplate)e2).getSeverity());
+                          else
+                             result = 0;
                                break;
                        case EventConfigurator.COLUMN_FLAGS:
-                               result = ((EventTemplate)e1).getFlags() - ((EventTemplate)e2).getFlags();
+            if (e1 instanceof EventTemplate && e2 instanceof EventTemplate)
+               result = ((EventTemplate)e1).getFlags() - ((EventTemplate)e2).getFlags();
+            else
+               result = 0;
                                break;
                        case EventConfigurator.COLUMN_MESSAGE:
-                               result = ((EventTemplate)e1).getMessage().compareToIgnoreCase(((EventTemplate)e2).getMessage());
+            if (e1 instanceof EventTemplate && e2 instanceof EventTemplate)
+               result = ((EventTemplate)e1).getMessage().compareToIgnoreCase(((EventTemplate)e2).getMessage());
+            else
+               result = 0;
                                break;
                        case EventConfigurator.COLUMN_DESCRIPTION:
-                               result = ((EventTemplate)e1).getDescription().compareToIgnoreCase(((EventTemplate)e2).getDescription());
+                               result = ((EventObject)e1).getDescription().compareToIgnoreCase(((EventObject)e2).getDescription());
                                break;
                        default:
                                result = 0;
index 23f3c5d..6ad7582 100644 (file)
@@ -21,6 +21,7 @@ package org.netxms.ui.eclipse.eventmanager.views.helpers;
 import org.eclipse.jface.viewers.ITableLabelProvider;
 import org.eclipse.swt.graphics.Image;
 import org.eclipse.ui.model.WorkbenchLabelProvider;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.events.EventTemplate;
 import org.netxms.ui.eclipse.console.resources.StatusDisplayInfo;
 import org.netxms.ui.eclipse.eventmanager.views.EventConfigurator;
@@ -48,17 +49,26 @@ public class EventTemplateLabelProvider extends WorkbenchLabelProvider implement
                switch(columnIndex)
                {
                        case EventConfigurator.COLUMN_CODE:
-                               return Long.toString(((EventTemplate)element).getCode());
+                               return Long.toString(((EventObject)element).getCode());
                        case EventConfigurator.COLUMN_NAME:
-                               return getText(element);
+                                  return getText(element);
                        case EventConfigurator.COLUMN_SEVERITY:
-                               return StatusDisplayInfo.getStatusText(((EventTemplate)element).getSeverity());
+            if (element instanceof EventTemplate)
+               return StatusDisplayInfo.getStatusText(((EventTemplate)element).getSeverity());
+            else
+               return "";
                        case EventConfigurator.COLUMN_FLAGS:
-                               return ((((EventTemplate)element).getFlags() & EventTemplate.FLAG_WRITE_TO_LOG) != 0) ? "L" : "-"; //$NON-NLS-1$ //$NON-NLS-2$
+            if (element instanceof EventTemplate)
+               return ((((EventTemplate)element).getFlags() & EventTemplate.FLAG_WRITE_TO_LOG) != 0) ? "L" : "-"; //$NON-NLS-1$ //$NON-NLS-2$
+            else
+               return "";
                        case EventConfigurator.COLUMN_MESSAGE:
-                               return ((EventTemplate)element).getMessage();
+            if (element instanceof EventTemplate)
+               return ((EventTemplate)element).getMessage();
+            else
+               return "";
                        case EventConfigurator.COLUMN_DESCRIPTION:
-                               return ((EventTemplate)element).getDescription();
+                               return ((EventObject)element).getDescription();
                }
                return null;
        }
index b57c91e..ba1de35 100644 (file)
@@ -125,7 +125,7 @@ public class EventSelector extends AbstractSelector
                this.eventCode = eventCode;
                if (eventCode != 0)
                {
-                       EventTemplate event = ((NXCSession)ConsoleSharedData.getSession()).findEventTemplateByCode(eventCode);
+                       EventTemplate event = (EventTemplate)((NXCSession)ConsoleSharedData.getSession()).findEventObjectByCode(eventCode);
                        if (event != null)
                        {
                                setText(event.getName());
index 452a812..2f8c0db 100644 (file)
@@ -27,7 +27,7 @@ import org.eclipse.ui.model.WorkbenchLabelProvider;
 import org.netxms.client.NXCSession;
 import org.netxms.client.TableRow;
 import org.netxms.client.events.Alarm;
-import org.netxms.client.events.EventTemplate;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.log.Log;
 import org.netxms.client.log.LogColumn;
 import org.netxms.client.objects.AbstractObject;
@@ -183,8 +183,8 @@ public class LogLabelProvider implements ITableLabelProvider
                                try
                                {
                                        long code = Long.parseLong(value);
-                                       EventTemplate evt = session.findEventTemplateByCode(code);
-                                       return (evt != null) ? evt.getName() : ("[" + code + "]"); //$NON-NLS-1$ //$NON-NLS-2$
+                                       EventObject evo = session.findEventObjectByCode(code);
+                                       return (evo != null) ? evo.getName() : ("[" + code + "]"); //$NON-NLS-1$ //$NON-NLS-2$
                                }
                                catch(NumberFormatException e)
                                {
index 678033a..edcbd8e 100644 (file)
@@ -33,6 +33,7 @@ import org.eclipse.ui.forms.widgets.ImageHyperlink;
 import org.eclipse.ui.model.WorkbenchLabelProvider;
 import org.netxms.client.constants.ColumnFilterType;
 import org.netxms.client.constants.Severity;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.events.EventTemplate;
 import org.netxms.client.log.ColumnFilter;
 import org.netxms.ui.eclipse.console.resources.SharedIcons;
@@ -123,11 +124,11 @@ public class EventConditionEditor extends ConditionEditor
       {
          setSelectedOperation(initialFilter.isNegated() ? 1 : 0);
          eventCode = initialFilter.getNumericValue();
-         EventTemplate e = ConsoleSharedData.getSession().findEventTemplateByCode(eventCode);
-         if (e != null)
+         EventObject o = ConsoleSharedData.getSession().findEventObjectByCode(eventCode);
+         if (o != null && o instanceof EventTemplate)
          {
-            objectName.setText(e.getName());
-            objectName.setImage(labelProvider.getImage(e));
+            objectName.setText(o.getName());
+            objectName.setImage(labelProvider.getImage(o));
          }
          else
          {
index 43d8154..90640b5 100644 (file)
@@ -24,7 +24,7 @@ import org.eclipse.jface.viewers.ViewerComparator;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.widgets.TableColumn;
 import org.netxms.client.NXCSession;
-import org.netxms.client.events.EventTemplate;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.snmp.SnmpTrap;
 import org.netxms.ui.eclipse.shared.ConsoleSharedData;
 import org.netxms.ui.eclipse.snmp.Messages;
@@ -68,10 +68,10 @@ public class SnmpTrapComparator extends ViewerComparator
                                rc = trap1.getObjectId().compareTo(trap2.getObjectId());
                                break;
                        case SnmpTrapEditor.COLUMN_EVENT:
-                               EventTemplate evt1 = session.findEventTemplateByCode(trap1.getEventCode());
-                               EventTemplate evt2 = session.findEventTemplateByCode(trap2.getEventCode());
-                               String name1 = (evt1 != null) ? evt1.getName() : Messages.get().SnmpTrapComparator_Unknown;
-                               String name2 = (evt2 != null) ? evt2.getName() : Messages.get().SnmpTrapComparator_Unknown;
+                               EventObject evo1 = session.findEventObjectByCode(trap1.getEventCode());
+                               EventObject evo2 = session.findEventObjectByCode(trap2.getEventCode());
+                               String name1 = (evo1 != null) ? evo1.getName() : Messages.get().SnmpTrapComparator_Unknown;
+                               String name2 = (evo2 != null) ? evo2.getName() : Messages.get().SnmpTrapComparator_Unknown;
                                rc = name1.compareToIgnoreCase(name2);
                                break;
                        case SnmpTrapEditor.COLUMN_DESCRIPTION:
index ad8820d..9449d6b 100644 (file)
@@ -22,7 +22,7 @@ import org.eclipse.jface.viewers.ILabelProviderListener;
 import org.eclipse.jface.viewers.ITableLabelProvider;
 import org.eclipse.swt.graphics.Image;
 import org.netxms.client.NXCSession;
-import org.netxms.client.events.EventTemplate;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.snmp.SnmpTrap;
 import org.netxms.ui.eclipse.shared.ConsoleSharedData;
 import org.netxms.ui.eclipse.snmp.Messages;
@@ -67,8 +67,8 @@ public class SnmpTrapLabelProvider implements ITableLabelProvider
                        case SnmpTrapEditor.COLUMN_TRAP_OID:
                                return trap.getObjectId().toString();
                        case SnmpTrapEditor.COLUMN_EVENT:
-                               EventTemplate evt = session.findEventTemplateByCode(trap.getEventCode());
-                               return (evt != null) ? evt.getName() : Messages.get().SnmpTrapLabelProvider_Unknown;
+                               EventObject evo = session.findEventObjectByCode(trap.getEventCode());
+                               return (evo != null) ? evo.getName() : Messages.get().SnmpTrapLabelProvider_Unknown;
                        case SnmpTrapEditor.COLUMN_DESCRIPTION:
                                return trap.getDescription();
                }
index 626a5ad..ddac263 100644 (file)
@@ -24,7 +24,7 @@ import org.eclipse.jface.viewers.ViewerComparator;
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.widgets.TableColumn;
 import org.netxms.client.NXCSession;
-import org.netxms.client.events.EventTemplate;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.snmp.SnmpTrap;
 import org.netxms.ui.eclipse.serverconfig.dialogs.SelectSnmpTrapDialog;
 import org.netxms.ui.eclipse.shared.ConsoleSharedData;
@@ -64,10 +64,10 @@ public class SnmpTrapComparator extends ViewerComparator
                                rc = trap1.getObjectId().compareTo(trap2.getObjectId());
                                break;
                        case SelectSnmpTrapDialog.COLUMN_EVENT:
-                               EventTemplate evt1 = session.findEventTemplateByCode(trap1.getEventCode());
-                               EventTemplate evt2 = session.findEventTemplateByCode(trap2.getEventCode());
-                               String name1 = (evt1 != null) ? evt1.getName() : ("[" + Integer.toString(trap1.getEventCode()) + "]"); //$NON-NLS-1$ //$NON-NLS-2$
-                               String name2 = (evt2 != null) ? evt2.getName() : ("[" + Integer.toString(trap2.getEventCode()) + "]"); //$NON-NLS-1$ //$NON-NLS-2$
+                          EventObject evo1 = session.findEventObjectByCode(trap1.getEventCode());
+            EventObject evo2 = session.findEventObjectByCode(trap2.getEventCode());
+                               String name1 = (evo1 != null) ? evo1.getName() : ("[" + Integer.toString(trap1.getEventCode()) + "]"); //$NON-NLS-1$ //$NON-NLS-2$
+                               String name2 = (evo2 != null) ? evo2.getName() : ("[" + Integer.toString(trap2.getEventCode()) + "]"); //$NON-NLS-1$ //$NON-NLS-2$
                                rc = name1.compareToIgnoreCase(name2);
                                break;
                        case SelectSnmpTrapDialog.COLUMN_DESCRIPTION:
index 6cf1b09..5b88a8c 100644 (file)
@@ -67,7 +67,7 @@ public class SnmpTrapFilter extends ViewerFilter
    public boolean eventMatch(Object element)
    {
       NXCSession session = (NXCSession)ConsoleSharedData.getSession();
-      if(session.findEventTemplateByCode(((SnmpTrap)element).getEventCode()).toString().toLowerCase().contains(filterString))
+      if(session.findEventObjectByCode(((SnmpTrap)element).getEventCode()).toString().toLowerCase().contains(filterString))
          return true;
       return false;
    }
index 247e49d..e41d65e 100644 (file)
@@ -22,7 +22,7 @@ import org.eclipse.jface.viewers.ITableLabelProvider;
 import org.eclipse.jface.viewers.LabelProvider;
 import org.eclipse.swt.graphics.Image;
 import org.netxms.client.NXCSession;
-import org.netxms.client.events.EventTemplate;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.snmp.SnmpTrap;
 import org.netxms.ui.eclipse.serverconfig.dialogs.SelectSnmpTrapDialog;
 import org.netxms.ui.eclipse.shared.ConsoleSharedData;
@@ -55,8 +55,8 @@ public class TrapListLabelProvider extends LabelProvider implements ITableLabelP
                        case SelectSnmpTrapDialog.COLUMN_OID:
                                return trap.getObjectId().toString();
                        case SelectSnmpTrapDialog.COLUMN_EVENT:
-                               EventTemplate evt = session.findEventTemplateByCode(trap.getEventCode());
-                               return (evt != null) ? evt.getName() : ("[" + Integer.toString(trap.getEventCode()) + "]"); //$NON-NLS-1$ //$NON-NLS-2$
+                               EventObject evo = session.findEventObjectByCode(trap.getEventCode());
+                               return (evo != null) ? evo.getName() : ("[" + Integer.toString(trap.getEventCode()) + "]"); //$NON-NLS-1$ //$NON-NLS-2$
                        case SelectSnmpTrapDialog.COLUMN_DESCRIPTION:
                                return trap.getDescription();
                }
index 1ba8c18..bca79a5 100644 (file)
@@ -64,6 +64,7 @@ import org.netxms.base.NXCommon;
 import org.netxms.client.NXCSession;
 import org.netxms.client.Script;
 import org.netxms.client.datacollection.DciSummaryTableDescriptor;
+import org.netxms.client.events.EventObject;
 import org.netxms.client.events.EventProcessingPolicyRule;
 import org.netxms.client.events.EventTemplate;
 import org.netxms.client.market.Repository;
@@ -116,7 +117,7 @@ public class ExportFileBuilder extends ViewPart implements ISaveablePart
    private TableViewer summaryTableViewer;
        private Action actionSave;
        private Action actionPublish;
-       private Map<Long, EventTemplate> events = new HashMap<Long, EventTemplate>();
+       private Map<Long, EventObject> events = new HashMap<Long, EventObject>();
        private Map<Long, Template> templates = new HashMap<Long, Template>();
        private Map<Long, SnmpTrap> traps = new HashMap<Long, SnmpTrap>();
        private Map<UUID, EventProcessingPolicyRule> rules = new HashMap<UUID, EventProcessingPolicyRule>();
@@ -878,8 +879,8 @@ public class ExportFileBuilder extends ViewPart implements ISaveablePart
        {
       final long[] eventList = new long[events.size()];
       int i = 0;
-      for(EventTemplate t : events.values())
-         eventList[i++] = t.getCode();
+      for(EventObject o : events.values())
+         eventList[i++] = o.getCode();
       
       final long[] templateList = new long[templates.size()];
       i = 0;
@@ -1134,7 +1135,7 @@ public class ExportFileBuilder extends ViewPart implements ISaveablePart
                                                @Override
                                                public void run()
                                                {
-                                                  for(EventTemplate e : session.findMultipleEventTemplates(eventCodes.toArray(new Long[eventCodes.size()])))
+                                                  for(EventObject e : session.findMultipleEventObjects(eventCodes.toArray(new Long[eventCodes.size()])))
                                                   {
                                                      events.put(e.getCode(), e);
                                                   }
@@ -1176,9 +1177,9 @@ public class ExportFileBuilder extends ViewPart implements ISaveablePart
                        setModified();
                        if (eventCodes.size() > 0)
                        {
-                               for(EventTemplate e : session.findMultipleEventTemplates(eventCodes.toArray(new Long[eventCodes.size()])))
+                               for(EventObject o : session.findMultipleEventObjects(eventCodes.toArray(new Long[eventCodes.size()])))
                                {
-                                  events.put(e.getCode(), e);
+                                  events.put(o.getCode(), o);
                                }
                                eventViewer.setInput(events.values().toArray());
                        };
@@ -1209,9 +1210,9 @@ public class ExportFileBuilder extends ViewPart implements ISaveablePart
                        setModified();
                        if (eventCodes.size() > 0)
                        {
-                               for(EventTemplate e : session.findMultipleEventTemplates(eventCodes.toArray(new Long[eventCodes.size()])))
+                               for(EventObject o : session.findMultipleEventObjects(eventCodes.toArray(new Long[eventCodes.size()])))
                                {
-                                  events.put(e.getCode(), e);
+                                  events.put(o.getCode(), o);
                                }
                                eventViewer.setInput(events.values().toArray());
                        };
index d56187b..049032b 100644 (file)
@@ -39,7 +39,7 @@ import org.eclipse.ui.forms.events.HyperlinkEvent;
 import org.eclipse.ui.forms.widgets.FormToolkit;
 import org.eclipse.ui.forms.widgets.ImageHyperlink;
 import org.netxms.client.NXCSession;
-import org.netxms.client.events.EventTemplate;
+import org.netxms.client.events.EventObject;
 import org.netxms.ui.eclipse.console.resources.SharedIcons;
 import org.netxms.ui.eclipse.eventmanager.widgets.EventSelector;
 import org.netxms.ui.eclipse.serverconfig.Messages;
@@ -407,9 +407,9 @@ public class LogParserRuleEditor extends DashboardComposite
                        }
                        catch(NumberFormatException e)
                        {
-                               EventTemplate t = ((NXCSession)ConsoleSharedData.getSession()).findEventTemplateByName(rule.getEvent().getEvent());
-                               if (t != null)
-                                       eventCode = t.getCode();
+                               EventObject o = ((NXCSession)ConsoleSharedData.getSession()).findEventObjectByName(rule.getEvent().getEvent());
+                               if (o != null)
+                                       eventCode = o.getCode();
                        }
                }
                
index 92619fc..1b97727 100644 (file)
@@ -1300,7 +1300,6 @@ typedef struct
    String charData[MAX_STACK_DEPTH];
    bool trimValue[MAX_STACK_DEPTH];
    bool merge;
-   bool expandEnv;
 } XML_PARSER_STATE;
 
 /**
@@ -1398,7 +1397,7 @@ static void EndElement(void *userData, const char *name)
       ps->level--;
       if (ps->trimValue[ps->level])
          ps->charData[ps->level].trim();
-      ps->stack[ps->level]->addValuePreallocated(ExpandValue(ps->charData[ps->level], true, ps->expandEnv));
+      ps->stack[ps->level]->addValuePreallocated(ExpandValue(ps->charData[ps->level], true, ps->config->isExpansionAllowed()));
    }
 }
 
@@ -1431,7 +1430,6 @@ bool Config::loadXmlConfigFromMemory(const char *xml, int xmlSize, const TCHAR *
    state.parser = parser;
    state.file = (name != NULL) ? name : _T("<mem>");
    state.merge = merge;
-   state.expandEnv = m_allowMacroExpansion;
 
    bool success = (XML_Parse(parser, xml, xmlSize, TRUE) != XML_STATUS_ERROR);
    if (!success)
index 06e874d..4b68749 100644 (file)
@@ -453,7 +453,7 @@ void DCItem::checkThresholds(ItemValue &value)
                PostDciEventWithNames(t->getEventCode(), m_owner->getId(), m_id, "ssssisd",
                                           s_paramNamesReach, m_name, m_description, t->getStringValue(),
                   (const TCHAR *)checkValue, m_id, m_instance, 0);
-                                  EventTemplate *evt = FindEventTemplateByCode(t->getEventCode());
+                                  EventTemplate *evt = (EventTemplate *)FindEventObjectByCode(t->getEventCode());
                                   if (evt != NULL)
                                   {
                                           t->markLastEvent(evt->getSeverity());
@@ -483,7 +483,7 @@ void DCItem::checkThresholds(ItemValue &value)
                                           PostDciEventWithNames(t->getEventCode(), m_owner->getId(), m_id, "ssssisd",
                                                   s_paramNamesReach, m_name, m_description, t->getStringValue(),
                                                   (const TCHAR *)checkValue, m_id, m_instance, 1);
-                                          EventTemplate *evt = FindEventTemplateByCode(t->getEventCode());
+                                          EventTemplate *evt = (EventTemplate *)FindEventObjectByCode(t->getEventCode());
                                           if (evt != NULL)
                                           {
                                                   t->markLastEvent(evt->getSeverity());
@@ -782,7 +782,7 @@ void DCItem::processNewError(bool noInstance, time_t now)
                PostDciEventWithNames(t->getEventCode(), m_owner->getId(), m_id, "ssssisd",
                                           s_paramNamesReach, m_name, m_description, _T(""), _T(""),
                   m_id, m_instance, 0);
-               EventTemplate *evt = FindEventTemplateByCode(t->getEventCode());
+               EventTemplate *evt = (EventTemplate *)FindEventObjectByCode(t->getEventCode());
                                   if (evt != NULL)
                                   {
                                           t->markLastEvent(evt->getSeverity());
@@ -807,7 +807,7 @@ void DCItem::processNewError(bool noInstance, time_t now)
                                           PostDciEventWithNames(t->getEventCode(), m_owner->getId(), m_id, "ssssisd",
                                                   s_paramNamesReach, m_name, m_description, _T(""), _T(""),
                                                   m_id, m_instance, 1);
-                                          EventTemplate *evt = FindEventTemplateByCode(t->getEventCode());
+                                          EventTemplate *evt = (EventTemplate *)FindEventObjectByCode(t->getEventCode());
                                           if (evt != NULL)
                                           {
                                                   t->markLastEvent(evt->getSeverity());
index 576277c..37f08f5 100644 (file)
@@ -65,7 +65,7 @@ BOOL EF_ProcessMessage(ISCSession *session, NXCPMessage *request, NXCPMessage *r
                        if (name != NULL)
                        {
                                DbgPrintf(5, _T("Event specified by name (%s)"), name);
-                               EventTemplate *pt = FindEventTemplateByName(name);
+                               EventTemplate *pt = (EventTemplate *)FindEventObjectByName(name);
                                if (pt != NULL)
                                {
                                        code = pt->getCode();
index 48f35a8..1fa4c7e 100644 (file)
@@ -70,11 +70,11 @@ EPRule::EPRule(ConfigEntry *config)
       m_pdwEventList = (UINT32 *)malloc(sizeof(UINT32) * events->size());
       for(int i = 0; i < events->size(); i++)
       {
-         EventTemplate *e = FindEventTemplateByName(events->get(i)->getSubEntryValue(_T("name"), 0, _T("<unknown>")));
-         if (e != NULL)
+         EventObject *o = FindEventObjectByName(events->get(i)->getSubEntryValue(_T("name"), 0, _T("<unknown>")));
+         if (o != NULL)
          {
-            m_pdwEventList[m_dwNumEvents++] = e->getCode();
-            e->decRefCount();
+            m_pdwEventList[m_dwNumEvents++] = o->getCode();
+            o->decRefCount();
          }
       }
    }
@@ -399,7 +399,12 @@ bool EPRule::matchEvent(UINT32 dwEventCode)
       for(i = 0; i < m_dwNumEvents; i++)
          if (m_pdwEventList[i] & GROUP_FLAG_BIT)
          {
-            /* TODO: check group membership */
+            EventGroup *g = (EventGroup *)FindEventObjectByCode(m_pdwEventList[i]);
+            if (g->isMember(dwEventCode))
+            {
+               bMatch = true;
+               break;
+            }
          }
          else
          {
index 9b888ae..ac8c8fd 100644 (file)
@@ -31,30 +31,101 @@ EventPolicy *g_pEventPolicy = NULL;
 /**
  * Static data
  */
-static RefCountHashMap<UINT32, EventTemplate> m_eventTemplates(true);
+static RefCountHashMap<UINT32, EventObject> m_eventObjects(true);
 static RWLOCK m_rwlockTemplateAccess;
 
 /**
- * Create event template from DB record
+ * Create event object from DB record
  */
-EventTemplate::EventTemplate(DB_RESULT hResult, int row)
+EventObject::EventObject(DB_RESULT hResult, int row)
 {
    m_code = DBGetFieldULong(hResult, row, 0);
-   m_severity = DBGetFieldLong(hResult, row, 1);
-   m_flags = DBGetFieldLong(hResult, row, 2);
-   m_messageTemplate = DBGetField(hResult, row, 3, NULL, 0);
-   m_description = DBGetField(hResult, row, 4, NULL, 0);
-   DBGetField(hResult, row, 5, m_name, MAX_EVENT_NAME);
+   m_description = DBGetField(hResult, row, 1, NULL, 0);
+   DBGetField(hResult, row, 2, m_name, MAX_EVENT_NAME);
+}
+
+/**
+ * Create event object from message
+ */
+EventObject::EventObject(NXCPMessage *msg)
+{
+   m_code = 0;
+   m_description = msg->getFieldAsString(VID_DESCRIPTION);
+   msg->getFieldAsString(VID_NAME, m_name, MAX_EVENT_NAME);
+}
+
+/**
+ * Event object destructor
+ */
+EventObject::~EventObject()
+{
+   free(m_description);
+}
+
+/**
+ * Modify event object from message
+ */
+void EventObject::modifyFromMessage(NXCPMessage *msg)
+{
+   m_code = msg->getFieldAsUInt32(VID_EVENT_CODE);
+   free(m_description);
+   m_description = msg->getFieldAsString(VID_DESCRIPTION);
+   msg->getFieldAsString(VID_NAME, m_name, MAX_EVENT_NAME);
+}
+
+/**
+ * Fill message with event object data
+ */
+void EventObject::fillMessage(NXCPMessage *msg, UINT32 base) const
+{
+   msg->setField(base + 1, m_code);
+   msg->setField(base + 2, m_description);
+   msg->setField(base + 3, m_name);
+}
+
+/**
+ * Convert event object to JSON
+ */
+json_t *EventObject::toJson() const
+{
+   json_t *root = json_object();
+
+   json_object_set_new(root, "name", json_string_t(m_name));
+   json_object_set_new(root, "code", json_integer(m_code));
+   json_object_set_new(root, "description", json_string_t(m_description));
+
+   return root;
+}
+
+/**
+ * Create event template from DB record
+ */
+EventTemplate::EventTemplate(DB_RESULT hResult, int row) : EventObject(hResult, row)
+{
+   m_severity = DBGetFieldLong(hResult, row, 3);
+   m_flags = DBGetFieldLong(hResult, row, 4);
+   m_messageTemplate = DBGetField(hResult, row, 5, NULL, 0);
    m_guid = DBGetFieldGUID(hResult, row, 6);
 }
 
 /**
+ * Create event template from message
+ */
+EventTemplate::EventTemplate(NXCPMessage *msg) : EventObject(msg)
+{
+   m_code = CreateUniqueId(IDG_EVENT);
+   m_severity = msg->getFieldAsInt32(VID_SEVERITY);
+   m_flags = msg->getFieldAsInt32(VID_FLAGS);
+   m_messageTemplate = msg->getFieldAsString(VID_MESSAGE);
+   m_guid = uuid::generate();
+}
+
+/**
  * Event template destructor
  */
 EventTemplate::~EventTemplate()
 {
    free(m_messageTemplate);
-   free(m_description);
 }
 
 /**
@@ -62,13 +133,194 @@ EventTemplate::~EventTemplate()
  */
 json_t *EventTemplate::toJson() const
 {
-   json_t *root = json_object();
-   json_object_set_new(root, "code", json_integer(m_code));
+   json_t *root = EventObject::toJson();
    json_object_set_new(root, "guid", m_guid.toJson());
    json_object_set_new(root, "severity", json_integer(m_severity));
    json_object_set_new(root, "flags", json_integer(m_flags));
    json_object_set_new(root, "message", json_string_t(m_messageTemplate));
-   json_object_set_new(root, "description", json_string_t(m_description));
+
+   return root;
+}
+
+/**
+ * Modify event template from message
+ */
+void EventTemplate::modifyFromMessage(NXCPMessage *msg)
+{
+   EventObject::modifyFromMessage(msg);
+   m_severity = msg->getFieldAsInt32(VID_SEVERITY);
+   m_flags = msg->getFieldAsInt32(VID_FLAGS);
+   free(m_messageTemplate);
+   m_messageTemplate = msg->getFieldAsString(VID_MESSAGE);
+}
+
+/**
+ * Fill message with event template data
+ */
+void EventTemplate::fillMessage(NXCPMessage *msg, UINT32 base) const
+{
+   EventObject::fillMessage(msg, base);
+   msg->setField(base + 4, m_severity);
+   msg->setField(base + 5, m_flags);
+   msg->setField(base + 6, m_messageTemplate);
+}
+
+/**
+ * Save event template to database
+ */
+bool EventTemplate::saveToDatabase() const
+{
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+   DB_STATEMENT hStmt;
+   bool success = false;
+
+   bool recordExists = IsDatabaseRecordExist(hdb, _T("event_cfg"), _T("event_code"), m_code);
+   if (recordExists)
+      hStmt = DBPrepare(hdb, _T("UPDATE event_cfg SET event_name=?,severity=?,flags=?,message=?,description=?, WHERE event_code=?"));
+   else
+      hStmt = DBPrepare(hdb, _T("INSERT INTO event_cfg (event_name,severity,flags,message,description,event_code,guid) VALUES (?,?,?,?,?,?,?)"));
+
+   if (hStmt != NULL)
+   {
+      DBBind(hStmt, 1, DB_SQLTYPE_VARCHAR, m_name, DB_BIND_STATIC);
+      DBBind(hStmt, 2, DB_SQLTYPE_INTEGER, m_severity);
+      DBBind(hStmt, 3, DB_SQLTYPE_INTEGER, m_flags);
+      DBBind(hStmt, 4, DB_SQLTYPE_VARCHAR, m_messageTemplate, DB_BIND_STATIC, MAX_EVENT_MSG_LENGTH - 1);
+      DBBind(hStmt, 5, DB_SQLTYPE_TEXT, m_description, DB_BIND_STATIC);
+      DBBind(hStmt, 6, DB_SQLTYPE_INTEGER, m_code);
+
+      if (!recordExists)
+      {
+         DBBind(hStmt, 7, DB_SQLTYPE_VARCHAR, uuid::generate());
+      }
+      success = DBExecute(hStmt);
+      DBFreeStatement(hStmt);
+   }
+   DBConnectionPoolReleaseConnection(hdb);
+
+   return success;
+}
+
+/**
+ * Create event group from message
+ */
+EventGroup::EventGroup(NXCPMessage *msg) : EventObject(msg)
+{
+   m_code = CreateUniqueId(IDG_EVENT_GROUP);
+   m_eventCodeList = new IntegerArray<UINT32>;
+   msg->getFieldAsInt32Array(VID_EVENT_LIST, m_eventCodeList);
+}
+
+/**
+ * Create event group from DB
+ */
+EventGroup::EventGroup(DB_RESULT result, int row, IntegerArray<UINT32> *memberCache) : EventObject(result, row)
+{
+   m_eventCodeList = new IntegerArray<UINT32>(16, 16);
+   int i = 0;
+   while((i < memberCache->size()) && (memberCache->get(i) != m_code))
+      i += 2;
+   while((i < memberCache->size()) && (memberCache->get(i) == m_code))
+   {
+      m_eventCodeList->add(memberCache->get(i + 1));
+      i += 2;
+   }
+}
+
+/**
+ * Event group destructor
+ */
+EventGroup::~EventGroup()
+{
+   free(m_eventCodeList);
+}
+
+/**
+ * Fill message with event group data
+ */
+void EventGroup::fillMessage(NXCPMessage *msg, UINT32 base) const
+{
+   EventObject::fillMessage(msg, base);
+   msg->setFieldFromInt32Array(base + 4, m_eventCodeList);
+}
+
+/**
+ * Save event group to database
+ */
+bool EventGroup::saveToDatabase() const
+{
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+
+   bool success = DBBegin(hdb);
+   if (success)
+   {
+      DB_STATEMENT hStmt;
+      bool recordExists = IsDatabaseRecordExist(hdb, _T("event_groups"), _T("id"), m_code);
+      if (recordExists)
+         hStmt = DBPrepare(hdb, _T("UPDATE event_groups SET name=?,description=? WHERE id=?"));
+      else
+         hStmt = DBPrepare(hdb, _T("INSERT INTO event_groups (name,description,id) VALUES (?,?,?,?)"));
+
+      if (hStmt != NULL)
+      {
+         DBBind(hStmt, 1, DB_SQLTYPE_VARCHAR, m_name, DB_BIND_STATIC);
+         DBBind(hStmt, 2, DB_SQLTYPE_TEXT, m_description, DB_BIND_STATIC);
+         DBBind(hStmt, 3, DB_SQLTYPE_INTEGER, m_code);
+
+         success = DBExecute(hStmt);
+         DBFreeStatement(hStmt);
+      }
+
+      if (success)
+      {
+         hStmt = DBPrepare(hdb, _T("DELETE FROM event_group_members WHERE group_id=?"));
+         if (hStmt != NULL)
+         {
+            DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_code);
+            success = DBExecute(hStmt);
+            DBFreeStatement(hStmt);
+         }
+         else
+            success = false;
+      }
+
+      if (success)
+      {
+         hStmt = DBPrepare(hdb, _T("INSERT INTO event_group_members (group_id,event_code) VALUES (?,?)"));
+         if (hStmt != NULL)
+         {
+            DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, m_code);
+            for(int i = 0; i < m_eventCodeList->size() && success; i++)
+            {
+               DBBind(hStmt, 2, DB_SQLTYPE_INTEGER, m_eventCodeList->get(i));
+               success = DBExecute(hStmt);
+            }
+            DBFreeStatement(hStmt);
+         }
+      }
+
+      if (success)
+         success = DBCommit(hdb);
+      else
+         DBRollback(hdb);
+   }
+   DBConnectionPoolReleaseConnection(hdb);
+
+   return success;
+}
+
+/**
+ * Convert event group to JSON
+ */
+json_t *EventGroup::toJson() const
+{
+   json_t *root = EventObject::toJson();
+
+   json_t *groupList =  json_array();
+   for(int i = 0; i < m_eventCodeList->size(); i++)
+      json_array_append_new(groupList, json_integer(m_eventCodeList->get(i)));
+   json_object_set_new(root, "groups", groupList);
+
    return root;
 }
 
@@ -772,19 +1024,43 @@ static bool LoadEvents()
 {
    bool success = false;
    DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
-   DB_RESULT hResult = DBSelect(hdb, _T("SELECT event_code,severity,flags,message,description,event_name,guid FROM event_cfg"));
+   DB_RESULT hResult = DBSelect(hdb, _T("SELECT event_code,description,event_name,severity,flags,message,guid FROM event_cfg"));
    if (hResult != NULL)
    {
       int count = DBGetNumRows(hResult);
       for(int i = 0; i < count; i++)
       {
          EventTemplate *t = new EventTemplate(hResult, i);
-         m_eventTemplates.set(t->getCode(), t);
+         m_eventObjects.set(t->getCode(), t);
          t->decRefCount();
       }
-
       DBFreeResult(hResult);
-      success = true;
+
+      IntegerArray<UINT32> memberCache(256, 256);
+      hResult = DBSelect(hdb, _T("SELECT group_id,event_code FROM event_group_members ORDER BY group_id"));
+      if (hResult != NULL)
+      {
+         int count = DBGetNumRows(hResult);
+         for(int i = 0; i < count; i++)
+         {
+            memberCache.add(DBGetFieldULong(hResult, i, 0));
+            memberCache.add(DBGetFieldULong(hResult, i, 1));
+         }
+         DBFreeResult(hResult);
+      }
+
+      hResult = DBSelect(hdb, _T("SELECT id,description,name FROM event_groups"));
+      if (hResult != NULL)
+      {
+         UINT32 numRows = DBGetNumRows(hResult);
+         for(int i = 0; i < numRows; i++)
+         {
+            EventGroup *g = new EventGroup(hResult, i, &memberCache);
+            m_eventObjects.set(g->getCode(), g);
+            g->decRefCount();
+         }
+         success = true;
+      }
    }
    else
    {
@@ -802,7 +1078,7 @@ BOOL InitEventSubsystem()
 {
    BOOL bSuccess;
 
-   // Create template access mutex
+   // Create object access mutex
    m_rwlockTemplateAccess = RWLockCreate();
 
    // Create event queue
@@ -842,18 +1118,18 @@ void ShutdownEventSubsystem()
 void ReloadEvents()
 {
    RWLockWriteLock(m_rwlockTemplateAccess, INFINITE);
-   m_eventTemplates.clear();
+   m_eventObjects.clear();
    LoadEvents();
    RWLockUnlock(m_rwlockTemplateAccess);
 }
 
 /**
- * Delete event template from list
+ * Delete event object from list
  */
-void DeleteEventTemplateFromList(UINT32 eventCode)
+void DeleteEventObjectFromList(UINT32 eventCode)
 {
    RWLockWriteLock(m_rwlockTemplateAccess, INFINITE);
-   m_eventTemplates.remove(eventCode);
+   m_eventObjects.remove(eventCode);
    RWLockUnlock(m_rwlockTemplateAccess);
 }
 
@@ -887,7 +1163,7 @@ static bool RealPostEvent(Queue *queue, UINT64 *eventId, UINT32 eventCode, UINT3
 
    RWLockReadLock(m_rwlockTemplateAccess, INFINITE);
 
-   eventTemplate = m_eventTemplates.get(eventCode);
+   eventTemplate = (EventTemplate *)m_eventObjects.get(eventCode);
    if (eventTemplate != NULL)
    {
       // Template found, create new event
@@ -1227,23 +1503,38 @@ void CreateNXMPEventRecord(String &str, UINT32 eventCode)
    RWLockReadLock(m_rwlockTemplateAccess, INFINITE);
 
    // Find event template
-   EventTemplate *p = m_eventTemplates.get(eventCode);
-   if (p != NULL)
+   EventObject *o = m_eventObjects.get(eventCode);
+   if (o != NULL)
    {
       str.appendFormattedString(_T("\t\t<event id=\"%d\">\n")
-                             _T("\t\t\t<name>%s</name>\n")
-                             _T("\t\t\t<guid>%s</guid>\n")
-                             _T("\t\t\t<code>%d</code>\n")
-                             _T("\t\t\t<severity>%d</severity>\n")
-                             _T("\t\t\t<flags>%d</flags>\n")
-                             _T("\t\t\t<message>%s</message>\n")
-                             _T("\t\t\t<description>%s</description>\n")
-                             _T("\t\t</event>\n"),
-                             p->getCode(), (const TCHAR *)EscapeStringForXML2(p->getName()),
-                             (const TCHAR *)p->getGuid().toString(), p->getCode(), p->getSeverity(),
-                             p->getFlags(), (const TCHAR *)EscapeStringForXML2(p->getMessageTemplate()),
-                             (const TCHAR *)EscapeStringForXML2(p->getDescription()));
-      p->decRefCount();
+                                      _T("\t\t\t<name>%s</name>\n")
+                                      _T("\t\t\t<code>%d</code>\n")
+                                      _T("\t\t\t<description>%s</description>\n"),
+                                      o->getCode(), (const TCHAR *)EscapeStringForXML2(o->getName()),
+                                     (const TCHAR *)EscapeStringForXML2(o->getDescription()));
+      if (eventCode & GROUP_FLAG_BIT)
+      {
+         str.appendFormattedString(_T("\t\t\t<members>\n"));
+         for(int i = 0; i < ((EventGroup *) o)->getMemberCount(); i++)
+         {
+            str.appendFormattedString(_T("\t\t\t\t<code>%d</code>\n"),
+                                     ((EventGroup *) o)->getMember(i));
+         }
+         str.appendFormattedString(_T("\t\t\t</members>\n"));
+      }
+      else
+      {
+         str.appendFormattedString(_T("\t\t\t<guid>%s</guid>\n")
+                                _T("\t\t\t<severity>%d</severity>\n")
+                                _T("\t\t\t<flags>%d</flags>\n")
+                                _T("\t\t\t<message>%s</message>\n")
+                                _T("\t\t</event>\n"),
+                                (const TCHAR *)((EventTemplate *)o)->getGuid().toString(), o->getCode(),
+                                ((EventTemplate *)o)->getSeverity(), ((EventTemplate *)o)->getFlags(),
+                                (const TCHAR *)EscapeStringForXML2(((EventTemplate *)o)->getMessageTemplate()),
+                                (const TCHAR *)EscapeStringForXML2(((EventTemplate *)o)->getDescription()));
+      }
+      o->decRefCount();
    }
 
    RWLockUnlock(m_rwlockTemplateAccess);
@@ -1258,11 +1549,11 @@ bool EventNameFromCode(UINT32 eventCode, TCHAR *buffer)
 
    RWLockReadLock(m_rwlockTemplateAccess, INFINITE);
 
-   EventTemplate *p = m_eventTemplates.get(eventCode);
-   if (p != NULL)
+   EventObject *o = m_eventObjects.get(eventCode);
+   if (o != NULL)
    {
-      _tcscpy(buffer, p->getName());
-      p->decRefCount();
+      _tcscpy(buffer, o->getName());
+      o->decRefCount();
       bRet = true;
    }
    else
@@ -1275,31 +1566,31 @@ bool EventNameFromCode(UINT32 eventCode, TCHAR *buffer)
 }
 
 /**
- * Find event template by code - suitable for external call
+ * Find event object by code - suitable for external call
  */
-EventTemplate *FindEventTemplateByCode(UINT32 eventCode)
+EventObject *FindEventObjectByCode(UINT32 eventCode)
 {
    RWLockReadLock(m_rwlockTemplateAccess, INFINITE);
-   EventTemplate *p = m_eventTemplates.get(eventCode);
+   EventObject *o = m_eventObjects.get(eventCode);
    RWLockUnlock(m_rwlockTemplateAccess);
-   return p;
+   return o;
 }
 
 /**
- * Find event template by name - suitable for external call
+ * Find event object by name - suitable for external call
  */
-EventTemplate *FindEventTemplateByName(const TCHAR *name)
+EventObject *FindEventObjectByName(const TCHAR *name)
 {
-   EventTemplate *result = NULL;
+   EventObject *result = NULL;
 
    RWLockReadLock(m_rwlockTemplateAccess, INFINITE);
-   Iterator<EventTemplate> *it = m_eventTemplates.iterator();
+   Iterator<EventObject> *it = m_eventObjects.iterator();
    while(it->hasNext())
    {
-      EventTemplate *t = it->next();
-      if (!_tcscmp(t->getName(), name))
+      EventObject *o = it->next();
+      if (!_tcscmp(o->getName(), name))
       {
-         result = t;
+         result = o;
          result->incRefCount();
          break;
       }
@@ -1315,11 +1606,11 @@ EventTemplate *FindEventTemplateByName(const TCHAR *name)
  */
 UINT32 NXCORE_EXPORTABLE EventCodeFromName(const TCHAR *name, UINT32 defaultValue)
 {
-       EventTemplate *p = FindEventTemplateByName(name);
-       if (p == NULL)
+   EventObject *o = FindEventObjectByName(name);
+       if (o == NULL)
           return defaultValue;
-       UINT32 code = p->getCode();
-       p->decRefCount();
+       UINT32 code = o->getCode();
+       o->decRefCount();
        return code;
 }
 
@@ -1340,3 +1631,158 @@ const TCHAR NXCORE_EXPORTABLE *GetStatusAsText(int status, bool allCaps)
       return ((status >= STATUS_NORMAL) && (status <= STATUS_TESTING)) ? statusTextSmall[status] : _T("INTERNAL ERROR");
    }
 }
+
+/**
+ * Callback for sending event configuration change notifications
+ */
+static void SendEventDBChangeNotification(ClientSession *session, void *arg)
+{
+   if (session->isAuthenticated() &&
+       (session->checkSysAccessRights(SYSTEM_ACCESS_VIEW_EVENT_DB) ||
+        session->checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB) ||
+        session->checkSysAccessRights(SYSTEM_ACCESS_EPP)))
+      session->postMessage((NXCPMessage *)arg);
+}
+
+/**
+ * Update or create new event object from request
+ */
+UINT32 UpdateEventObject(NXCPMessage *request, json_t *oldValue, json_t *newValue)
+{
+   TCHAR name[MAX_EVENT_NAME];
+   request->getFieldAsString(VID_NAME, name, MAX_EVENT_NAME);
+   if (name == NULL || !IsValidObjectName(name, TRUE))
+   {
+      return RCC_INVALID_OBJECT_NAME;
+   }
+
+   EventObject *obj;
+   UINT32 eventCode = request->getFieldAsUInt32(VID_EVENT_CODE);
+   RWLockWriteLock(m_rwlockTemplateAccess, INFINITE);
+
+   if (eventCode == 0)
+   {
+      if (request->getFieldAsBoolean(VID_IS_GROUP))
+         obj = new EventGroup(request);
+      else
+         obj = new EventTemplate(request);
+      m_eventObjects.set(obj->getCode(), obj);
+   }
+   else
+   {
+      obj = m_eventObjects.get(eventCode);
+      if (obj == NULL)
+      {
+         RWLockUnlock(m_rwlockTemplateAccess);
+         return RCC_INVALID_EVENT_CODE;
+      }
+      oldValue = obj->toJson();
+      obj->modifyFromMessage(request);
+   }
+   newValue = obj->toJson();
+   bool success = obj->saveToDatabase();
+   if (success)
+   {
+      NXCPMessage nmsg;
+      nmsg.setCode(CMD_EVENT_DB_UPDATE);
+      nmsg.setField(VID_NOTIFICATION_CODE, (WORD)NX_NOTIFY_ETMPL_CHANGED);
+      obj->fillMessage(&nmsg, VID_ELEMENT_LIST_BASE);
+      EnumerateClientSessions(SendEventDBChangeNotification, &nmsg);
+   }
+
+   RWLockUnlock(m_rwlockTemplateAccess);
+
+   return success ? RCC_SUCCESS : RCC_DB_FAILURE;
+}
+
+/**
+ * Delete event template
+ */
+UINT32 DeleteEventObject(UINT32 eventCode)
+{
+   UINT32 rcc = RCC_SUCCESS;
+   DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
+   DB_STATEMENT hStmt;
+
+   RWLockWriteLock(m_rwlockTemplateAccess, INFINITE);
+   if (eventCode & GROUP_FLAG_BIT)
+   {
+      if(m_eventObjects.contains(eventCode))
+      {
+         bool success = DBBegin(hdb);
+         if (success)
+         {
+            hStmt = DBPrepare(hdb, _T("DELETE FROM event_groups WHERE id=?"));
+            if (hStmt != NULL)
+            {
+               DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, eventCode);
+               success = DBExecute(hStmt);
+               DBFreeStatement(hStmt);
+            }
+            else
+               success = false;
+            if (success)
+            {
+               hStmt = DBPrepare(hdb, _T("DELETE FROM event_group_members WHERE group_id=?"));
+               if (hStmt != NULL)
+               {
+                  DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, eventCode);
+                  success = DBExecute(hStmt);
+                  DBFreeStatement(hStmt);
+               }
+               else
+                  success = false;
+            }
+            if (success)
+               success = DBCommit(hdb);
+            else
+               DBRollback(hdb);
+         }
+         rcc = success ? RCC_SUCCESS : RCC_DB_FAILURE;
+      }
+   }
+   else if (m_eventObjects.contains(eventCode))
+   {
+      hStmt = DBPrepare(hdb, _T("DELETE FROM event_cfg WHERE event_code=?"));
+      if (hStmt != NULL)
+      {
+         DBBind(hStmt, 1, DB_SQLTYPE_INTEGER, eventCode);
+         rcc = DBExecute(hStmt) ? RCC_SUCCESS : RCC_DB_FAILURE;
+         DBFreeStatement(hStmt);
+      }
+   }
+   else
+      rcc = RCC_INVALID_EVENT_CODE;
+
+   if (rcc == RCC_SUCCESS)
+   {
+      m_eventObjects.remove(eventCode);
+      NXCPMessage nmsg;
+      nmsg.setCode(CMD_EVENT_DB_UPDATE);
+      nmsg.setField(VID_NOTIFICATION_CODE, (WORD)NX_NOTIFY_ETMPL_DELETED);
+      nmsg.setField(VID_EVENT_CODE, eventCode);
+      EnumerateClientSessions(SendEventDBChangeNotification, &nmsg);
+   }
+   RWLockUnlock(m_rwlockTemplateAccess);
+
+   DBConnectionPoolReleaseConnection(hdb);
+   return rcc;
+}
+
+/**
+ * Get event configuration
+ */
+void GetEventConfiguration(NXCPMessage *msg)
+{
+   RWLockWriteLock(m_rwlockTemplateAccess, INFINITE);
+   UINT32 base = VID_ELEMENT_LIST_BASE;
+   msg->setField(VID_NUM_EVENTS, m_eventObjects.size());
+   Iterator<EventObject> *it = m_eventObjects.iterator();
+   while(it->hasNext())
+   {
+      EventObject *o = it->next();
+      o->fillMessage(msg, base);
+      base += 10;
+   }
+   RWLockUnlock(m_rwlockTemplateAccess);
+}
index 5708a0c..d95953c 100644 (file)
@@ -27,7 +27,7 @@
  */
 static bool IsEventExist(const TCHAR *name, Config *config)
 {
-       if (FindEventTemplateByName(name) != NULL)
+       if (FindEventObjectByName(name) != NULL)
                return true;
 
        ConfigEntry *eventsRoot = config->getEntry(_T("/events"));
@@ -154,10 +154,10 @@ bool ValidateConfig(Config *config, UINT32 flags, TCHAR *errorText, int errorTex
                                ConfigEntry *e = event->findEntry(_T("name"));
                                if (e != NULL)
                                {
-                                  EventTemplate *pEvent = FindEventTemplateByName(e->getValue());
-                                       if (pEvent != NULL)
+                                  EventObject *eventObject = FindEventObjectByName(e->getValue());
+                                       if (eventObject != NULL)
                                        {
-                                          pEvent->decRefCount();
+                                          eventObject->decRefCount();
                                                if (!(flags & CFG_IMPORT_REPLACE_EVENT_BY_NAME))
                                                {
                                                        _sntprintf(errorText, errorTextLen, _T("Event with name %s already exist"), e->getValue());
@@ -173,17 +173,17 @@ bool ValidateConfig(Config *config, UINT32 flags, TCHAR *errorText, int errorTex
                        }
                        else
                        {
-                          EventTemplate *pEvent = FindEventTemplateByCode(code);
-                               if (pEvent != NULL)
+                          EventObject *eventObject = FindEventObjectByCode(code);
+                               if (eventObject != NULL)
                                {
                                        if (!(flags & CFG_IMPORT_REPLACE_EVENT_BY_CODE))
                                        {
                                                _sntprintf(errorText, errorTextLen, _T("Event with code %d already exist (existing event name: %s; new event name: %s)"),
-                                                          pEvent->getCode(), pEvent->getName(), event->getSubEntryValue(_T("name"), 0, _T("<unnamed>")));
-                                               pEvent->decRefCount();
+                                                        eventObject->getCode(), eventObject->getName(), event->getSubEntryValue(_T("name"), 0, _T("<unnamed>")));
+                                               eventObject->decRefCount();
                                                goto stop_processing;
                                        }
-               pEvent->decRefCount();
+                                       eventObject->decRefCount();
                                }
                        }
                }
@@ -328,8 +328,8 @@ static UINT32 ImportEvent(ConfigEntry *event)
 static UINT32 ImportTrap(ConfigEntry *trap) // TODO transactions needed?
 {
    UINT32 rcc = RCC_INTERNAL_ERROR;
-       EventTemplate *event = FindEventTemplateByName(trap->getSubEntryValue(_T("event"), 0, _T("")));
-       if (event == NULL)
+       EventObject *eventObject = FindEventObjectByName(trap->getSubEntryValue(_T("event"), 0, _T("")));
+       if (eventObject == NULL)
                return rcc;
 
        uuid guid = trap->getSubEntryValueAsUUID(_T("guid"));
@@ -339,7 +339,7 @@ static UINT32 ImportTrap(ConfigEntry *trap) // TODO transactions needed?
       nxlog_debug(4, _T("ImportTrap: GUID not found in config, generated GUID %s"), (const TCHAR *)guid.toString());
    }
    UINT32 id = ResolveTrapGuid(guid);
-       SNMPTrapConfiguration *trapCfg = new SNMPTrapConfiguration(trap, guid, id, event->getCode());
+       SNMPTrapConfiguration *trapCfg = new SNMPTrapConfiguration(trap, guid, id, eventObject->getCode());
 
        if (!trapCfg->getOid().isValid())
        {
index 77b44a9..1b68535 100644 (file)
@@ -693,7 +693,7 @@ void ClientSession::processingThread()
             deleteAlarmCategory(pMsg);
             break;
          case CMD_LOAD_EVENT_DB:
-            sendEventDB(pMsg->getId());
+            sendEventDB(pMsg);
             break;
          case CMD_SET_EVENT_INFO:
             modifyEventTemplate(pMsg);
@@ -1970,80 +1970,29 @@ void ClientSession::deleteAlarmCategory(NXCPMessage *request)
 /**
  * Send event configuration to client
  */
-void ClientSession::sendEventDB(UINT32 dwRqId)
+void ClientSession::sendEventDB(NXCPMessage *pRequest)
 {
    NXCPMessage msg;
    TCHAR szBuffer[4096];
 
    // Prepare response message
    msg.setCode(CMD_REQUEST_COMPLETED);
-   msg.setId(dwRqId);
+   msg.setId(pRequest->getId());
 
    if (checkSysAccessRights(SYSTEM_ACCESS_VIEW_EVENT_DB) || checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB) || checkSysAccessRights(SYSTEM_ACCESS_EPP))
    {
       if (!(g_flags & AF_DB_CONNECTION_LOST))
       {
          msg.setField(VID_RCC, RCC_SUCCESS);
-         sendMessage(&msg);
-         msg.deleteAllFields();
-
-         // Prepare data message
-         msg.setCode(CMD_EVENT_DB_RECORD);
-         msg.setId(dwRqId);
-
-         DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
-         DB_UNBUFFERED_RESULT hResult = DBSelectUnbuffered(hdb, _T("SELECT event_code,event_name,severity,flags,message,description FROM event_cfg"));
-         if (hResult != NULL)
-         {
-            while(DBFetch(hResult))
-            {
-               msg.setField(VID_EVENT_CODE, DBGetFieldULong(hResult, 0));
-               msg.setField(VID_NAME, DBGetField(hResult, 1, szBuffer, 1024));
-               msg.setField(VID_SEVERITY, DBGetFieldULong(hResult, 2));
-               msg.setField(VID_FLAGS, DBGetFieldULong(hResult, 3));
-
-               DBGetField(hResult, 4, szBuffer, 4096);
-               msg.setField(VID_MESSAGE, szBuffer);
-
-               DBGetField(hResult, 5, szBuffer, 4096);
-               msg.setField(VID_DESCRIPTION, szBuffer);
-
-               sendMessage(&msg);
-               msg.deleteAllFields();
-            }
-            DBFreeResult(hResult);
-         }
-         DBConnectionPoolReleaseConnection(hdb);
-
-         // End-of-list indicator
-         msg.setField(VID_EVENT_CODE, (UINT32)0);
-                       msg.setEndOfSequence();
-      }
-      else
-      {
-         msg.setField(VID_RCC, RCC_DB_CONNECTION_LOST);
+         GetEventConfiguration(&msg);
       }
    }
    else
-   {
       msg.setField(VID_RCC, RCC_ACCESS_DENIED);
-   }
    sendMessage(&msg);
 }
 
 /**
- * Callback for sending event configuration change notifications
- */
-static void SendEventDBChangeNotification(ClientSession *session, void *arg)
-{
-       if (session->isAuthenticated() &&
-       (session->checkSysAccessRights(SYSTEM_ACCESS_VIEW_EVENT_DB) ||
-        session->checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB) ||
-        session->checkSysAccessRights(SYSTEM_ACCESS_EPP)))
-               session->postMessage((NXCPMessage *)arg);
-}
-
-/**
  * Update event template
  */
 void ClientSession::modifyEventTemplate(NXCPMessage *pRequest)
@@ -2053,92 +2002,25 @@ void ClientSession::modifyEventTemplate(NXCPMessage *pRequest)
    // Prepare reply message
    msg.setCode(CMD_REQUEST_COMPLETED);
    msg.setId(pRequest->getId());
-
-   UINT32 eventCode = pRequest->getFieldAsUInt32(VID_EVENT_CODE);
-
    // Check access rights
    if (checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB))
    {
-      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
-
-               bool bEventExist = IsDatabaseRecordExist(hdb, _T("event_cfg"), _T("event_code"), eventCode);
-
-      // Check that we are not trying to create event below 100000
-      if (bEventExist || (eventCode >= FIRST_USER_EVENT_ID))
+      json_t *oldValue, *newValue;
+      UINT32 rcc = UpdateEventObject(pRequest, oldValue, newValue);
+      if (rcc == RCC_SUCCESS)
       {
-         // Prepare and execute SQL query
          TCHAR name[MAX_EVENT_NAME];
          pRequest->getFieldAsString(VID_NAME, name, MAX_EVENT_NAME);
-         if (IsValidObjectName(name, TRUE))
-         {
-            EventTemplate *evt = FindEventTemplateByCode(eventCode);
-            json_t *oldValue = (evt != NULL) ? evt->toJson() : NULL;
-
-            DB_STATEMENT hStmt;
-            if (bEventExist)
-            {
-               hStmt = DBPrepare(hdb, _T("UPDATE event_cfg SET event_name=?,severity=?,flags=?,message=?,description=? WHERE event_code=?"));
-            }
-            else
-            {
-               hStmt = DBPrepare(hdb, _T("INSERT INTO event_cfg (event_name,severity,flags,message,description,event_code,guid) VALUES (?,?,?,?,?,?,?)"));
-            }
-
-            if (hStmt != NULL)
-            {
-               DBBind(hStmt, 1, DB_SQLTYPE_VARCHAR, name, DB_BIND_STATIC);
-               DBBind(hStmt, 2, DB_SQLTYPE_INTEGER, pRequest->getFieldAsInt32(VID_SEVERITY));
-               DBBind(hStmt, 3, DB_SQLTYPE_INTEGER, pRequest->getFieldAsInt32(VID_FLAGS));
-               DBBind(hStmt, 4, DB_SQLTYPE_VARCHAR, pRequest->getFieldAsString(VID_MESSAGE), DB_BIND_DYNAMIC, MAX_EVENT_MSG_LENGTH - 1);
-               DBBind(hStmt, 5, DB_SQLTYPE_TEXT, pRequest->getFieldAsString(VID_DESCRIPTION), DB_BIND_DYNAMIC);
-               DBBind(hStmt, 6, DB_SQLTYPE_INTEGER, eventCode);
-               if (!bEventExist)
-               {
-                  DBBind(hStmt, 7, DB_SQLTYPE_VARCHAR, uuid::generate());
-               }
-
-               if (DBExecute(hStmt))
-               {
-                  msg.setField(VID_RCC, RCC_SUCCESS);
-                  ReloadEvents();
-
-                                          NXCPMessage nmsg(pRequest);
-                                          nmsg.setCode(CMD_EVENT_DB_UPDATE);
-                                          nmsg.setField(VID_NOTIFICATION_CODE, (WORD)NX_NOTIFY_ETMPL_CHANGED);
-                                          EnumerateClientSessions(SendEventDBChangeNotification, &nmsg);
-
-                                          evt = FindEventTemplateByCode(eventCode);
-                                          json_t *newValue = (evt != NULL) ? evt->toJson() : NULL;
-                                          writeAuditLogWithValues(AUDIT_SYSCFG, true, 0, oldValue, newValue, _T("Event template %s [%d] modified"), name, eventCode);
-                                          json_decref(newValue);
-               }
-               else
-               {
-                  msg.setField(VID_RCC, RCC_DB_FAILURE);
-               }
-               DBFreeStatement(hStmt);
-            }
-            else
-            {
-               msg.setField(VID_RCC, RCC_DB_FAILURE);
-            }
-            json_decref(oldValue);
-         }
-         else
-         {
-            msg.setField(VID_RCC, RCC_INVALID_OBJECT_NAME);
-         }
-      }
-      else
-      {
-         msg.setField(VID_RCC, RCC_INVALID_EVENT_CODE);
+         writeAuditLogWithValues(AUDIT_SYSCFG, true, 0, oldValue, newValue, _T("Event template %s [%d] modified"), name, pRequest->getFieldAsUInt32(VID_EVENT_CODE));
       }
-      DBConnectionPoolReleaseConnection(hdb);
+      json_decref(oldValue);
+      json_decref(newValue);
+      msg.setField(VID_RCC, rcc);
    }
    else
    {
       msg.setField(VID_RCC, RCC_ACCESS_DENIED);
-      writeAuditLog(AUDIT_SYSCFG, false, 0, _T("Access denied on modify event template [%d]"), eventCode);
+      writeAuditLog(AUDIT_SYSCFG, false, 0, _T("Access denied on modify event template [%d]"), pRequest->getFieldAsUInt32(VID_EVENT_CODE)); // TODO change message
    }
 
    // Send response
@@ -2162,28 +2044,11 @@ void ClientSession::deleteEventTemplate(NXCPMessage *pRequest)
    // Check access rights
    if (checkSysAccessRights(SYSTEM_ACCESS_EDIT_EVENT_DB) && (dwEventCode >= FIRST_USER_EVENT_ID))
    {
-      DB_HANDLE hdb = DBConnectionPoolAcquireConnection();
-      TCHAR szQuery[256];
-      _sntprintf(szQuery, 256, _T("DELETE FROM event_cfg WHERE event_code=%d"), dwEventCode);
-      if (DBQuery(hdb, szQuery))
-      {
-         DeleteEventTemplateFromList(dwEventCode);
-
-                       NXCPMessage nmsg;
-                       nmsg.setCode(CMD_EVENT_DB_UPDATE);
-                       nmsg.setField(VID_NOTIFICATION_CODE, (WORD)NX_NOTIFY_ETMPL_DELETED);
-                       nmsg.setField(VID_EVENT_CODE, dwEventCode);
-                       EnumerateClientSessions(SendEventDBChangeNotification, &nmsg);
-
-         msg.setField(VID_RCC, RCC_SUCCESS);
-
+      UINT32 rcc = DeleteEventObject(dwEventCode);
+      if (rcc == RCC_SUCCESS)
                        writeAuditLog(AUDIT_SYSCFG, true, 0, _T("Event template [%d] deleted"), dwEventCode);
-      }
-      else
-      {
-         msg.setField(VID_RCC, RCC_DB_FAILURE);
-      }
-      DBConnectionPoolReleaseConnection(hdb);
+
+      msg.setField(VID_RCC, rcc);
    }
    else
    {
index a98ef68..685e0a0 100644 (file)
@@ -557,7 +557,7 @@ static void SyslogParserCallback(UINT32 eventCode, const TCHAR *eventName, const
 static bool EventNameResolver(const TCHAR *name, UINT32 *code)
 {
        bool success = false;
-       EventTemplate *event = FindEventTemplateByName(name);
+       EventObject *event = FindEventObjectByName(name);
        if (event != NULL)
        {
                *code = event->getCode();
index b2484cf..07ff748 100644 (file)
@@ -531,7 +531,7 @@ private:
    void getAlarmCategories(UINT32 requestId);
    void modifyAlarmCategory(NXCPMessage *pRequest);
    void deleteAlarmCategory(NXCPMessage *pRequest);
-   void sendEventDB(UINT32 dwRqId);
+   void sendEventDB(NXCPMessage *pRequest);
    void modifyEventTemplate(NXCPMessage *pRequest);
    void deleteEventTemplate(NXCPMessage *pRequest);
    void generateEventCode(UINT32 dwRqId);
index decb28e..4355355 100644 (file)
 #define EVENTLOG_MAX_MESSAGE_SIZE   255
 #define EVENTLOG_MAX_USERTAG_SIZE   63
 
+class EventObject : public RefCountObject
+{
+protected:
+   UINT32 m_code;
+   TCHAR m_name[MAX_EVENT_NAME];
+   TCHAR *m_description;
+
+   EventObject(DB_RESULT hResult, int row);
+   EventObject(NXCPMessage *msg);
+   ~EventObject();
+
+
+public:
+   UINT32 getCode() const { return m_code; }
+   const TCHAR *getName() const { return m_name; }
+   const TCHAR *getDescription() const { return m_description; }
+
+   virtual void modifyFromMessage(NXCPMessage *msg);
+   virtual void fillMessage(NXCPMessage *msg, UINT32 base) const;
+   virtual bool saveToDatabase() const = 0;
+
+   virtual json_t *toJson() const;
+};
+
 /**
  * Event template
  */
-class EventTemplate : public RefCountObject
+class EventTemplate : public EventObject
 {
 private:
-   UINT32 m_code;
    int m_severity;
-   uuid m_guid;
-   TCHAR m_name[MAX_EVENT_NAME];
    UINT32 m_flags;
    TCHAR *m_messageTemplate;
-   TCHAR *m_description;
+   uuid m_guid;
 
 protected:
    virtual ~EventTemplate();
 
 public:
    EventTemplate(DB_RESULT hResult, int row);
+   EventTemplate(NXCPMessage *msg);
 
-   UINT32 getCode() const { return m_code; }
    int getSeverity() const { return m_severity; }
-   const uuid& getGuid() const { return m_guid; }
-   const TCHAR *getName() const { return m_name; }
    UINT32 getFlags() const { return m_flags; }
+   const uuid& getGuid() const { return m_guid; }
    const TCHAR *getMessageTemplate() const { return m_messageTemplate; }
-   const TCHAR *getDescription() const { return m_description; }
 
-   json_t *toJson() const;
+   virtual void modifyFromMessage(NXCPMessage *msg);
+   virtual void fillMessage(NXCPMessage *msg, UINT32 base) const;
+   virtual bool saveToDatabase() const;
+
+   virtual json_t *toJson() const;
+};
+
+/**
+ * Event group
+ */
+class EventGroup : public EventObject
+{
+private:
+   IntegerArray<UINT32> *m_eventCodeList;
+
+protected:
+   ~EventGroup();
+
+public:
+   EventGroup(DB_RESULT result, int row, IntegerArray<UINT32> *memberCache);
+   EventGroup(NXCPMessage *msg);
+
+   virtual void fillMessage(NXCPMessage *msg, UINT32 base) const;
+   virtual bool saveToDatabase() const;
+
+   UINT32 getMemberCount() { return m_eventCodeList->size(); }
+   UINT32 getMember(int index) { return m_eventCodeList->get(index); }
+   bool isMember(UINT32 eventCode) { return m_eventCodeList->contains(eventCode); }
+
+   virtual json_t *toJson() const;
 };
 
 /**
@@ -236,14 +284,17 @@ public:
 BOOL InitEventSubsystem();
 void ShutdownEventSubsystem();
 void ReloadEvents();
-void DeleteEventTemplateFromList(UINT32 eventCode);
+UINT32 UpdateEventObject(NXCPMessage *request, json_t *oldValue, json_t *newValue);
+UINT32 DeleteEventObject(UINT32 eventCode);
+void GetEventConfiguration(NXCPMessage *msg);
+void DeleteEventObjectFromList(UINT32 eventCode);
 void CorrelateEvent(Event *pEvent);
 void CreateNXMPEventRecord(String &str, UINT32 eventCode);
 
 bool EventNameFromCode(UINT32 eventCode, TCHAR *buffer);
 UINT32 NXCORE_EXPORTABLE EventCodeFromName(const TCHAR *name, UINT32 defaultValue = 0);
-EventTemplate *FindEventTemplateByCode(UINT32 eventCode);
-EventTemplate *FindEventTemplateByName(const TCHAR *pszName);
+EventObject *FindEventObjectByCode(UINT32 eventCode);
+EventObject *FindEventObjectByName(const TCHAR *pszName);
 
 bool NXCORE_EXPORTABLE PostEvent(UINT32 eventCode, UINT32 sourceId, const char *format, ...);
 bool NXCORE_EXPORTABLE PostDciEvent(UINT32 eventCode, UINT32 sourceId, UINT32 dciId, const char *format, ...);
index 6cedbeb..56856b0 100644 (file)
@@ -585,6 +585,21 @@ static bool SetSchemaVersion(int version)
 }
 
 /**
+ * Upgrade from V458 to V459
+ */
+static BOOL H_UpgradeFromV458(int currVersion, int newVersion)
+{
+   static const TCHAR *batch =
+            _T("ALTER TABLE event_groups DROP range_start\n")
+            _T("ALTER TABLE event_groups DROP range_end\n")
+            _T("ALTER TABLE event_groups ADD guid varchar(36) not null\n")
+            _T("<END>");
+   CHK_EXEC(SQLBatch(batch))
+   CHK_EXEC(SetSchemaVersion(459));
+   return TRUE;
+}
+
+/**
  * Upgrade from V456 to V457
  */
 static BOOL H_UpgradeFromV457(int currVersion, int newVersion)
@@ -691,6 +706,7 @@ static BOOL H_UpgradeFromV454(int currVersion, int newVersion)
             _T("<END>");
    CHK_EXEC(SQLBatch(batch));
    CHK_EXEC(DBSetNotNullConstraint(g_hCoreDB, _T("interfaces"), _T("parent_iface")));
+
    CHK_EXEC(SetSchemaVersion(455));
    return TRUE;
 }
@@ -11907,6 +11923,7 @@ static struct
    { 455, 456, H_UpgradeFromV455 },
    { 456, 457, H_UpgradeFromV456 },
    { 457, 458, H_UpgradeFromV457 },
+   { 458, 459, H_UpgradeFromV458 },
    { 0, 0, NULL }
 };