Skip to content
Snippets Groups Projects
Commit 8f0b7f60 authored by Tom Wiesing's avatar Tom Wiesing
Browse files

It works!

parent 1f22734d
No related branches found
No related tags found
No related merge requests found
Showing
with 14948 additions and 183 deletions
No preview for this file type
using System; using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using System.IO;
using log4net; using log4net;
using log4net.Config; using log4net.Config;
using SallySchemas;
using Apache.NMS; using Apache.NMS;
using Apache.NMS.Util;
using Apache.NMS.ActiveMQ.Commands;
using SallyConnect; using SallyConnect;
namespace ConnectToSally namespace ConnectToSally
{ {
/// <summary>
/// Represent a sally client
/// </summary>
class DotNetSallyClient class DotNetSallyClient
{ {
protected static TimeSpan receiveTimeout = TimeSpan.FromSeconds(10); protected static TimeSpan receiveTimeout = TimeSpan.FromSeconds(10);
/// <summary>
/// A logger so that we can write things to the console.
/// </summary>
private static readonly ILog logger = LogManager.GetLogger(typeof(DotNetSallyClient)); private static readonly ILog logger = LogManager.GetLogger(typeof(DotNetSallyClient));
/// <summary>
/// Username for the connection.
/// </summary>
public string user { get; private set; } public string user { get; private set; }
/// <summary>
/// Password for the connection.
/// </summary>
public string password { get; private set; } public string password { get; private set; }
/// <summary>
/// Address for the connection.
/// </summary>
public string address { get; private set; }
/// <summary>
/// Connection session variable
/// </summary>
public ISession session { get; private set; } public ISession session { get; private set; }
public IConnection connection { get; private set; }
/// <summary>
/// Connection variable
/// </summary>
public IConnection connection { get; private set; }
protected void startConnection() /// <summary>
/// Starts the connection to Sally.
/// </summary>
protected bool startConnection()
{ {
Uri connecturi = new Uri("activemq:tcp://neptune.eecs.jacobs-university.de:61616");//neptune.eecs.jacobs-university.de:61616 // set up a URI and get ready for connecting
Uri connecturi = new Uri(this.address);
IConnectionFactory connectFactory = new NMSConnectionFactory(connecturi); IConnectionFactory connectFactory = new NMSConnectionFactory(connecturi);
try try
{ {
//create a connection
this.connection = connectFactory.CreateConnection(this.user, this.password); this.connection = connectFactory.CreateConnection(this.user, this.password);
//create a session
this.session = this.connection.CreateSession(); this.session = this.connection.CreateSession();
//and get everything running
this.connection.Start(); this.connection.Start();
// we have started the connection.
return this.connection.IsStarted;
} }
// catch exceptions so that we do not crash
catch (TypeLoadException e) catch (TypeLoadException e)
{ {
Console.WriteLine(e.ToString()); Console.WriteLine(e.ToString());
...@@ -53,37 +81,63 @@ namespace ConnectToSally ...@@ -53,37 +81,63 @@ namespace ConnectToSally
Console.WriteLine(e.ToString()); Console.WriteLine(e.ToString());
} }
//nope something went wrong.
return false;
} }
/// <summary> /// <summary>
/// Starts a DotNetSallyClient object with a session and connection with Sally. /// Starts a DotNetSallyClient object with a session and connection with Sally.
/// </summary> /// </summary>
/// <param name="user"></param> /// <param name="address">Adress to connect to. </param>
/// <param name="password"></param> /// <param name="user">Username to connect with. </param>
public DotNetSallyClient(string user="webclient", string password="webclient") /// <param name="password">Password to connect with. </param>
public DotNetSallyClient(string address= "activemq:tcp://localhost:61616", string user="karaf", string password="karaf")
{ {
// store connection params
this.address = address;
this.user = user; this.user = user;
this.password = password; this.password = password;
BasicConfigurator.Configure(); //for the logger
startConnection(); //set up the logger.
if (!this.connection.IsStarted) BasicConfigurator.Configure();
if (!startConnection())
{ {
Console.WriteLine("Could not start connection.."); // if we could not start the connection, we should complain.
logger.Fatal("Could not start connection!"); Console.WriteLine("DotNetSallyClient <" + address + ">: Could not start connection");
logger.Fatal("DotNetSallyClient <" + address + ">: Could not start connection");
return;
} }
Console.WriteLine("Started connection and registered the document. Queue A set.");
// we're done for now.
Console.WriteLine("DotNetSallyClient <"+ address + ">: Started connection");
} }
/// <summary>
/// returns the session of this SallyClient.
/// </summary>
/// <returns></returns>
public ISession getSallySession(){ public ISession getSallySession(){
// if there is no connection, we can not return it.
if (!this.connection.IsStarted) { if (!this.connection.IsStarted) {
throw new Exception("No connection started yet. Start a connection and try again."); throw new Exception("DotNetSallyClient <" + address + ">: No connection started yet. Start a connection and try again.");
} }
//and return it.
return this.session; return this.session;
} }
/// <summary>
/// Registers a document with this Sally Client.
/// </summary>
/// <param name="doc"></param>
public void registerDocument(SallyDocument doc)
{
//just call the document method to do this.
doc.registerWith(this);
}
} }
} }
File suppressed by a .gitattributes entry or the file's encoding is unsupported.
File added
File suppressed by a .gitattributes entry or the file's encoding is unsupported.
This diff is collapsed.
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants> <DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
...@@ -42,24 +43,14 @@ ...@@ -42,24 +43,14 @@
<Reference Include="Apache.NMS.Stomp"> <Reference Include="Apache.NMS.Stomp">
<HintPath>..\packages\Apache.NMS.Stomp.1.5.4\lib\net40\Apache.NMS.Stomp.dll</HintPath> <HintPath>..\packages\Apache.NMS.Stomp.1.5.4\lib\net40\Apache.NMS.Stomp.dll</HintPath>
</Reference> </Reference>
<Reference Include="commcore">
<HintPath>E:\rsvworks\sallymay14\tocommit\dist\commcore.dll</HintPath>
</Reference>
<Reference Include="commlmh">
<HintPath>E:\rsvworks\sallymay14\tocommit\dist\commlmh.dll</HintPath>
</Reference>
<Reference Include="commmhworker">
<HintPath>E:\rsvworks\sallymay14\tocommit\dist\commmhworker.dll</HintPath>
</Reference>
<Reference Include="commplanetaryclient">
<HintPath>E:\rsvworks\sallymay14\tocommit\dist\commplanetaryclient.dll</HintPath>
</Reference>
<Reference Include="commtheo">
<HintPath>E:\rsvworks\sallymay14\tocommit\dist\commtheo.dll</HintPath>
</Reference>
<Reference Include="log4net"> <Reference Include="log4net">
<HintPath>..\packages\log4net.2.0.3\lib\net40-full\log4net.dll</HintPath> <HintPath>..\packages\log4net.2.0.3\lib\net40-full\log4net.dll</HintPath>
</Reference> </Reference>
<Reference Include="Microsoft.QualityTools.Testing.Fakes, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
<Reference Include="SallySchemas, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\sally4-core\comm-core\dist\SallySchemas.DLL</HintPath>
</Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" /> <Reference Include="System.Xml.Linq" />
...@@ -76,6 +67,7 @@ ...@@ -76,6 +67,7 @@
<Compile Include="Utilities.cs" /> <Compile Include="Utilities.cs" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Fakes Include="Fakes\commcore.fakes" />
<None Include="packages.config" /> <None Include="packages.config" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
......
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ReferencePath>
</ReferencePath>
</PropertyGroup>
</Project>
\ No newline at end of file
...@@ -8,6 +8,7 @@ using SallySchemas; ...@@ -8,6 +8,7 @@ using SallySchemas;
using Apache.NMS; using Apache.NMS;
using Apache.NMS.Util; using Apache.NMS.Util;
using System.Xml; using System.Xml;
using System.Xml.Serialization;
using System.IO; using System.IO;
using ConnectToSally; using ConnectToSally;
using log4net; using log4net;
...@@ -16,170 +17,242 @@ namespace SallyConnect ...@@ -16,170 +17,242 @@ namespace SallyConnect
{ {
class SallyDocument class SallyDocument
{ {
/// <summary>
/// The name of the sally queue we want to subscribe to
/// </summary>
public string sallyQueue { get; private set; } public string sallyQueue { get; private set; }
/// <summary>
/// A boolean stating if we are subscribed to the given SallyQueue
/// </summary>
public bool subscribedToQueue { get; private set; } public bool subscribedToQueue { get; private set; }
/// <summary>
/// The system environment ID used by Sally.
/// </summary>
public string environmentID { get; private set; } public string environmentID { get; private set; }
/// <summary>
/// Interfaces implemented by this client.
/// </summary>
public string[] interfaces { get; private set; } public string[] interfaces { get; private set; }
/// <summary>
/// Messaging session
/// </summary>
private ISession session { get; set; } private ISession session { get; set; }
/// <summary>
/// Messaging producer
/// </summary>
private IMessageProducer sender { get; set; } private IMessageProducer sender { get; set; }
/// <summary>
/// A logger for this document.
/// </summary>
private static readonly ILog logger = LogManager.GetLogger(typeof(SallyDocument)); private static readonly ILog logger = LogManager.GetLogger(typeof(SallyDocument));
/// <summary>
/// Represents a Sally Client.
/// </summary>
/// <param name="environmentID">Environment ID to use when registering with Sally. </param>
/// <param name="interfaces">A list of interfaces this client should implement. </param>
public SallyDocument(string environmentID, string[] interfaces) public SallyDocument(string environmentID, string[] interfaces)
{ {
// set up basic variables.
this.environmentID = environmentID; this.environmentID = environmentID;
this.interfaces = interfaces; this.interfaces = interfaces;
this.subscribedToQueue = false; this.subscribedToQueue = false;
this.sallyQueue = "dotnet_alex_" + Guid.NewGuid().ToString();
}
protected SallySchemas.registerdocument getCoreRegisterDocument() // generate a new unique client name.
{ this.sallyQueue = "dotnet_client_" + Guid.NewGuid().ToString();
SallySchemas.registerdocument reg = new registerdocument();
reg.environmentid = this.environmentID;
reg.documentqueue = this.sallyQueue;
reg.interfaces = this.interfaces;
return reg;
} }
/// <summary> #region Initial register With Sally
/// Register a new listener and handler to the given session so as to start communicating details about this document.
/// </summary>
/// <param name="docName"></param>
/// <param name="interfaces"></param>
protected void registerDocQueueListener()
{
IDestination docQueue = SessionUtil.GetDestination(this.session, "queue://" + this.sallyQueue);
IMessageConsumer regConsumer = this.session.CreateConsumer(docQueue);
regConsumer.Listener += new MessageListener(OnDocQueueMessage); //listen for heartbeats
}
/// <summary> /// <summary>
/// Register a new document with Sally so as to start communicating details about that document. /// Registers this document with a SallyClient
/// </summary> /// </summary>
/// <param name="docName"></param> /// <param name="dns">SallyClient to register with</param>
/// <param name="interfaces"></param> public void registerWith(DotNetSallyClient dns)
public void registerDocument(DotNetSallyClient dns)
{ {
//load the session.
this.session = dns.getSallySession(); this.session = dns.getSallySession();
// build the message to send
string xmlMessage = Apache.NMS.Util.XmlUtil.Serialize(getCoreRegisterDocument()); string xmlMessage = Apache.NMS.Util.XmlUtil.Serialize(getCoreRegisterDocument());
ITextMessage regRequest = session.CreateTextMessage(xmlMessage); ITextMessage regRequest = session.CreateTextMessage(xmlMessage);
Console.WriteLine(xmlMessage); //Now sending it to sally_register with a temp queue for the replyTo
//be ready to respond on the document queue
registerDocQueueListener(); registerDocQueueListener();
// send the sally registration
sendReceive(SessionUtil.GetDestination(this.session, "queue://sally_register"), regRequest); sendReceive(SessionUtil.GetDestination(this.session, "queue://sally_register"), regRequest);
} }
/// <summary> /// <summary>
/// Send a message to the given destination. A temporary queue is set as a replyTo for this transaction. /// Registers to the response Queue so that we can send messages.
/// </summary> /// </summary>
/// <param name="destination"></param> /// <param name="responseQueue">Name of the response queue</param>
/// <param name="message"></param>
protected void sendReceive(IDestination destination, IMessage message)
{
ITemporaryQueue tempQueue = this.session.CreateTemporaryQueue();
IMessageConsumer tempQueueConsumer = this.session.CreateConsumer(tempQueue);
tempQueueConsumer.Listener += new MessageListener(OnResponseQueueMessage);
message.NMSReplyTo = tempQueue;
message.NMSCorrelationID = Guid.NewGuid().ToString();
IMessageProducer producer = this.session.CreateProducer(destination);
producer.Send(message);
}
protected void registerToResponseQueue(String responseQueue) protected void registerToResponseQueue(String responseQueue)
{ {
logger.Info("Reached to the registration of response queue.."); // create the destination
string prefixedQueue = responseQueue; IDestination responseQDestination = SessionUtil.GetDestination(this.session, responseQueue);
IDestination responseQDestination = SessionUtil.GetDestination(this.session, prefixedQueue);
// and store the sender
this.sender = session.CreateProducer(responseQDestination); this.sender = session.CreateProducer(responseQDestination);
// we are now ready to send messages.
this.subscribedToQueue = true; this.subscribedToQueue = true;
//semaphore.Set();
Console.WriteLine("Ready to send messages to Sally on the response queue");
}
public bool isRegistered() { Console.WriteLine("SallyDocument <" + environmentID + ">: Registered to document queue");
return this.subscribedToQueue;
} }
/// <summary> /// <summary>
/// Send a message to Sally on the specific queue provided by Sally after the registration of the document. If wait is enabled it waits for 1 sec (being used during unit testing) /// Builds a request to register this document with Sally
/// </summary> /// </summary>
/// <param name="xmlMessage"></param> /// <returns>the request</returns>
/// <param name="wait"></param> protected SallySchemas.RegisterClientRequest getCoreRegisterDocument()
public void sendToSally(String xmlMessage, bool wait = false)
{ {
//semaphore.WaitOne((int)TimeSpan.FromSeconds(1).TotalMilliseconds, true);
if (!this.subscribedToQueue)
{
if (wait) {
System.Threading.Thread.Sleep(1000);
sendToSally(xmlMessage, false);
}
logger.Fatal("Register to the queue from sally's response first..."); //create the request
Console.WriteLine("Register to the queue from sally's response first..."); SallySchemas.RegisterClientRequest reg = new RegisterClientRequest();
// and set up the parameters.
reg.EnvironmentID = this.environmentID;
reg.ListenQueue = this.sallyQueue;
reg.Schemas = this.interfaces;
// and return it.
return reg;
} }
else
#endregion
#region Heartbeat Responding
/// <summary>
/// Registers a listener for the document queue
/// </summary>
/// <param name="docName"></param>
/// <param name="interfaces"></param>
protected void registerDocQueueListener()
{ {
this.sender.Send(xmlMessage); //the queue
Console.WriteLine("Sent a message on response queue.."); IDestination docQueue = SessionUtil.GetDestination(this.session, "queue://" + this.sallyQueue);
}
// build and register a listener
IMessageConsumer regConsumer = this.session.CreateConsumer(docQueue);
regConsumer.Listener += new MessageListener(OnDocQueueMessage);
Console.WriteLine("SallyDocument <" + environmentID + ">: Registered document queue listener");
} }
/// <summary> /// <summary>
/// This one gets heartbeats /// Handler for messages received on the document queue
/// </summary> /// </summary>
/// <param name="receivedMsg"></param> /// <param name="receivedMsg">message received</param>
protected void OnDocQueueMessage(IMessage receivedMsg) protected void OnDocQueueMessage(IMessage receivedMsg)
{ {
IBytesMessage msg = (IBytesMessage)receivedMsg;
//semaphore.Set();
logger.Info("Received a heartbeat on " + this.environmentID + "'s queue..");
Console.WriteLine("Received a heartbeat on " + this.environmentID + "'s queue..");
if (receivedMsg == null) if (receivedMsg == null)
{ {
// nothing to do ...
logger.Warn("No ITextMessage..."); logger.Warn("No ITextMessage...");
} }
else else
{ {
System.Byte[] content = (receivedMsg as IBytesMessage).Content; string res_xml = Utilities.getMessageContent(receivedMsg, "HeartbeatRequest");
String xmlResponse = System.Text.Encoding.Default.GetString(content);
logger.Info("Received => " + receivedMsg);
logger.Info("ByteArray => " + content);
Console.WriteLine("ByteArray => " + content);
logger.Info("Init parsing the response: " + xmlResponse);
using (XmlReader reader = XmlReader.Create(new StringReader(xmlResponse))) // check if we have indeed received a message.
if (res_xml == null)
{ {
string res; logger.Warn("Unknown message type..");
Dictionary<String, String> sallyResponse = Utilities.xmlResponseReader(reader, "heartbeatrequest"); Console.WriteLine("Unknown message type..");
if (sallyResponse.ContainsKey("heartbeatrequest")) return;
} else
{ {
//respond to the hb request Console.WriteLine("SallyDocument <" + environmentID + ">: Received HeartbeatRequest");
Console.WriteLine("Heartbeatrequest is getting heartbeat response.."); HeartbeatRequest res = Utilities.deserialize<HeartbeatRequest>(res_xml);
res = sallyResponse["heartbeatrequest"];
heartBeartResponder(receivedMsg); heartBeartResponder(receivedMsg);
} }
else
{
//default handler
logger.Warn("Unknown message type..");
Console.WriteLine("Unknown message type..");
} }
} }
/// <summary>
/// Responds to a heart beat request
/// </summary>
/// <param name="receivedHeartBeat"></param>
protected void heartBeartResponder(IMessage receivedHeartBeat)
{
// create the heartbeatreponse
SallySchemas.HeartbeatResponse hbResponseContent = new HeartbeatResponse();
// and serialise it.
ITextMessage hbResponse = this.session.CreateTextMessage(Utilities.serialize<HeartbeatResponse>(hbResponseContent));
// and respond to it.
replyAndReceive(receivedHeartBeat, hbResponse);
Console.WriteLine("SallyDocument <" + environmentID + ">: Send HeartbeatResponse");
} }
/// <summary>
/// Replies to a message and handles the response.
/// </summary>
/// <param name="destination">Destination to send message to. </param>
protected void replyAndReceive(IMessage inResponseTo, IMessage message)
{
// create a temporary queue and consumer
ITemporaryQueue tempQueue = this.session.CreateTemporaryQueue();
IMessageConsumer tempQueueConsumer = this.session.CreateConsumer(tempQueue);
// handle the response with the onResponseQueueMessage
tempQueueConsumer.Listener += new MessageListener(OnResponseQueueMessage);
// set the reply to and ids for the message
message.NMSReplyTo = tempQueue;
message.NMSCorrelationID = inResponseTo.NMSCorrelationID;
// finally make a consumer and send the message.
IMessageProducer producer = this.session.CreateProducer(inResponseTo.NMSReplyTo);
producer.Send(message);
Console.WriteLine("SallyDocument <" + environmentID + ">: Replying with CorrelationID " + inResponseTo.NMSCorrelationID.ToString());
} }
protected void heartBeartResponder(IMessage receivedHeartBeat)
#endregion
#region Message Send & Receive
/// <summary>
/// Sends a message to a destionation and handles the response.
/// </summary>
/// <param name="destination">Destination to send message to. </param>
/// <param name="message">Message to send. </param>
protected void sendReceive(IDestination destination, IMessage message)
{ {
Console.WriteLine("Going to respond to heartbeat request"); // create a temporary queue and consumer
SallySchemas.heartbeatresponse hbResponseContent = new heartbeatresponse(); ITemporaryQueue tempQueue = this.session.CreateTemporaryQueue();
ITextMessage hbResponse = this.session.CreateTextMessage(Apache.NMS.Util.XmlUtil.Serialize(hbResponseContent)); IMessageConsumer tempQueueConsumer = this.session.CreateConsumer(tempQueue);
sendReceive(receivedHeartBeat.NMSReplyTo, hbResponse);
Console.WriteLine("Responded to heartbeat request"); // handle the response with the onResponseQueueMessage
tempQueueConsumer.Listener += new MessageListener(OnResponseQueueMessage);
// set the reply to and ids for the message
message.NMSReplyTo = tempQueue;
message.NMSCorrelationID = Guid.NewGuid().ToString();
// finally make a consumer and send the message.
IMessageProducer producer = this.session.CreateProducer(destination);
producer.Send(message);
Console.WriteLine("SallyDocument <" + environmentID + ">: Sending message to "+destination.ToString());
} }
/// <summary> /// <summary>
...@@ -188,42 +261,66 @@ namespace SallyConnect ...@@ -188,42 +261,66 @@ namespace SallyConnect
/// <param name="receivedMsg"></param> /// <param name="receivedMsg"></param>
protected void OnResponseQueueMessage(IMessage receivedMsg) protected void OnResponseQueueMessage(IMessage receivedMsg)
{ {
IBytesMessage msg = (IBytesMessage)receivedMsg;
//semaphore.Set(); Console.WriteLine("SallyDocument <" + environmentID + ">: Received response Queue message");
logger.Info("Received a response on " + this.environmentID + "'s queue..");
Console.WriteLine("Received a response on " + this.environmentID + "'s queue..");
if (receivedMsg == null) if (receivedMsg == null)
{ {
// if there is no message, we have nothing to do
logger.Warn("No ITextMessage..."); logger.Warn("No ITextMessage...");
} }
else else
{ {
System.Byte[] content = (receivedMsg as IBytesMessage).Content; // read the message content
String xmlResponse = System.Text.Encoding.Default.GetString(content); string res_xml = Utilities.getMessageContent(receivedMsg, "RegisterClientResponse");
logger.Info("Received => " + receivedMsg); // and register to the response queue if possible.
logger.Info("ByteArray => " + content); if(res_xml == null) {
Console.WriteLine("ByteArray => " + content); logger.Warn("SallyDocument <" + environmentID + ">: Unrecognised response Queue message");
logger.Info("Init parsing the response: " + xmlResponse); Console.WriteLine("SallyDocument < " + environmentID + " >: Unrecognised response Queue message");
} else {
RegisterClientResponse res = Utilities.deserialize<RegisterClientResponse>(res_xml);
registerToResponseQueue(res.SendQueue);
}
}
}
using (XmlReader reader = XmlReader.Create(new StringReader(xmlResponse))) #endregion
{
string res; public bool isRegistered() {
Dictionary<String, String> sallyResponse = Utilities.xmlResponseReader(reader, "sallyqueue"); return this.subscribedToQueue;
if (sallyResponse.ContainsKey("sallyqueue"))
{
//register to the queue in response - even if already registered before(?)
res = sallyResponse["sallyqueue"];
registerToResponseQueue(res);
} }
else
/// <summary>
/// Sends a message to sally. The wait parameter is used for debugging.
/// </summary>
/// <param name="xmlMessage"></param>
/// <param name="wait"></param>
public void sendToSally(String xmlMessage, bool wait = false)
{ {
//default handler if (!this.subscribedToQueue)
logger.Warn("Unknown message type.."); {// we are not subscribed to a quenue yet, so we can not send anything.
Console.WriteLine("Unknown message type..");
// in the debug case, we should wait for a second
// and try again.
if (wait) {
System.Threading.Thread.Sleep(1000);
sendToSally(xmlMessage, false);
return;
} }
// otherwise die with a fatal message
logger.Fatal("Register to the queue from sally's response first...");
Console.WriteLine("Register to the queue from sally's response first...");
} }
else
{// we are subscribed => send the message.
this.sender.Send(xmlMessage);
Console.WriteLine("Sent a message on response queue..");
} }
} }
......
...@@ -10,17 +10,26 @@ namespace SallyConnect ...@@ -10,17 +10,26 @@ namespace SallyConnect
class TestUnit class TestUnit
{ {
static void Main(string[] args) { static void Main(string[] args) {
String[] interfaces = new string[] { "theo" };
String docName = "random_edit_1114717882592231.sdaf";
DotNetSallyClient dns = new DotNetSallyClient(); String[] interfaces = new string[] { "theo" }; // we implement the theo interface
String docName = "random_edit_1114717882592231.sdaf"; // something we want to name.
// we first create the sally client.
DotNetSallyClient dns = new DotNetSallyClient("activemq:tcp://localhost:61616");//neptune.eecs.jacobs-university.de:61616
//and then register a document to it.
SallyDocument sD = new SallyDocument(docName, interfaces); SallyDocument sD = new SallyDocument(docName, interfaces);
sD.registerDocument(dns); dns.registerDocument(sD); // register the document.
//now just wait
Console.Read();
/*
System.Threading.Thread.Sleep(1000); System.Threading.Thread.Sleep(1000);
if (sD.isRegistered()){ if (sD.isRegistered()){
sD.sendToSally("some message"); sD.sendToSally("some message");
} }
Console.Read(); Console.Read();
*/
} }
} }
} }
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml; using System.Xml;
using Apache.NMS;
using System.IO;
using System.Xml.Serialization;
namespace SallyConnect namespace SallyConnect
{ {
class Utilities class Utilities
{ {
public static Dictionary<String, String> xmlResponseReader(XmlReader xmlReader, String xmlNode = "heartbeatrequest")
/// <summary>
/// Gets the content of a message from Sally or null.
/// </summary>
/// <param name="receivedMsg">Message that was received from Sally. </param>
/// <param name="messageType">The type of message that is received. </param>
/// <param name="prop">The property of the name to return</param>
/// <returns>the message content or null. </returns>
public static String getMessageContent(IMessage receivedMsg, String messageType)
{ {
Dictionary<String, String> sallyResponse = new Dictionary<string, string>(); // turn the message content into a string
while (xmlReader.Read()) System.Byte[] content = (receivedMsg as IBytesMessage).Content;
String xmlMsg = System.Text.Encoding.Default.GetString(content);
// DEBUG: Log message
Console.WriteLine(xmlMsg);
// and make an xml reader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlMsg)))
{ {
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == xmlNode))
// while reading it.
while (reader.Read())
{
// if we have the correct node type
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == messageType))
{ {
sallyResponse.Add(xmlReader.Name, xmlReader.ReadElementContentAsString()); return xmlMsg;
return sallyResponse; }
} }
} }
sallyResponse.Add("noresponse", "null");
return sallyResponse; // we have nothing to return.
return null;
} }
public static T deserialize<T>(string xml)
{
// create a reader and serialiser
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlReader reader = XmlReader.Create(new StringReader(xml));
// and deserialise
return (T)serializer.Deserialize(reader);
}
public static string serialize<T>(T message)
{
return Apache.NMS.Util.XmlUtil.Serialize(message);
}
} }
} }
File added
File added
This diff is collapsed.
File added
File added
This diff is collapsed.
File added
File added
File added
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment