Hard refactoring. CodecEngine is associated to a unique stack.
[anna.git] / example / diameter / launcher / Launcher.cpp
index 8f3cacd..f7921e7 100644 (file)
@@ -15,7 +15,9 @@
 // Project
 #include <anna/timex/Engine.hpp>
 #include <anna/statistics/Engine.hpp>
+#include <anna/diameter/codec/functions.hpp>
 #include <anna/diameter/codec/Engine.hpp>
+#include <anna/diameter/codec/EngineManager.hpp>
 #include <anna/http/Transport.hpp>
 #include <anna/diameter/stack/Engine.hpp>
 #include <anna/diameter/helpers/base/functions.hpp>
@@ -35,7 +37,6 @@
 #define SIGUSR2_TASKS_OUTPUT_FILENAME "./sigusr2.out"
 
 
-
 const char *ServicesDTD = "\
 <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
 <!-- Diameter services DTD -->\n\
@@ -43,22 +44,27 @@ const char *ServicesDTD = "\
 <!ELEMENT services (stack*, node*)>\n\
 \n\
 <!ELEMENT stack EMPTY>\n\
-<!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED>\n\
+<!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED validationMode (BeforeEncoding | AfterDecoding | Always | Never) #IMPLIED validationDepth (Complete | FirstError) #IMPLIED fixMode (BeforeEncoding | AfterDecoding | Always | Never) #IMPLIED ignoreFlagsOnValidation (yes | no) #IMPLIED>\n\
 <!--\n\
    Stack record\n\
 \n\
-   id:         Normally the id corresponds to the Application-Id for which the dictionary provided is designed\n\
-               (in multistack applications, it shall be mandatory respect such association to know the stack used\n\
-               for processed messages).\n\
-   dictionary: Path to the dictionary file\n\
+    id:                      Normally the id corresponds to the Application-Id for which the dictionary provided is designed\n\
+                             (in multistack applications, it shall be mandatory respect such association to know the stack used\n\
+                             for processed messages).\n\
+    dictionary:              Path to the dictionary file.\n\
+    validationMode:          Sets the validation mode. Default is 'AfterDecoding'.\n\
+    validationDepth:         Sets the validation depth. Default is 'FirstError'.\n\
+    fixMode:                 Sets the fix mode. Default is 'BeforeEncoding'.\n\
+    ignoreFlagsOnValidation: Ignore flags during message validation. Default is 'no'.\n\
 -->\n\
 \n\
 <!ELEMENT node EMPTY>\n\
-<!ATTLIST node originRealm CDATA #REQUIRED originHost CDATA #IMPLIED cer CDATA #IMPLIED dwr CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>\n\
+<!ATTLIST node originRealm CDATA #REQUIRED applicationId CDATA #REQUIRED originHost CDATA #IMPLIED cer CDATA #IMPLIED dwr CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>\n\
 <!--\n\
    Node record\n\
 \n\
    originRealm:                             Node identifier (Origin-Realm name).\n\
+   applicationId:                           The Application-Id provided must exists as a registered 'stack id'.\n\
    originHost:                              Diameter application host name (system name). If missing, process sets o.s. hostname\n\
                                             Note that if you have two or more realms, the names must be different.\n\
    cer:                                     User defined CER path file to be encoded to establish diameter connections.\n\
@@ -110,8 +116,6 @@ const char *ServicesDTD = "\
 
 
 Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "1.1"), a_communicator(NULL) {
-  a_codecEngine = new anna::diameter::codec::Engine("MyCodecEngine");
-  a_baseProtocolDictionary = NULL;
   a_timeEngine = NULL;
   a_counterRecorder = NULL;
   a_admlMinResolution = 2 * anna::timex::Engine::minResolution; // 2*10 = 20 ms; 1000/20 = 50 ticks per second;
@@ -129,19 +133,25 @@ Launcher::Launcher() : anna::comm::Application("launcher", "DiameterLauncher", "
 
 void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOperation) throw(anna::RuntimeException) {
   //<!ATTLIST stack id CDATA #REQUIRED dictionary CDATA #REQUIRED>
-  const anna::xml::Attribute  *id, *dictionary;
+  const anna::xml::Attribute *id, *dictionary;
 
-  // <!ATTLIST node originRealm CDATA #REQUIRED originHost CDATA #IMPLIED cer CDATA #IMPLIED dwr CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>
-  const anna::xml::Attribute  *originRealm, *originHost, *cer, *dwr, *allowedInactivityTime, *tcpConnectDelay,
-                              *answersTimeout, *ceaTimeout, *watchdogPeriod, *entity, *entityServerSessions,
-                              *diameterServer, *diameterServerSessions, *balance, *sessionBasedModelsClientSocketSelection,
-                              *retries, *log, *splitLog, *detailedLog, *dumpLog, *burstLog;
+  // <!ATTLIST node originRealm CDATA #REQUIRED applicationId CDATA #REQUIRED originHost CDATA #IMPLIED cer CDATA #IMPLIED dwr CDATA #IMPLIED allowedInactivityTime CDATA #IMPLIED tcpConnectDelay CDATA #IMPLIED answersTimeout CDATA #IMPLIED ceaTimeout CDATA #IMPLIED watchdogPeriod CDATA #IMPLIED entity CDATA #IMPLIED entityServerSessions CDATA #IMPLIED diameterServer CDATA #IMPLIED diameterServerSessions CDATA #IMPLIED balance (yes | no) #IMPLIED sessionBasedModelsClientSocketSelection (SessionIdLowPart | SessionIdHighPart | SessionIdOptionalPart | RoundRobin) #IMPLIED retries CDATA #IMPLIED log CDATA #IMPLIED splitLog (yes | no) #IMPLIED detailedLog (yes | no) #IMPLIED dumpLog (yes | no) #IMPLIED burstLog (yes | no) #IMPLIED>
+  const anna::xml::Attribute *originRealm, *appId, *originHost, *cer, *dwr, *allowedInactivityTime, *tcpConnectDelay,
+  *answersTimeout, *ceaTimeout, *watchdogPeriod, *entity, *entityServerSessions,
+  *diameterServer, *diameterServerSessions, *balance, *sessionBasedModelsClientSocketSelection,
+  *retries, *log, *splitLog, *detailedLog, *dumpLog, *burstLog;
 
   // Never clear services content from here (append new data from xml). At the moment no node removing is implemented in this process
 
   // Stacks
   anna::diameter::stack::Engine &stackEngine = anna::diameter::stack::Engine::instantiate();
   anna::diameter::stack::Dictionary *d;
+  const anna::diameter::stack::Dictionary *bpd = NULL; // base protocol dictionary
+
+  // Codec engine manager:
+  anna::diameter::codec::EngineManager &em = anna::diameter::codec::EngineManager::instantiate();
+  anna::diameter::codec::Engine *ce;
+
   ///////////////////////////////////////////
   // APPLICATION MESSAGE OAM MODULE SCOPES //
   ///////////////////////////////////////////
@@ -151,6 +161,7 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp
   static int scope_id = 3;
   bool id_0_registered = false;
   unsigned int id_value;
+  std::string codecEngineName;
 
   for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
     std::string nodeName = (*it)->getName();
@@ -163,7 +174,7 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp
 
       try {
         d = stackEngine.createDictionary(id_value, dictionary->getValue());
-        getCodecEngine()->setDictionary(d);
+        LOGDEBUG(anna::Logger::debug(anna::functions::asString("Created dictionary (%p) for stack id %llu", d, id_value), ANNA_FILE_LOCATION));
 
         // OAM module for counters:
         appMsgOamModule.createStackCounterScope(scope_id, id_value /* application-id */);
@@ -174,9 +185,47 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp
         throw ex;
       }
 
-      if (id_value == 0)
+      if (id_value == 0) {
         id_0_registered = true;
-        a_baseProtocolDictionary = d;
+        bpd = d;
+      }
+
+      // Create codec engine and register it in the codec engine manager:
+      codecEngineName = anna::functions::asString("CodecEngineForStackId_%llu", id_value);
+      ce = new anna::diameter::codec::Engine(codecEngineName.c_str(), d);
+      em.registerCodecEngine(id_value, ce);
+
+      // Codec engine configuration:
+      const anna::xml::Attribute *vm_attr = (*it)->getAttribute("validationMode", false /* no exception */);
+      const anna::xml::Attribute *vd_attr = (*it)->getAttribute("validationDepth", false /* no exception */);
+      const anna::xml::Attribute *fm_attr = (*it)->getAttribute("fixMode", false /* no exception */);
+      const anna::xml::Attribute *if_attr = (*it)->getAttribute("ignoreFlags", false /* no exception */);
+
+      std::string vm_value = vm_attr ? vm_attr->getValue() : "AfterDecoding";
+      std::string vd_value = vd_attr ? vd_attr->getValue() : "FirstError";
+      std::string fm_value = fm_attr ? fm_attr->getValue() : "BeforeEncoding";
+
+      anna::diameter::codec::Engine::ValidationMode::_v vm;
+      if (vm_value == "BeforeEncoding") vm = anna::diameter::codec::Engine::ValidationMode::BeforeEncoding;
+      else if (vm_value == "AfterDecoding") vm = anna::diameter::codec::Engine::ValidationMode::AfterDecoding;
+      else if (vm_value == "Always") vm = anna::diameter::codec::Engine::ValidationMode::Always;
+      else if (vm_value == "Never") vm = anna::diameter::codec::Engine::ValidationMode::Never;
+      ce->setValidationMode(vm);
+
+      anna::diameter::codec::Engine::ValidationDepth::_v vd;
+      if (vd_value == "Complete") vd = anna::diameter::codec::Engine::ValidationDepth::Complete;
+      else if (vd_value == "FirstError") vd = anna::diameter::codec::Engine::ValidationDepth::FirstError;
+      ce->setValidationDepth(vd);
+
+      anna::diameter::codec::Engine::FixMode::_v fm;
+      if (fm_value == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding;
+      else if (fm_value == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding;
+      else if (fm_value == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
+      else if (fm_value == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
+      ce->setFixMode(fm);
+
+      bool if_value = (if_attr ? (if_attr->getValue() == "yes") : false);
+      ce->ignoreFlagsOnValidation(if_value);
     }
   }
 
@@ -184,26 +233,26 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp
   std::cout << "Stacks currently loaded:" << std::endl;
   std::cout << anna::functions::tab(stackEngine.asString(false /* light */)) << std::endl;
 
-
-  // Codec engine adjustments:
-  // Auto stack selection based on Application-ID:
+  // Basic checking for multistack:
   bool multistack = (stackEngine.stack_size() > 1);
   if (multistack) {
-    getCodecEngine()->selectStackWithApplicationId(true);
-    // In multistack, id = 0 MUST be registered:
-    if (!id_0_registered)
+    if(!id_0_registered)
       throw anna::RuntimeException("In multistack applications is mandatory register a stack id = 0 using a dictionary which contains the needed elements to build base protocol messages (CER/A, DWR/A, DPR/A, STR/A, etc.)", ANNA_FILE_LOCATION);
   }
-  else {
-    a_baseProtocolDictionary = d;
+  else { // monostack
+    if (!bpd)
+      bpd = ce->getDictionary(); // in mono-stack applications, we understand the existing stack as the used
+                                 // for base protocol, regardless if it is registered with stack id 0 or not
   }
 
+  // REALMS:
   for(anna::xml::Node::const_child_iterator it = servicesNode->child_begin(); it != servicesNode->child_end(); it++) {
     std::string nodeName = (*it)->getName();
 
     if(nodeName == "node") {
       // Input data:
       originRealm = (*it)->getAttribute("originRealm");
+      appId = (*it)->getAttribute("applicationId");
       originHost = (*it)->getAttribute("originHost", false /* no exception */);
       cer = (*it)->getAttribute("cer", false /* no exception */);
       dwr = (*it)->getAttribute("dwr", false /* no exception */);
@@ -232,6 +281,12 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp
         throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
       }
 
+      unsigned int applicationId = appId->getIntegerValue();
+      if (!stackEngine.getDictionary(applicationId)) {
+        std::string msg = "Cannot found a registered stack id with the value of applicationId provided: "; msg += appId->getValue();
+        throw anna::RuntimeException(msg, ANNA_FILE_LOCATION);
+      }
+
       // Engine time measures checking & assignment:
       anna::Millisecond allowedInactivityTimeMs(90000);
       anna::Millisecond tcpConnectDelayMs(200);
@@ -260,7 +315,7 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp
       }
 
       // Create new Node instance /////////////////////////////////////////////////////////////////
-      a_workingNode = new RealmNode(originRealm->getValue(), a_codecEngine, a_baseProtocolDictionary);
+      a_workingNode = new RealmNode(originRealm->getValue(), applicationId, bpd);
       MyDiameterEngine *commEngine = a_workingNode->getMyDiameterEngine();
       /////////////////////////////////////////////////////////////////////////////////////////////
 
@@ -313,12 +368,15 @@ void Launcher::servicesFromXML(const anna::xml::Node* servicesNode, bool eventOp
       // Lazy initialization for comm engine:
       if (eventOperation) commEngine->lazyInitialize();
 
-      // New Node assignment //////////////////////////////////////////////////////////////////////
+      // Node and Codec Engine registration ///////////////////////////////////////////////////////
       a_nodes[originRealm->getValue()] = a_workingNode;
       /////////////////////////////////////////////////////////////////////////////////////////////
     }
   }
 
+  if (!uniqueRealm())
+    a_workingNode = NULL; // by default, mode auto
+
   // Diameter comm engines which are loaded after application start (via management operation 'services') are not really started,
   //  but this don't care because application startComponents() -> initialize() -> do_initialize() -> do nothing.
   // And when stopped, running state is not checked and it will be stopped anyway.
@@ -333,10 +391,10 @@ void Launcher::loadServices(const std::string & xmlPathFile, bool eventOperation
   }
 
   LOGDEBUG(
-    std::string trace = "Loading ADML services file '";
-    trace += xmlPathFile;
-    trace += "'";
-    anna::Logger::debug(trace, ANNA_FILE_LOCATION);
+      std::string trace = "Loading ADML services file '";
+  trace += xmlPathFile;
+  trace += "'";
+  anna::Logger::debug(trace, ANNA_FILE_LOCATION);
   );
   anna::xml::DocumentFile xmlDocument; // has private copy constructor defined but not implemented to avoid inhenrit/copy (is very heavy)
   anna::xml::DTDMemory xmlDTD;
@@ -348,19 +406,19 @@ void Launcher::loadServices(const std::string & xmlPathFile, bool eventOperation
   }
   catch (anna::RuntimeException &ex) {
     LOGWARNING(
-      std::string msg = "Services DTD schema:\n\n";
-      msg += ServicesDTD;
-      anna::Logger::warning(msg, ANNA_FILE_LOCATION);
+        std::string msg = "Services DTD schema:\n\n";
+    msg += ServicesDTD;
+    anna::Logger::warning(msg, ANNA_FILE_LOCATION);
     );
     throw ex;
   }
 
   LOGDEBUG(
-    std::string trace = "Loaded XML file (";
-    trace += xmlPathFile;
-    trace += "):\n";
-    trace += anna::xml::Compiler().apply(rootNode);
-    anna::Logger::debug(trace, ANNA_FILE_LOCATION);
+      std::string trace = "Loaded XML file (";
+  trace += xmlPathFile;
+  trace += "):\n";
+  trace += anna::xml::Compiler().apply(rootNode);
+  anna::Logger::debug(trace, ANNA_FILE_LOCATION);
   );
   servicesFromXML(rootNode, eventOperation);
 }
@@ -407,37 +465,63 @@ anna::Millisecond Launcher::checkTimeMeasure(const std::string &parameter, const
   throw RuntimeException(msg, ANNA_FILE_LOCATION);
 }
 
-RealmNode *Launcher::getWorkingNode() const throw(anna::RuntimeException) {
-
-  if (!a_workingNode)
-    throw RuntimeException("No services yet loaded. Try 'services' operation (via management interface), or restart process using command-line 'services' parameter", ANNA_FILE_LOCATION);
-
-  return a_workingNode;
-}
-
 bool Launcher::setWorkingNode(const std::string &name) throw() {
   bool result = false;
 
-  realm_nodes_nc_it nodeIt = a_nodes.find(name);
+  realm_nodes_it nodeIt = a_nodes.find(name);
   if (nodeIt == a_nodes.end()) {
     LOGWARNING(
-      std::string msg = "Unknown node with name '"; msg += name; msg += "'. Ignoring ...";
-      anna::Logger::warning(msg, ANNA_FILE_LOCATION);
+        std::string msg = "Unknown node with name '"; msg += name; msg += "'. Ignoring ...";
+    anna::Logger::warning(msg, ANNA_FILE_LOCATION);
     );
   }
   else {
-    a_workingNode = nodeIt->second;
+    a_workingNode = const_cast<RealmNode*>(nodeIt->second);
     result = true;
   }
 
   return result;
 }
 
-RealmNode *Launcher::getRealmNode(const std::string &realmName) const throw() {
+RealmNode *Launcher::getRealmNode(const std::string &realmName) const throw(anna::RuntimeException) {
   realm_nodes_it it = a_nodes.find(realmName);
   if (it != a_nodes.end()) return it->second;
+  throw anna::RuntimeException(anna::functions::asString("There is no realm node registered as '%s' (set Origin-Realm avp correctly or force a specific realm with 'node' operation)", realmName.c_str()), ANNA_FILE_LOCATION);
+}
+
+RealmNode *Launcher::getRealmNode(const anna::diameter::codec::Message &message) const throw(anna::RuntimeException) {
+  std::string originRealm = message.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
+  return (getRealmNode(originRealm));
+}
 
-  return NULL; // this never happens
+void Launcher::updateOperatedRealmNodeWithMessage(const anna::diameter::codec::Message &message) throw(anna::RuntimeException) {
+  if (!a_operatedRealm) // priority for working node by mean 'node' operation
+    a_operatedRealm = getRealmNode(message);
+}
+
+RealmNode *Launcher::getOperatedRealm() const throw(anna::RuntimeException) {
+  if(!a_operatedRealm)
+    throw anna::RuntimeException("Realm Node not identified (try to force a specific realm with 'node' operation)", ANNA_FILE_LOCATION);
+
+  return a_operatedRealm;
+}
+
+MyDiameterEntity *Launcher::getOperatedEntity() const throw(anna::RuntimeException) {
+  MyDiameterEntity *result = getOperatedRealm()->getEntity();
+  if (!result)
+    throw anna::RuntimeException("No entity configured for the operated Realm Node", ANNA_FILE_LOCATION);
+  return result;
+}
+
+MyLocalServer *Launcher::getOperatedServer() const throw(anna::RuntimeException) {
+  MyLocalServer *result = getOperatedRealm()->getDiameterServer();
+  if (!result)
+    throw anna::RuntimeException("No local server configured for the operated Realm Node", ANNA_FILE_LOCATION);
+  return result;
+}
+
+MyDiameterEngine *Launcher::getOperatedEngine() const throw(anna::RuntimeException) {
+  return getOperatedRealm()->getMyDiameterEngine(); // never will be NULL
 }
 
 void Launcher::initialize()
@@ -484,12 +568,12 @@ throw(anna::RuntimeException) {
   anna::statistics::Engine::instantiate().enable();
 
   LOGINFORMATION(
-    // Help on startup traces:
-    anna::Logger::information(help(), ANNA_FILE_LOCATION);
-    // Test messages dtd:
-    std::string msg = "\n                     ------------- TESTMESSAGES DTD -------------\n";
-    msg += anna::diameter::codec::MessageDTD;
-    anna::Logger::information(msg, ANNA_FILE_LOCATION);
+      // Help on startup traces:
+      anna::Logger::information(help(), ANNA_FILE_LOCATION);
+  // Test messages dtd:
+  std::string msg = "\n                     ------------- TESTMESSAGES DTD -------------\n";
+  msg += anna::diameter::codec::MessageDTD;
+  anna::Logger::information(msg, ANNA_FILE_LOCATION);
   );
 
   // HTTP Server:
@@ -626,29 +710,6 @@ throw(anna::RuntimeException) {
     a_timeEngine->activate(a_counterRecorderClock); // start clock
   }
 
-
-  // Integration (validation 'Complete' for receiving messages) and debugging (validation also before encoding: 'Always').
-  // If missing 'integrationAndDebugging', default behaviour at engine is: mode 'AfterDecoding', depth 'FirstError':
-  if(cl.exists("integrationAndDebugging")) {
-    getCodecEngine()->setValidationMode(anna::diameter::codec::Engine::ValidationMode::Always);
-    getCodecEngine()->setValidationDepth(anna::diameter::codec::Engine::ValidationDepth::Complete);
-  }
-
-  // Fix mode
-  if(cl.exists("fixMode")) { // BeforeEncoding(default), AfterDecoding, Always, Never
-    std::string fixMode = cl.getValue("fixMode");
-    anna::diameter::codec::Engine::FixMode::_v fm;
-    if (fixMode == "BeforeEncoding") fm = anna::diameter::codec::Engine::FixMode::BeforeEncoding;
-    else if (fixMode == "AfterDecoding") fm = anna::diameter::codec::Engine::FixMode::AfterDecoding;
-    else if (fixMode == "Always") fm = anna::diameter::codec::Engine::FixMode::Always;
-    else if (fixMode == "Never") fm = anna::diameter::codec::Engine::FixMode::Never;
-    else LOGINFORMATION(anna::Logger::information("Unreconized command-line fix mode. Assumed default 'BeforeEncoding'", ANNA_FILE_LOCATION));
-    getCodecEngine()->setFixMode(fm);
-  }
-
-  getCodecEngine()->ignoreFlagsOnValidation(cl.exists("ignoreFlags"));
-
-
   // Log statistics concepts
   if(cl.exists("logStatisticSamples")) {
     std::string list = cl.getValue("logStatisticSamples");
@@ -707,9 +768,9 @@ bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBl
     // Allow colon separator in hex string: we have to remove them before processing with 'fromHexString':
     hexString.erase(std::remove(hexString.begin(), hexString.end(), ':'), hexString.end());
     LOGDEBUG(
-      std::string msg = "Hex string (remove colons if exists): ";
-      msg += hexString;
-      anna::Logger::debug(msg, ANNA_FILE_LOCATION);
+        std::string msg = "Hex string (remove colons if exists): ";
+    msg += hexString;
+    anna::Logger::debug(msg, ANNA_FILE_LOCATION);
     );
     anna::functions::fromHexString(hexString, db);
     // Close file
@@ -721,7 +782,14 @@ bool Launcher::getDataBlockFromHexFile(const std::string &pathfile, anna::DataBl
 }
 
 void Launcher::resetStatistics() throw() {
-  getWorkingNode()->getMyDiameterEngine()->resetStatistics();
+  if (a_workingNode) {
+    a_workingNode->getMyDiameterEngine()->resetStatistics();
+  }
+  else {
+    for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
+      it->second->getMyDiameterEngine()->resetStatistics();
+    }
+  }
 }
 
 void Launcher::resetCounters() throw() {
@@ -732,12 +800,12 @@ void Launcher::resetCounters() throw() {
 
 void Launcher::signalUSR2() throw(anna::RuntimeException) {
   LOGNOTICE(
-    std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
-    msg += SIGUSR2_TASKS_INPUT_FILENAME;
-    msg += "' (results will be written at '";
-    msg += SIGUSR2_TASKS_OUTPUT_FILENAME;
-    msg += "')";
-    anna::Logger::notice(msg, ANNA_FILE_LOCATION);
+      std::string msg = "Captured signal SIGUSR2. Reading tasks at '";
+  msg += SIGUSR2_TASKS_INPUT_FILENAME;
+  msg += "' (results will be written at '";
+  msg += SIGUSR2_TASKS_OUTPUT_FILENAME;
+  msg += "')";
+  anna::Logger::notice(msg, ANNA_FILE_LOCATION);
   );
 
   // Operation:
@@ -752,9 +820,9 @@ void Launcher::signalUSR2() throw(anna::RuntimeException) {
 
   while(getline(in_file, line)) {
     LOGDEBUG(
-      std::string msg = "Processing line: ";
-      msg += line;
-      anna::Logger::debug(msg, ANNA_FILE_LOCATION);
+        std::string msg = "Processing line: ";
+    msg += line;
+    anna::Logger::debug(msg, ANNA_FILE_LOCATION);
     );
 
     try {
@@ -827,7 +895,7 @@ std::string Launcher::help() const throw() {
   result += "\n  <stack id=\"0\" dictionary=\"dictionary.xml\"/>";
   result += "\n";
   result += "\n  <!-- Nodes -->";
-  result += "\n  <node originRealm=\"ADML-client\" entity=\"localhost:3868\"/>";
+  result += "\n  <node originRealm=\"ADML-client\" applicationId=\"0\" entity=\"localhost:3868\"/>";
   result += "\n</services>";
   result += "\n";
   result += "\nServer configuration:";
@@ -837,7 +905,7 @@ std::string Launcher::help() const throw() {
   result += "\n  <stack id=\"0\" dictionary=\"dictionary.xml\"/>";
   result += "\n";
   result += "\n  <!-- Nodes -->";
-  result += "\n  <node originRealm=\"ADML-server\" diameterServer=\"localhost:3868\"/>";
+  result += "\n  <node originRealm=\"ADML-server\" applicationId=\"0\" diameterServer=\"localhost:3868\"/>";
   result += "\n</services>";
   result += "\n";
   result += "\nIf you act as a proxy or a translation agent, you need to combine both former setups, and probably";
@@ -854,8 +922,8 @@ std::string Launcher::help() const throw() {
   result += "\n  <stack id=\"0\" dictionary=\"dictionary_base.xml\"/>";
   result += "\n";
   result += "\n  <!-- Nodes -->";
-  result += "\n  <node originRealm=\"ADML-Rx-client\" entity=\"localhost:3868\" cer=\"cer_Rx.xml\"/>";
-  result += "\n  <node originRealm=\"ADML-Gx-client\" entity=\"localhost:3868\" cer=\"cer_Gx.xml\"/>";
+  result += "\n  <node originRealm=\"ADML-Rx-client\" applicationId=\"16777236\" entity=\"localhost:3868\" cer=\"cer_Rx.xml\"/>";
+  result += "\n  <node originRealm=\"ADML-Gx-client\" applicationId=\"16777238\" entity=\"localhost:3868\" cer=\"cer_Gx.xml\"/>";
   result += "\n</services>";
   result += "\n";
   result += "\n";
@@ -875,11 +943,24 @@ std::string Launcher::help() const throw() {
   result += "\n";
   result += "\nhelp                                 This help.";
   result += "\n";
-  result += "\n---------------------------------------------------------------------------------------- Node selection";
-  result += "\n";
-  result += "\nnode[|<name>]                         Select current working node by mean the registered name.";
-  result += "\n                                      All the subsequent operations will be referred to this node.";
-  result += "\n                                      Without argument, the current node information is retrieved.";
+  result += "\n--------------------------------------------------------------------------------------- Node management";
+  result += "\n";
+  result += "\nnode[|<name>]                         Selects a context working node by mean a registered name.";
+  result += "\n                                      All the subsequent operations will be forced to work with";
+  result += "\n                                      this node, which makes possible some rare scenarios like";
+  result += "\n                                      sending unexpected messages on remote peers. This is also";
+  result += "\n                                      useful for some operations in order to restrict the scope";
+  result += "\n                                      of action (statistics, communication visibility, etc.).";
+  result += "\n                                      Empty parameter will show the current configuration.";
+  result += "\n";
+  result += "\nnode_auto                             Returns to the default behaviour (smart node selection).";
+  result += "\n                                      Depending on the operation, this could imply a global";
+  result += "\n                                      action scope, affecting to all the registered realms.";
+  result += "\n                                      This should be the normal configuration. Take into";
+  result += "\n                                      account that if you fix the working node, this could";
+  result += "\n                                      affect to things like test programming: communication";
+  result += "\n                                      resources will override those which would be inferred";
+  result += "\n                                      from programmed messages Origin-Realm avps.";
   result += "\n";
   result += "\n------------------------------------------------------------------------------------ Parsing operations";
   result += "\n";
@@ -904,8 +985,10 @@ std::string Launcher::help() const throw() {
   result += "\n                                      default '/var/tmp/anna.context.<pid>' will be used.";
   result += "\ncollect                              Reset statistics and counters to start a new test stage of";
   result += "\n                                      performance measurement. Context data can be written at";
-  result += "\n                                      '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'";
+  result += "\n                                      '/var/tmp/anna.context.<pid>' by mean 'kill -10 <pid>'.";
   result += "\n                                      or sending operation 'context|[target file]'.";
+  result += "\n                                     This operation applies over all the registered realm nodes";
+  result += "\n                                      except if one specific working node has been set.";
   result += "\nforceCountersRecord                  Forces dump to file the current counters of the process.";
   result += "\n";
   result += "\n<visibility action>[|<address>:<port>][|socket id]";
@@ -924,20 +1007,18 @@ std::string Launcher::help() const throw() {
   result += "\n";
   result += "\nsendxml2e|<source_file>    Sends xml source file (pathfile) through configured entity.";
   result += "\nsendxml2c|<source_file>    Sends xml source file (pathfile) to client.";
-  result += "\nsendxml|<source_file>      Same as 'sendxml2e'.";
   result += "\nanswerxml2e[|source_file]  Answer xml source file (pathfile) for incoming request with same code from entity.";
   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
   result += "\n                           as many queues as different message codes have been programmed.";
   result += "\nanswerxml2c[|source_file]  Answer xml source file (pathfile) for incoming request with same code from client.";
   result += "\n                           The answer is stored in a FIFO queue for a specific message code, then there are";
   result += "\n                           as many queues as different message codes have been programmed.";
-  result += "\nanswerxml[|source_file]    Same as 'answerxml2c'.";
-  result += "\nanswerxml(2e/2c)           List programmed answers (to entity/client) if no parameter provided.";
-  result += "\nanswerxml(2e/2c)|dump      Write programmed answers (to entity/client) to file 'programmed_answer.<message code>.<sequence>',";
+  result += "\nanswerxml<2e/2c>           List programmed answers (to entity/client) if no parameter provided.";
+  result += "\nanswerxml<2e/2c>|dump      Write programmed answers (to entity/client) to file 'programmed_answer.<message code>.<sequence>',";
   result += "\n                           where 'sequence' is the order of the answer in each FIFO code-queue of programmed answers.";
-  result += "\nanswerxml(2e/2c)|clear     Clear programmed answers (to entity/client).";
-  result += "\nanswerxml(2e/2c)|exhaust   Disable the corresponding queue rotation, which is the default behaviour.";
-  result += "\nanswerxml(2e/2c)|rotate    Enable the corresponding queue rotation, useful in performance tests.";
+  result += "\nanswerxml<2e/2c>|clear     Clear programmed answers (to entity/client).";
+  result += "\nanswerxml<2e/2c>|exhaust   Disable the corresponding queue rotation, which is the default behaviour.";
+  result += "\nanswerxml<2e/2c>|rotate    Enable the corresponding queue rotation, useful in performance tests.";
   result += "\n                           Rotation consists in add again to the queue, each element retrieved for answering.";
   result += "\n";
   result += "\nSend operations are available using hexadecimal content (hex formatted files) which also allow to test";
@@ -945,13 +1026,12 @@ std::string Launcher::help() const throw() {
   result += "\n";
   result += "\nsendhex2e|<source_file>    Sends hex source file (pathfile) through configured entity.";
   result += "\nsendhex2c|<source_file>    Sends hex source file (pathfile) to client.";
-  result += "\nsendhex|<source_file>      Same as 'sendhex2e'.";
   result += "\n";
   result += "\nAnswer programming in hexadecimal is not really neccessary (you could use send primitives) and also";
   result += "\n is intended to be used with decoded messages in order to replace things like hop by hop, end to end,";
   result += "\n subscriber id, session id, etc. Anyway you could use 'decode' operation and then program the xml created.";
   result += "\n";
-  result += "\nIf a request is received, answer map (built with 'answerxml<[2c] or 2e>' operations) will be";
+  result += "\nIf a request is received, answer map (built with 'answerxml<2e/2c>' operations) will be";
   result += "\n checked to find a corresponding programmed answer to be replied(*). If no ocurrence is found,";
   result += "\n or answer message was received, the message is forwarded to the other side (entity or client),";
   result += "\n or nothing but trace when no peer at that side is configured. Answer to client have sense when";
@@ -964,7 +1044,7 @@ std::string Launcher::help() const throw() {
   result += "\n";
   result += "\n(*) sequence values (hop-by-hop and end-to-end), Session-Id and Subscription-Id avps, are mirrored";
   result += "\n    to the peer which sent the request. If user wants to test a specific answer without changing it,";
-  result += "\n    use sendxml/sendhex operations better than programming.";
+  result += "\n    use sendxml<2e/2c>/sendhex<2e/2c> operations better than programming.";
   result += "\n";
   result += "\nBalance ('--balance' command line parameter) could be used to forward server socket receptions through";
   result += "\n entity servers by mean a round-robin algorithm. Both diameter server socket and entity targets should";
@@ -992,6 +1072,12 @@ std::string Launcher::help() const throw() {
   result += "\n";
   result += "\n------------------------------------------------------------------------------------------- Burst tests";
   result += "\n";
+  result += "\nIn order to simplify user experience, burst category operations are only allowed in single realm node";
+  result += "\n configuration. Indeed, you could send messages with incorrect Origin-Realm, and no warning is shown.";
+  result += "\nAll the operations are performed through the unique realm: if you need to use more interfaces, you may";
+  result += "\n launch different ADML instances. Is nonsense to allow burst in a multi-realm configured ADML, because";
+  result += "\n this feature is not able to coordinate the messages.";
+  result += "\n";
   result += "\nburst|<action>[|parameter]     Used for performance testing, we first program diameter requests";
   result += "\n                                messages in order to launch them from client side to the configured";
   result += "\n                                diameter entity. We could start the burst with an initial load";
@@ -1030,7 +1116,9 @@ std::string Launcher::help() const throw() {
   result += "\n                           Adds a new step to the test case with provided identifier. If provided identifier";
   result += "\n                            is not registered yet, a new test case will be created with that value and the";
   result += "\n                            step will be added as the first. For a specific 'id', the steps are stored in";
-  result += "\n                            order as they are programmed";
+  result += "\n                            order as they are programmed. Check possible runtime exceptions when adding a";
+  result += "\n                            new step because those which fail, will be ignored/skipped during test case";
+  result += "\n                            programming giving an incomplete sequence invalid for the testing purpose.";
   result += "\n";
   result += "\n                           <id>: integer number, normally monotonically increased for each test case. Some external";
   result += "\n                                 script/procedure shall clone a test case template in order to build a collection";
@@ -1104,14 +1192,14 @@ std::string Launcher::help() const throw() {
   result += "\n                                         a real unexpected message).";
 
   // TODO(***)
-//  result += "\n                                        The way to identify the test case, is through registered Session-Id values for";
-//  result += "\n                                         programmed requests. But this depends on the type of node. Acting as clients,";
-//  result += "\n                                         requests received have Session-Id values which are already registered with";
-//  result += "\n                                         one test case, causing an error if not found. Acting as servers, requests are";
-//  result += "\n                                         received over a diameter local server from a client which are generating that";
-//  result += "\n                                         Session-Id values. Then we know nothing about such values. The procedure in";
-//  result += "\n                                         this case is find out a test case not-started containing a condition which";
-//  result += "\n                                         comply with the incoming message, and reactivates it.";
+  //  result += "\n                                        The way to identify the test case, is through registered Session-Id values for";
+  //  result += "\n                                         programmed requests. But this depends on the type of node. Acting as clients,";
+  //  result += "\n                                         requests received have Session-Id values which are already registered with";
+  //  result += "\n                                         one test case, causing an error if not found. Acting as servers, requests are";
+  //  result += "\n                                         received over a diameter local server from a client which are generating that";
+  //  result += "\n                                         Session-Id values. Then we know nothing about such values. The procedure in";
+  //  result += "\n                                         this case is find out a test case not-started containing a condition which";
+  //  result += "\n                                         comply with the incoming message, and reactivates it.";
   // The other solution: register Session-Id values for answers send to client from a local diameter server.
 
   result += "\n                                        How to answer: a wait condition for a request will store the incoming message";
@@ -1126,12 +1214,10 @@ std::string Launcher::help() const throw() {
   result += "\n";
   result += "\n                                        Condition format:";
   result += "\n";
-  result += "\n                                           [code]|[bitR]|[ResultCode]|[sessionId]|[hopByHop]|[msisdn]|[imsi]|[serviceContextId]";
+  result += "\n                                           [code]|[bitR]|[hopByHop]|[applicationId]|[sessionId]|[resultCode]|[msisdn]|[imsi]|[serviceContextId]";
   result += "\n";
   result += "\n                                             code: integer number";
   result += "\n                                             bitR: 1 (request), 0 (answer)";
-  result += "\n                                             ResultCode: integer number";
-  result += "\n                                             sessionId: string";
   result += "\n                                             hopByHop: integer number or request send step reference: #<step number>";
   result += "\n";
   result += "\n                                                       Using the hash reference, you would indicate a specific wait condition";
@@ -1140,6 +1226,9 @@ std::string Launcher::help() const throw() {
   result += "\n                                                       This 'hop-by-hop' variant eases the wait condition for answers in the";
   result += "\n                                                        safest way.";
   result += "\n";
+  result += "\n                                             applicationId: integer number";
+  result += "\n                                             sessionId: string";
+  result += "\n                                             resultCode: integer number";
   result += "\n                                             msisdn: string";
   result += "\n                                             imsi: string";
   result += "\n                                             serviceContextId: string";
@@ -1167,14 +1256,14 @@ std::string Launcher::help() const throw() {
   result += "\n";
   result += "\n                              test|1|timeout|5000                  (step 1: whole time requirement is 5 seconds)";
   result += "\n                              test|1|sendxml2e|CCR-I.xml           (step 2: imagine this xml uses the Session-Id 'SGx')";
-  result += "\n                              test|1|waitfe|272|0|2001|SGx         (step 3: waits the CCA for the CCR-I with Result-Code = DIAMETER_SUCCESS)";
+  result += "\n                              test|1|waitfe|272|0|||SGx|2001       (step 3: waits the CCA for the CCR-I with Result-Code = DIAMETER_SUCCESS)";
   result += "\n                              test|1|sendxml2e|AAR-flows.xml       (step 4: imagine this xml uses the Session-Id 'SRx')";
-  result += "\n                              test|1|waitfe|265|0|2001|SRx         (step 5: waits the AAA for the AAR-flows with Result-Code = DIAMETER_SUCCESS)";
-  result += "\n                              test|1|waitfe|258|1||SGx             (step 6: waits the RAR (install policies) from the PCRF server)";
+  result += "\n                              test|1|waitfe|265|0|||SRx|2001       (step 5: waits the AAA for the AAR-flows with Result-Code = DIAMETER_SUCCESS)";
+  result += "\n                              test|1|waitfe|258|1|||SGx            (step 6: waits the RAR (install policies) from the PCRF server)";
   result += "\n                              test|1|sendxml2e|RAA-install.xml|6   (step 7: sends the response for the RAR)";
   result += "\n                              test|1|sendxml2e|CCR-T.xml           (step 8: termination of the Gx session, imagine this xml puts hop-by-hop 'H1')";
-  result += "\n                              test|1|waitfe|272|0|2001|SGx|H1      (step 9: waits the CCA for the CCR-T with Result-Code = DIAMETER_SUCCESS and hop-by-hop 'H1')";
-  result += "\n                              test|1|waitfe|258|1||SGx             (step 10: waits the RAR (remove policies) from the PCRF server)";
+  result += "\n                              test|1|waitfe|272|0|H1||SGx|2001     (step 9: waits the CCA for the CCR-T with Result-Code = DIAMETER_SUCCESS and hop-by-hop 'H1')";
+  result += "\n                              test|1|waitfe|258|1|||SGx            (step 10: waits the RAR (remove policies) from the PCRF server)";
   result += "\n                              test|1|sendxml2e|RAA-remove.xml|10   (step 11: sends the response for the RAR)";
   result += "\n";
   result += "\n                              Notes: We added an additional condition in step 9: the hop-by-hop. When we program the corresponding";
@@ -1196,9 +1285,9 @@ std::string Launcher::help() const throw() {
   result += "\n";
   result += "\n                                     Other simplifications: the steps 3, 5 and 9 can be replaced by";
   result += "\n";
-  result += "\n                                        test|1|waitfe||0|||#2";
-  result += "\n                                        test|1|waitfe||0|||#4";
-  result += "\n                                        test|1|waitfe||0|||#8";
+  result += "\n                                        test|1|waitfe||0|#2";
+  result += "\n                                        test|1|waitfe||0|#4";
+  result += "\n                                        test|1|waitfe||0|#8";
   result += "\n";
   result += "\n                                        which means that hop-by-hop must be retrieved from steps 2, 4 and 8 respectively,";
   result += "\n                                        and the expected message shall be an answer. Normally you will add other conditions,";
@@ -1304,18 +1393,19 @@ std::string Launcher::help() const throw() {
 void Launcher::eventOperation(const std::string &operation, std::string &response_content) throw(anna::RuntimeException) {
   LOGMETHOD(anna::TraceMethod tm("Launcher", "eventOperation", ANNA_FILE_LOCATION));
   if (operation == "") return; // ignore
-
-  CommandLine& cl(anna::CommandLine::instantiate());
-  TestManager &testManager = TestManager::instantiate();
   LOGDEBUG(anna::Logger::debug(operation, ANNA_FILE_LOCATION));
 
   // Default response:
   response_content = "Operation processed with exception (see traces): ";
   response_content += operation;
-
-
   std::string opt_response_content = ""; // aditional response content
   anna::DataBlock db_aux(true);
+  anna::diameter::codec::Message codecMsg; // auxiliary codec message
+
+  // Singletons:
+  CommandLine& cl(anna::CommandLine::instantiate());
+  TestManager &testManager = TestManager::instantiate();
+
 
   ///////////////////////////////////////////////////////////////////
   // Simple operations without arguments:
@@ -1350,7 +1440,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
   // Get the operation type and parameters:
   Tokenizer::const_iterator tok_iter = params.begin();
   std::string opType = Tokenizer::data(tok_iter);
-  std::string param1, param2, param3, param4, param5, param6, param7, param8, param9, param10;
+  std::string param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11;
   if(numParams >= 1) { tok_iter++; param1 = Tokenizer::data(tok_iter); }
   if(numParams >= 2) { tok_iter++; param2 = Tokenizer::data(tok_iter); }
   if(numParams >= 3) { tok_iter++; param3 = Tokenizer::data(tok_iter); }
@@ -1362,6 +1452,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
   if(numParams >= 8) { tok_iter++; param8 = Tokenizer::data(tok_iter); }
   if(numParams >= 9) { tok_iter++; param9 = Tokenizer::data(tok_iter); }
   if(numParams >= 10) { tok_iter++; param10 = Tokenizer::data(tok_iter); }
+  if(numParams >= 11) { tok_iter++; param11 = Tokenizer::data(tok_iter); }
   // Remove '<null>' artificial token to ease further checkings:
   if (param1 == "<null>") param1 = "";
   if (param2 == "<null>") param2 = "";
@@ -1373,6 +1464,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
   if (param8 == "<null>") param8 = "";
   if (param9 == "<null>") param9 = "";
   if (param10 == "<null>") param10 = "";
+  if (param11 == "<null>") param11 = "";
 
   // No operation has more than 2 arguments except 'test' ...
   if(opType != "test" && numParams > 2)
@@ -1383,10 +1475,11 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
   bool wrongBody = false;
 
   if((opType == "node") && (numParams > 1)) wrongBody = true;
+  if((opType == "node_auto") && (numParams > 0)) wrongBody = true;
 
   if(((opType == "code") || (opType == "decode")) && (numParams != 2)) wrongBody = true;
 
-  if(((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
+  if(((opType == "sendxml2e") || (opType == "sendhex2e")) && (numParams != 1)) wrongBody = true;
 
   if((opType == "burst") && (numParams < 1)) wrongBody = true;
 
@@ -1427,19 +1520,31 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
   // Realm switch:
   if(opType == "node") {
     if (param1 != "") {
-      if (setWorkingNode(param1)) response_content = anna::functions::asString("Current node is now '%s'", param1.c_str());
+      if (setWorkingNode(param1)) response_content = anna::functions::asString("Forced node is now '%s'", param1.c_str());
     }
     else {
-      response_content = getWorkingNode()->asXMLString();
+      if (a_workingNode) {
+        response_content = "Working node is forced to be: \n\n";
+        response_content += a_workingNode->asXMLString();
+      }
+      else {
+        response_content = "Working node is automatic";
+      }
     }
     return;
   }
+  if(opType == "node_auto") {
+    a_workingNode = NULL;
+    response_content = "Working node has been set to automatic";
+    return;
+  }
 
-  // Diameter endpoints:
-  MyDiameterEntity *entity = getWorkingNode()->getEntity();
-  MyDiameterEngine *commEngine = getWorkingNode()->getMyDiameterEngine();
-  MyLocalServer *localServer = getWorkingNode()->getDiameterServer();
-  anna::diameter::codec::Message codecMsg(getCodecEngine());
+  // Operated realm from possible forced-working node:
+  a_operatedRealm = a_workingNode ? a_workingNode /* priority */: NULL /* auto */;
+  // Use later:
+  //    If any message is managed: updateOperatedRealmNodeWithMessage(codecMessage)
+  //    To operate, use the exception-protected methods which never will return NULL:
+  //         getOperatedRealm(), getOperatedEntity(), getOperatedServer(), getOperatedEngine()
 
 
   if(opType == "code") {
@@ -1463,7 +1568,6 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
     outfile.write(xmlString.c_str(), xmlString.size());
     outfile.close();
   } else if((opType == "hide") || (opType == "show") || (opType == "hidden") || (opType == "shown")) {
-    if(!entity) throw anna::RuntimeException("No entity configured to send messages", ANNA_FILE_LOCATION);
 
     if(param1 != "") {
       if(param2 != "") {
@@ -1471,65 +1575,68 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
         key += "|";
         key += param2;
 
-        if(opType == "hide") commEngine->findClientSession(key)->hide();
+        if(opType == "hide") getOperatedEngine()->findClientSession(key)->hide();
 
-        if(opType == "show") commEngine->findClientSession(key)->show();
+        if(opType == "show") getOperatedEngine()->findClientSession(key)->show();
 
-        if(opType == "hidden") opt_response_content = commEngine->findClientSession(key)->hidden() ? "true" : "false";
+        if(opType == "hidden") opt_response_content = getOperatedEngine()->findClientSession(key)->hidden() ? "true" : "false";
 
-        if(opType == "shown") opt_response_content = commEngine->findClientSession(key)->shown() ? "true" : "false";
+        if(opType == "shown") opt_response_content = getOperatedEngine()->findClientSession(key)->shown() ? "true" : "false";
       } else {
         std::string address;
         int port;
         anna::functions::getAddressAndPortFromSocketLiteral(param1, address, port);
 
-        if(opType == "hide") commEngine->findServer(address, port)->hide();
+        if(opType == "hide") getOperatedEngine()->findServer(address, port)->hide();
 
-        if(opType == "show") commEngine->findServer(address, port)->show();
+        if(opType == "show") getOperatedEngine()->findServer(address, port)->show();
 
-        if(opType == "hidden") opt_response_content = commEngine->findServer(address, port)->hidden() ? "true" : "false";
+        if(opType == "hidden") opt_response_content = getOperatedEngine()->findServer(address, port)->hidden() ? "true" : "false";
 
-        if(opType == "shown") opt_response_content = commEngine->findServer(address, port)->shown() ? "true" : "false";
+        if(opType == "shown") opt_response_content = getOperatedEngine()->findServer(address, port)->shown() ? "true" : "false";
       }
     } else {
-      if(opType == "hide") entity->hide();
+      if(opType == "hide") getOperatedEntity()->hide();
 
-      if(opType == "show") entity->show();
+      if(opType == "show") getOperatedEntity()->show();
 
-      if(opType == "hidden") opt_response_content = entity->hidden() ? "true" : "false";
+      if(opType == "hidden") opt_response_content = getOperatedEntity()->hidden() ? "true" : "false";
 
-      if(opType == "shown") opt_response_content = entity->shown() ? "true" : "false";
+      if(opType == "shown") opt_response_content = getOperatedEntity()->shown() ? "true" : "false";
     }
-  } else if((opType == "sendxml") || (opType == "sendxml2e") || (opType == "sendhex") || (opType == "sendhex2e")) {
-    if(!entity) throw anna::RuntimeException("No entity configured to send the message", ANNA_FILE_LOCATION);
-    anna::diameter::comm::Message *msg = getWorkingNode()->createCommMessage();
+  } else if((opType == "sendxml2e") || (opType == "sendhex2e")) {
+    anna::diameter::comm::Message *msg;
 
-    if((opType == "sendxml") || (opType == "sendxml2e")) {
+    if(opType == "sendxml2e") {
       codecMsg.loadXML(param1);
+      updateOperatedRealmNodeWithMessage(codecMsg);
+      msg = getOperatedRealm()->createCommMessage();
       msg->clearBody();
       try { codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); }  // at least we need to see validation errors although it will continue sending (see validation mode configured in launcher)
-
       msg->setBody(codecMsg.code());
     } else {
       // Get DataBlock from file with hex content:
       if(!getDataBlockFromHexFile(param1, db_aux))
         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
-
+      msg = getOperatedRealm()->createCommMessage();
       msg->setBody(db_aux);
+      try { if(getOperatedRealm()->logEnabled()) codecMsg.decode(db_aux); } catch(anna::RuntimeException &ex) { ex.trace(); }
     }
 
-    bool success = entity->send(msg, cl.exists("balance"));
-    getWorkingNode()->releaseCommMessage(msg);
+    bool success = getOperatedEntity()->send(msg, cl.exists("balance"));
+    getOperatedRealm()->releaseCommMessage(msg);
 
     // Detailed log:
-    if(getWorkingNode()->logEnabled()) {
-      anna::diameter::comm::Server *usedServer = entity->getLastUsedResource();
+    if(getOperatedRealm()->logEnabled()) {
+      anna::diameter::comm::Server *usedServer = getOperatedEntity()->getLastUsedResource();
       anna::diameter::comm::ClientSession *usedClientSession = usedServer ? usedServer->getLastUsedResource() : NULL;
       std::string detail = usedClientSession ? usedClientSession->asString() : "<null client session>"; // shouldn't happen
-      getWorkingNode()->writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
+      getOperatedRealm()->writeLogFile(codecMsg, (success ? "sent2e" : "send2eError"), detail);
     }
   } else if((opType == "burst")) {
-    if(!entity) throw anna::RuntimeException("No entity configured to use burst feature", ANNA_FILE_LOCATION);
+
+    if (!uniqueRealm())
+      throw anna::RuntimeException("Burst category operations are only allowed in single realm node configuration. This is only to simplify user experience.", ANNA_FILE_LOCATION);
 
     // burst|clear                     clears all loaded burst messages.
     // burst|load|<source_file>        loads the next diameter message into launcher burst.
@@ -1546,17 +1653,16 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
 
     if(param1 == "clear") {
       opt_response_content = "removed ";
-      opt_response_content += anna::functions::asString(getWorkingNode()->clearBurst());
+      opt_response_content += anna::functions::asString(getOperatedRealm()->clearBurst());
       opt_response_content += " elements";
     } else if(param1 == "load") {
       if(param2 == "") throw anna::RuntimeException("Missing xml path file for burst load operation", ANNA_FILE_LOCATION);
 
       codecMsg.loadXML(param2);
-
       if(codecMsg.isAnswer()) throw anna::RuntimeException("Cannot load diameter answers for burst feature", ANNA_FILE_LOCATION);
       try { codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); }  // at least we need to see validation errors although it will continue loading (see validation mode configured in launcher)
 
-      int position = getWorkingNode()->loadBurstMessage(codecMsg.code());
+      int position = getOperatedRealm()->loadBurstMessage(codecMsg.code());
       opt_response_content = "loaded '";
       opt_response_content += param2;
       opt_response_content += "' file into burst list position ";
@@ -1565,7 +1671,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
       if(param2 == "") throw anna::RuntimeException("Missing initial load for burst start operation", ANNA_FILE_LOCATION);
 
       int initialLoad = atoi(param2.c_str());
-      int processed = getWorkingNode()->startBurst(initialLoad);
+      int processed = getOperatedRealm()->startBurst(initialLoad);
 
       if(processed > 0) {
         opt_response_content = "initial load completed for ";
@@ -1574,7 +1680,7 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
     } else if(param1 == "push") {
       if(param2 == "") throw anna::RuntimeException("Missing load amount for burst push operation", ANNA_FILE_LOCATION);
 
-      int pushed = getWorkingNode()->pushBurst(atoi(param2.c_str()));
+      int pushed = getOperatedRealm()->pushBurst(atoi(param2.c_str()));
 
       if(pushed > 0) {
         opt_response_content = "pushed ";
@@ -1584,14 +1690,14 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
       if(param2 == "") throw anna::RuntimeException("Missing amount for burst pop operation", ANNA_FILE_LOCATION);
 
       int releaseLoad = atoi(param2.c_str());
-      int popped = getWorkingNode()->popBurst(releaseLoad);
+      int popped = getOperatedRealm()->popBurst(releaseLoad);
 
       if(popped > 0) {
         opt_response_content = "burst popped for ";
         opt_response_content += anna::functions::entriesAsString(popped, "message");
       }
     } else if(param1 == "stop") {
-      int left = getWorkingNode()->stopBurst();
+      int left = getOperatedRealm()->stopBurst();
 
       if(left != -1) {
         opt_response_content += anna::functions::entriesAsString(left, "message");
@@ -1601,12 +1707,12 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
       if(param2 == "") param2 = "yes";
 
       bool repeat = (param2 == "yes");
-      getWorkingNode()->repeatBurst(repeat);
+      getOperatedRealm()->repeatBurst(repeat);
       opt_response_content += (repeat ? "repeat enabled" : "repeat disabled");
     } else if(param1 == "send") {
       if(param2 == "") throw anna::RuntimeException("Missing amount for burst send operation", ANNA_FILE_LOCATION);
 
-      int sent = getWorkingNode()->sendBurst(atoi(param2.c_str()));
+      int sent = getOperatedRealm()->sendBurst(atoi(param2.c_str()));
 
       if(sent > 0) {
         opt_response_content = "sent ";
@@ -1615,11 +1721,11 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
     } else if(param1 == "goto") {
       if(param2 == "") throw anna::RuntimeException("Missing order position for burst goto operation", ANNA_FILE_LOCATION);
 
-      opt_response_content = getWorkingNode()->gotoBurst(atoi(param2.c_str()));
+      opt_response_content = getOperatedRealm()->gotoBurst(atoi(param2.c_str()));
     } else if(param1 == "look") {
       int order = ((param2 != "") ? atoi(param2.c_str()) : -1);
       opt_response_content = "\n\n";
-      opt_response_content += getWorkingNode()->lookBurst(order);
+      opt_response_content += getOperatedRealm()->lookBurst(order);
     } else {
       throw anna::RuntimeException("Wrong body content format on HTTP Request for 'burst' operation (unexpected action parameter). See help", ANNA_FILE_LOCATION);
     }
@@ -1778,13 +1884,13 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
       if(id < 0)
         throw anna::RuntimeException("Invalid test case identifier: must be a non-negative number", ANNA_FILE_LOCATION);
 
-      // PARAM: 1     2            3      4          5           6          7         8       9           10
+      // PARAM: 1     2            3      4          5           6             7           8          9       10         11
       // test|<id>|<command>
       //             timeout|    <msecs>
       //             sendxml2e|  <file>[|<step number>]
       //             sendxml2c|  <file>[|<step number>]
       //             delay|      [msecs]
-      //             wait<fe/fc>|[code]|[bitR]|[ResultCode]|[sessionId]|[hopByHop]|[msisdn]|[imsi]|[serviceContextId]
+      //             wait<fe/fc>|[code]|[bitR]|[hopByHop]|[applicationId]|[sessionId]|[resultCode]|[msisdn]|[imsi]|[serviceContextId]
       //      wait<fe/fc>-answer|<step number>
       //      wait<fe/fc>-regexp|<regexp>
       if(param2 == "") throw anna::RuntimeException("Missing command for test id operation", ANNA_FILE_LOCATION);
@@ -1809,16 +1915,13 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
         else {
           if (param4 == "") LOGWARNING(anna::Logger::warning("Step number has not been provided. Take into account that this answer message will be sent 'as is' and sequence information could be wrong at the remote peer", ANNA_FILE_LOCATION));
         }
+        updateOperatedRealmNodeWithMessage(codecMsg);
         int stepNumber = ((param4 != "") ? atoi(param4.c_str()):-1);
-        std::string originRealm = codecMsg.getAvp(anna::diameter::helpers::base::AVPID__Origin_Realm)->getDiameterIdentity()->getValue();
-        RealmNode *realm = getRealmNode(originRealm);
-        if (!realm)
-          throw anna::RuntimeException("Cannot identify the realm node for the manager message. Check the Origin-Realm avp value (use the realm node name)", ANNA_FILE_LOCATION);
 
         if (param2 == "sendxml2e")
-          testManager.getTestCase(id)->addSendxml2e(codecMsg.code(), realm, stepNumber); // creates / reuses
+          testManager.getTestCase(id)->addSendxml2e(codecMsg.code(), getOperatedRealm(), stepNumber); // creates / reuses
         else
-          testManager.getTestCase(id)->addSendxml2c(codecMsg.code(), realm, stepNumber); // creates / reuses
+          testManager.getTestCase(id)->addSendxml2c(codecMsg.code(), getOperatedRealm(), stepNumber); // creates / reuses
       }
       else if (param2 == "delay") {
         if (numParams > 3)
@@ -1828,11 +1931,11 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
         testManager.getTestCase(id)->addDelay(delay); // creates / reuses
       }
       else if ((param2 == "waitfe")||(param2 == "waitfc")) {
-        if (numParams > 10)
+        if (numParams > 11)
           throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
-        if (param3 != "" || param4 != "" || param5 != "" || param6 != "" || param7 != "" || param8 != "" || param9 != "" || param10 != "") {
+        if (param3 != "" || param4 != "" || param5 != "" || param6 != "" || param7 != "" || param8 != "" || param9 != "" || param10 != "" || param11 != "") {
           bool fromEntity = (param2.substr(4,2) == "fe");
-          testManager.getTestCase(id)->addWait(fromEntity, param3, param4, param5, param6, param7, param8, param9, param10);
+          testManager.getTestCase(id)->addWait(fromEntity, param3, param4, param5, param6, param7, param8, param9, param10, param11);
         }
         else {
           throw anna::RuntimeException(anna::functions::asString("Missing condition for '%s' command in test id operation", param2.c_str()), ANNA_FILE_LOCATION);
@@ -1861,11 +1964,12 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
     }
 
   } else if((opType == "sendxml2c") || (opType == "sendhex2c")) {
-    if(!localServer) throw anna::RuntimeException("No local server configured to send the message", ANNA_FILE_LOCATION);
-    anna::diameter::comm::Message *msg = getWorkingNode()->createCommMessage();
+    anna::diameter::comm::Message *msg;
 
     if(opType == "sendxml2c") {
       codecMsg.loadXML(param1);
+      updateOperatedRealmNodeWithMessage(codecMsg);
+      msg = getOperatedRealm()->createCommMessage();
       msg->clearBody();
       try { codecMsg.valid(); } catch(anna::RuntimeException &ex) { ex.trace(); }  // at least we need to see validation errors although it will continue sending (see validation mode configured in launcher)
 
@@ -1874,18 +1978,18 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
       // Get DataBlock from file with hex content:
       if(!getDataBlockFromHexFile(param1, db_aux))
         throw anna::RuntimeException("Error reading hex file provided", ANNA_FILE_LOCATION);
-
+      msg = getOperatedRealm()->createCommMessage();
       msg->setBody(db_aux);
     }
 
-    bool success = localServer->send(msg);
-    getWorkingNode()->releaseCommMessage(msg);
+    bool success = getOperatedServer()->send(msg);
+    getOperatedRealm()->releaseCommMessage(msg);
 
     // Detailed log:
-    if(getWorkingNode()->logEnabled()) {
-      anna::diameter::comm::ServerSession *usedServerSession = localServer->getLastUsedResource();
+    if(getOperatedRealm()->logEnabled()) {
+      anna::diameter::comm::ServerSession *usedServerSession = getOperatedServer()->getLastUsedResource();
       std::string detail = usedServerSession ? usedServerSession->asString() : "<null server session>"; // shouldn't happen
-      getWorkingNode()->writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
+      getOperatedRealm()->writeLogFile(codecMsg, (success ? "sent2c" : "send2cError"), detail);
     }
   } else if(opType == "loadxml") {
     codecMsg.loadXML(param1);
@@ -1893,69 +1997,58 @@ void Launcher::eventOperation(const std::string &operation, std::string &respons
     return;
   } else if(opType == "diameterServerSessions") {
     int diameterServerSessions = atoi(param1.c_str());
+    getOperatedServer()->setMaxConnections(diameterServerSessions);
 
-    if(localServer)
-      localServer->setMaxConnections(diameterServerSessions);
-    else
-      LOGWARNING(anna::Logger::warning("To update the number of sessions, you must configure the process diameter local server: you could also launch it with no sessions (disabled)", ANNA_FILE_LOCATION));
-
-  } else if((opType == "answerxml") || (opType == "answerxml2c")) {
-    if(!localServer)
-      throw anna::RuntimeException("Operation not applicable (no own diameter server has been configured)", ANNA_FILE_LOCATION);
-
+  } else if(opType == "answerxml2c") {
     if(param1 == "") { // programmed answers FIFO's to stdout
-      response_content = localServer->getReactingAnswers()->asString("ANSWERS TO CLIENT");
+      response_content = getOperatedServer()->getReactingAnswers()->asString("ANSWERS TO CLIENT");
       return;
     } else if (param1 == "rotate") {
-      localServer->getReactingAnswers()->rotate(true);
+      getOperatedServer()->getReactingAnswers()->rotate(true);
     } else if (param1 == "exhaust") {
-      localServer->getReactingAnswers()->rotate(false);
+      getOperatedServer()->getReactingAnswers()->rotate(false);
     } else if (param1 == "clear") {
-      localServer->getReactingAnswers()->clear();
+      getOperatedServer()->getReactingAnswers()->clear();
     } else if (param1 == "dump") {
-      localServer->getReactingAnswers()->dump();
+      getOperatedServer()->getReactingAnswers()->dump();
     } else {
-      anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1);
-      LOGDEBUG
-      (
-        anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
-      );
+      codecMsg.loadXML(param1);
+      updateOperatedRealmNodeWithMessage(codecMsg);
+      anna::diameter::codec::Message *message = getOperatedRealm()->getCodecEngine()->createMessage(param1); // loads xml again, lesser of two evils
+      LOGDEBUG(anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION));
 
       if(message->isRequest())
         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
 
       int code = message->getId().first;
       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to client' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
-      localServer->getReactingAnswers()->addMessage(code, message);
+      getOperatedServer()->getReactingAnswers()->addMessage(code, message);
     }
   } else if(opType == "answerxml2e") {
-    if(!entity)
-      throw anna::RuntimeException("Operation not applicable (no diameter entity has been configured)", ANNA_FILE_LOCATION);
 
     if(param1 == "") { // programmed answers FIFO's to stdout
-      response_content = entity->getReactingAnswers()->asString("ANSWERS TO ENTITY");
+      response_content = getOperatedEntity()->getReactingAnswers()->asString("ANSWERS TO ENTITY");
       return;
     } else if (param1 == "rotate") {
-      entity->getReactingAnswers()->rotate(true);
+      getOperatedEntity()->getReactingAnswers()->rotate(true);
     } else if (param1 == "exhaust") {
-      entity->getReactingAnswers()->rotate(false);
+      getOperatedEntity()->getReactingAnswers()->rotate(false);
     } else if (param1 == "clear") {
-      entity->getReactingAnswers()->clear();
+      getOperatedEntity()->getReactingAnswers()->clear();
     } else if (param1 == "dump") {
-      entity->getReactingAnswers()->dump();
+      getOperatedEntity()->getReactingAnswers()->dump();
     } else {
-      anna::diameter::codec::Message *message = getCodecEngine()->createMessage(param1);
-      LOGDEBUG
-      (
-        anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION);
-      );
+      codecMsg.loadXML(param1);
+      updateOperatedRealmNodeWithMessage(codecMsg);
+      anna::diameter::codec::Message *message = getOperatedRealm()->getCodecEngine()->createMessage(param1); // loads xml again, lesser of two evils
+      LOGDEBUG(anna::Logger::debug(message->asXMLString(), ANNA_FILE_LOCATION));
 
       if(message->isRequest())
         throw anna::RuntimeException("Cannot program diameter requests. Answer type must be provided", ANNA_FILE_LOCATION);
 
       int code = message->getId().first;
       LOGDEBUG(anna::Logger::debug("Adding a new programed 'answer to entity' to the FIFO queue corresponding to its message code ...", ANNA_FILE_LOCATION));
-      entity->getReactingAnswers()->addMessage(code, message);
+      getOperatedEntity()->getReactingAnswers()->addMessage(code, message);
     }
   } else {
     throw anna::RuntimeException("Wrong body content format on HTTP Request. Use 'help' management command to see more information.", ANNA_FILE_LOCATION);
@@ -1977,7 +2070,6 @@ throw() {
   result->createAttribute("StartTime", a_start_time.asString());
   result->createAttribute("SecondsLifeTime", anna::time::functions::lapsedMilliseconds() / 1000);
   // Diameter:
-  getCodecEngine()->asXML(result);
   for (realm_nodes_it it = a_nodes.begin(); it != a_nodes.end(); it++) {
     it->second->asXML(result);
   }