Interoperability without the network : JNI, .NET & DLLs

By Daniel Rubio
[Posted by J.Vaughan]
A non-networked application may seem unthinkable in this day in age, but its often designed in this manner to satisfy everything from infrastructure limitations to thwart security breaches, in the context of .NET and Java interoperability, there are a series of considerations to take into account for achieving such cross-platform communication, some of which we will explore in this last entry on interoperability without web services.

The first and obvious characteristic in this type of scenario is that communication is devoid of any common protocol between platforms such as HTTP for web apps or IIOP for CORBA which implies communication is established directly tapping Java or .NET classes that are managed by either a JVM(”Java Virtual Machine”) or CLR(”Common Language Runtime”), respectively.

The biggest hurdle in each of these cases, is that both a JVM and CLR interpret instructions in different form, in Javas case as byte-code(.class files) and in .NETs case as MSIL code(.dll files). Here once again, before proceeding I should mention there are numerous commercial offerings and other open source projects like Caffeine which offer distinct approaches to solving this particular problem, so as in the previous interoperability entries, this is just but one possibility that doesnt require third party tools, albeit one which might be considered a “long-route” by many.

Our interoperability scenario will involve invoking compiled .NET logic from a Java environment. In Javas case, the language along with its development kit is equipped with the necessary tools to execute non-Java code via JNI(Java Native Interface), however, in the particular of .NET DLLs there is a certain twist you should be aware of, from a Java standpoint compiled .NET code in either of its implementing languages C, VB.NET C++.NET is not considered native but rather managed code.

The advent of .NET has eliminated many of the issues related to native code such as memory management but this same insulation has in itself created an additional barrier to invoke this type of code from lower level interfaces available in other programming languages, and for which JNI was designed, so in other words, Java JNI cannot just call any function in any .dll, as many JNI tutorials lead to believe.

The solution to communicate with .NET DLLs from Java JNI then is to establish communication via a native DLL wrapper also known as non-managed code. So lets start with our .NET code, which is illustrated in Listing 1.1

Listing 1.1

Simple enough, now lets illustrate the non-managed C++ wrapper for this .NET class

Listing 1.2

The wrapper makes use of mscorelib.dll which is central to the .NET runtime, and JavaNetInterop.netmodule which is a compiled structure created from the .NET class similar to an assembly as would be JavaNetInterop.dll the rest is compromised by C++ wrapping.

Armed with the C++ wrapper, we would then need to create a header file C++ speak using Javas javah utility, which would later be used for creating our JNI implementation illustrated in Listing 1.3

Listing 1.3

The top most declarations are used for accessing JNIs header file, the C++ header file and non-managed C++ file, respectively, while the method is used for invoking the wrapping C++ logic. Finally, our last step would be creating a Java calling class that would look something like the following listing :

Listing 1.4

In this last snippet we make use of the native keyword to indicate we are dealing with a non-Java method, the System.loadLibrary declaration to load the JavaNet dll corresponding to the compiled non-managed C++ wrapper and a main method which creates an object instance while invoking the native method interopLogicMethod.

Though the process is somewhat elaborate, it will nevertheless allow you to call .NET logic from a Java environment. With this we come to a conclusion on our four part series dedicated to exploring non web-services technologies for Java and .NET interoperability. The next time you are faced with a project involving interoperability issues, be sure to give these alternatives a closer look, especially if your organization is still tied-up deciding when,where and if web services should be used.

Interoperability without the network : JNI, .NET & DLLs

By Daniel Rubio
[Posted by J.Vaughan]
A non-networked application may seem unthinkable in this day in age, but its often designed in this manner to satisfy everything from infrastructure limitations to thwart security breaches, in the context of .NET and Java interoperability, there are a series of considerations to take into account for achieving such cross-platform communication, some of which we will explore in this last entry on interoperability without web services.

The first and obvious characteristic in this type of scenario is that communication is devoid of any common protocol between platforms such as HTTP for web apps or IIOP for CORBA which implies communication is established directly tapping Java or .NET classes that are managed by either a JVM(”Java Virtual Machine”) or CLR(”Common Language Runtime”), respectively.

The biggest hurdle in each of these cases, is that both a JVM and CLR interpret instructions in different form, in Javas case as byte-code(.class files) and in .NETs case as MSIL code(.dll files). Here once again, before proceeding I should mention there are numerous commercial offerings and other open source projects like Caffeine which offer distinct approaches to solving this particular problem, so as in the previous interoperability entries, this is just but one possibility that doesnt require third party tools, albeit one which might be considered a “long-route” by many.

Our interoperability scenario will involve invoking compiled .NET logic from a Java environment. In Javas case, the language along with its development kit is equipped with the necessary tools to execute non-Java code via JNI(Java Native Interface), however, in the particular of .NET DLLs there is a certain twist you should be aware of, from a Java standpoint compiled .NET code in either of its implementing languages C, VB.NET C++.NET is not considered native but rather managed code.

The advent of .NET has eliminated many of the issues related to native code such as memory management but this same insulation has in itself created an additional barrier to invoke this type of code from lower level interfaces available in other programming languages, and for which JNI was designed, so in other words, Java JNI cannot just call any function in any .dll, as many JNI tutorials lead to believe.

The solution to communicate with .NET DLLs from Java JNI then is to establish communication via a native DLL wrapper also known as non-managed code. So lets start with our .NET code, which is illustrated in Listing 1.1

Listing 1.1

Simple enough, now lets illustrate the non-managed C++ wrapper for this .NET class

Listing 1.2

The wrapper makes use of mscorelib.dll which is central to the .NET runtime, and JavaNetInterop.netmodule which is a compiled structure created from the .NET class similar to an assembly as would be JavaNetInterop.dll the rest is compromised by C++ wrapping.

Armed with the C++ wrapper, we would then need to create a header file C++ speak using Javas javah utility, which would later be used for creating our JNI implementation illustrated in Listing 1.3

Listing 1.3

The top most declarations are used for accessing JNIs header file, the C++ header file and non-managed C++ file, respectively, while the method is used for invoking the wrapping C++ logic. Finally, our last step would be creating a Java calling class that would look something like the following listing :

Listing 1.4

In this last snippet we make use of the native keyword to indicate we are dealing with a non-Java method, the System.loadLibrary declaration to load the JavaNet dll corresponding to the compiled non-managed C++ wrapper and a main method which creates an object instance while invoking the native method interopLogicMethod.

Though the process is somewhat elaborate, it will nevertheless allow you to call .NET logic from a Java environment. With this we come to a conclusion on our four part series dedicated to exploring non web-services technologies for Java and .NET interoperability. The next time you are faced with a project involving interoperability issues, be sure to give these alternatives a closer look, especially if your organization is still tied-up deciding when,where and if web services should be used.

State of WS Interop Going Forward

Long-time Microsoft XML hand Jonathan Marsh is now part of WSO2, an engineering group devoted to building Web services middleware. An associated WSO2.org developer portal is now featuring a discussion with Jonathan about February’s W3C workshop on the “Web of Services for Enterprise Computing.” 

Marsh discusses the need for increasing the interoperability Basis for WS-*. He has noted a need to continue to focus on practical demonstrations of Web Services interoperability. He sees more emphasis of late on application demos, less emphasis on displays of Web Services interoperability.

He writes: “A return to the roots of Web Services, maximizing interoperability through open communication between developers, and between their implementations, would solidify industry confidence in Web Services as a solid basis for interoperability.”

He sees a much richer ecosystem of  specification, but the interoperability of stacks is still ‘a little bit iffy.” He’d like to see a working group to deal with interoperability problems going forward. Read a paper Jonathan Marsh wrote on interoperability for the W3C site.

A Look at the SpaceFacade Pattern

A unique form of distributed computing may be called ‘space-based.’ Program objects and data can share a space in this scenario, without a lot of stipulations placed upon them. JavaSpaces has emerged as a standard means to do such programming, and GigaSpaces has in turn emerged as a major commercializer of JavaSpaces technology.

Today, Owen Taylor of GigaSpaces writes about spaces. There is an interoperability play here. He notse one can embed a space in the same process as a .NET application and expose it to C++ and Java as a fully-functioning virtual resource. In fact, GigaSpaces has recently gone beyond the Java world to support space-based programming in .NET. [See Java player GigaSpaces sets course for .NET coverage, TSS.NET, February 27, 2007] – J.Vaughan

By Owen Taylor
A space-based architecture is fundamentally different from traditional architectures (meaning stuff we already understand).

This is primarily due to the combined behaviors of state management and event distribution that a Space provides. This creates a natural hub and spoke architecture where the space acts as the communication hub for the rest of the application.

Additionally, when using a space as a reliable in-memory store for your active Objects, there is a shift in dependency away from the database for frequent reads and even updates to the system state within a business transaction. (changes are usually propagated to the DB in an asynchronous fashion to facilitate long-term persistence and extensive queries)

Due to the space taking on the responsibility for state management and event distribution, an entirely new architecture can be achieved.

In essence, what a Space offers is a single logical resource that allows the sharing of Objects between different machines, processes, and threads within a process - aw heck, let’s just say among “services”. Which indeed leads us to adopt a service-oriented, space-based architecture.

Spaces are designed to support a very potent pattern called Master/Worker which is used to address problems where there is a huge amount of work to be done and most of it can be done independent of the rest.

In the Master/Worker pattern, the Master writes Entries into the space and the workers take them out. I liken this to serving a bowl of popcorn. The master fills the bowl and the workers take the popcorn out.

The more workers, the faster the popcorn is processed because there is no dependency between kernels.

Many work-flow applications can be modeled this way as can matching engines and execution engines as long as the Entries written are designed to house (or be deployed in the same process as) a self-contained set of instructions and or data.

What this allows within the familiar tier-based architecture is a kind of magical pressure valve that can take advantage of any number of boxes that might be available on the network and thus process these kernels of work at tremendous speeds. A facade can be created that receives a request for processing, cracks it into parallel tasks and submits them to a space.

While the original caller writes, blocks and waits for a result (thinking it is talking to a single resource) in the back-end many simultaneous operations are occurring that result in faster results and a more adaptive and scalable solution.

This use of this SpaceFacade pattern has resulted in great successes for the customers of GigaSpaces. These successes are measurable in various ways.

Performance:
Major financial firms worldwide are leveraging the space to facilitate dramatically reduced transaction latency and greater overall throughput. By collocating services with the data they require in the same process as a space, latency of operations within real applications are reduced from tens of milliseconds to hundreds of microseconds. This is realized through removing the dependency on separate messaging, data-caching/store, and business processing layers, and the resulting reduction in network hops and distributed transactions.

Reliability:
As described here.Virgin Mobile experiences not only greater throughput as a result of this architecture, but also increased reliability as the in-memory ‘virtual’ resources act as a buffer to the traditional backend systems. Last fall (2006), while their DB was down for 10+ hours, the Space and its associated services continued to accept and process orders so not a single one was lost.

Interoperability:
Being able to embed a space in the same process as a .NET application and expose it to C++ and Java as a fully-functioning virtual resource offers up an extremely simple solution to the problem of sharing information among disparate services and applications. I can think of three major financial services companies that today, leverage our support for inter-language communication where the SpaceFacade also hides the language used when implementing cooperative services.

Layers of indirection are remarkably useful!

———————

Owen Taylor is Senior Director for Worldwide Technical Communications, GigaSpaces Technologies.

————————-

Author’s Note: If you would like to try out the Space as implemented by GigaSpaces, I have posted a simple .NET/C# example on my blog here.

Further information on our .NET support can be found on the GigaSpaces .NET wiki.

For an introduction to the core space API and further discussion of the space value proposition you can look at my post on four verbs.

The tried and true wrapper: CORBA

By Daniel Rubio
[Posted by Jack Vaughan]

If interoperability was a necessity to enterprise software in the pre-web services era, CORBA (Common Object Request Broker Architecture) was in all likelihood at the top of the list for many. Similar to messaging, which we discussed in the last entry, CORBA has had wide acceptance due to the different language/platform support it has garnered throughout the years, including : Java/Java EE, C++, C, COBOL, Python, among others.

And even though the Microsoft product line has lagged in CORBA support, partly due to a competing and in-house technology named DCOM which came out around the same time as CORBA, a series of alternatives have come to fruition in the .NET camp, making CORBA a viable alternative for Java/.NET interoperability projects.

CORBA’s core concepts can be summarized in : ORB’s, IDL and IIOP. An ORB(Object Request Broker) serves as a dispatcher for CORBA-type requests, just like a web server does for web pages. IDL (Interface Description Language) on the other hand is a language-neutral syntax used for describing CORBA services, just like WSDL is a platform neutral syntax for describing web services. (For those wanting a little more background on the similarities between IDL/WSDL, an excellent post by Steve Vinoski can be found at: Weighing in on IDL vs. WSDL). Finally, IIOP (Internet Inter-ORB Protocol) is the wire protocol used by CORBA, that while a little bit arcane to mention as core, is an important aspect when attempting to use CORBA from .NET.

Before we continue our discussion, you should be aware that CORBA is a very powerful and hence complex technology, so it can take some time to become acquainted with its inner workings, nevertheless I will do my best to get you up and running with a very basic CORBA Java/.NET app.

Since Java’s JDK already comes bundled with an ORB and IDL compiler, we will use both tools to create a server side CORBA application, in the case of .NET, we will make use of an open source library named IIOP.NET to make requests from a .NET application to a Java-CORBA application.

Lets start by defining a CORBA application contract in IDL, the following listing illustrates such a contract:

Listing 1.1 CORBA-IDL Contract

module interopApp
{
  interface Demo
  {
    string interopMethod();
  };
};
Don’t dwell to much on the details, just realize the contract indicates the application will have a method by the name interopMethod that will return a string value. With this contract in-hand, you then need to feed it through an IDL compiler to generate language specific supporting CORBA classes. In Java’s case, execute the following from the command line : idlj -fall interopApp.idl, where idlj is the compiler located under the JDK’s bin directory and interopApp.idl is the file containing the contract.

Upon execution, an additional folder with 6 supporting Java/CORBA classes will be created, compile them as you would any other Java classes. These last classes are in effect CORBA’s wrapper for your Java application code, which would look something like the following class:

Listing 1.2 Java-CORBA implementation class

import interopApp.*;

public class DemoImpl extends DemoPOA
{   public DemoImpl() {
    System.out.println( “Called DemoImpl constructor”);
  }

  public String interopMethod() {
      // Hardcode String, other logic or DB access could be used here
      String response = “At ” + new java.util.Date() + ” : Interop String obtained from Java-CORBA server”;
      return response;
  }
}
The import statement in this case is used to tap the generated CORBA classes, while the class in itself inherits its behavior from one of the supporting classes named DemoPOA. The important thing to take note of here is the exposed CORBA method interopMethod is overridden to contain any type of Java logic required by the application.

Next, you need to create a server class to associate this particular application code with a CORBA-ORB, the following listing shows such a server:

Listing 1.3 Java-CORBA Server class

import org.omg.CORBA.ORB;
import org.omg.CosNaming.*;
import org.omg.PortableServer.*;

import interopApp.*;

public class Server
{
  public static void main(String args[]) {
    try {
      String obj_name = “javanetapp”;

      //Create and initialize the ORB
      ORB orb = ORB.init(args, null);
      //Reference to rootpoa & activate the POAManager
      POA rootpoa
      = POAHelper.narrow(orb.resolve_initial_references(”RootPOA”));
      rootpoa.the_POAManager().activate();

      //Create servant and register it with the ORB
      DemoImpl demo_serv = new DemoImpl();

      //Object reference from the servant
      org.omg.CORBA.Object ref = rootpoa.servant_to_reference( demo_serv );
      Demo demoServ = DemoHelper.narrow( ref );

      //Root naming context
      org.omg.CORBA.Object naming
      = orb.resolve_initial_references(”NameService”);
      NamingContextExt nctx = NamingContextExtHelper.narrow(naming);

      //Bind Object reference in naming
      NameComponent path[] = nctx.to_name( obj_name );
      nctx.rebind(path, demoServ)

      //Run a separate thread
      orb.run();
    }
    catch (Exception x) { }
   }
}
The most relevant aspects of this last server class are that it uses the DemoImpl class, and its association to the name javanetapp — using the obj_name string — as a network identifier. Finally, you need to activate the Java ORB so the application can be accessed across the network. From the command line type tnameserv -ORBInitialPort 2007 — this will activate CORBA’s naming service on port 2007 — and then type java Server -ORBInitialPort 2007 — where Server is the previous class — to expose the CORBA access point.

At this juncture, you have a full-fledged CORBA enabled application accessible through the name javanetapp, so lets take a final crack at tapping this application from a .NET environment. Accessing CORBA services is a little simpler than exposing them, while you will need to pass the IDL through the compiler provided in IIOP.NET to generate supporting classes, you won’t need to wire-up up an ORB. The following listing illustrates what a CORBA .NET client using IIOP.NET would look like:

Listing 1.4 .NET-CORBA Client class using IIOP.NET

using System;
using System.Runtime.Remoting.Channels;
using Ch.Elca.Iiop;
using Ch.Elca.Iiop.Services;
using omg.org.CosNaming;
// Route to IDL supporting files
using interop.Demo;
namespace Interop.Demo {

   public class Client {

         public static void Main(string[] args) {
            try {
                string nameServiceHost = “localhost”;
                int nameServicePort = 2007;

                //Register channel
                IiopClientChannel channel = new IiopClientChannel();
                ChannelServices.RegisterChannel(channel);

                //Access CORBA/COS naming service
                RmiIiopInit init = new RmiIiopInit(nameServiceHost, nameServicePort);
                NamingContext nameService = init.GetNameService();
                NameComponent[] name = new NameComponent[] { new NameComponent(”javanetapp”, “”) };
                //Get the reference to Demo
                Demo interopClient = (Demo)nameService.resolve(name);
                //Call interopMethod()
                String result = interopClient.interopMethod();
                Console.WriteLine(”Result: ” + result);
            } catch (Exception e) {
                Console.WriteLine(”Exception: ” + e);
            }
        }
    }
}
Relevant sections in this last listing include : the use of Ch.Elca.Iiop classes — which is the actual namespace used by the IIOP.NET library — and the use of localhost,servicePort and javanetapp for locating the CORBA service, as activated on the Java server side ORB.

With this we conclude our short overview of CORBA as a Java/.NET interoperability option. In the final entry of this series on using non-webservices for interoperability, we will take a look at a non-network approach to interoperability: JNI and DLL’s.

Daniel Rubio is a software consultant with over 10 years of experience in enterprise software development, having recently founded Mashup Soft, a startup specializing in the use Web services for Mashups. He is a technology enthusiast in all areas related to software platforms and maintains a blog on these topics at webforefront.com.

‘Stinking Badges’ and Identity Software Services Interop

If there is one place where interop has to happen more quickly, it is in web-based identity services. As long as the web is a place where, to borrow a phrase from The Treasure of the Sierra Madre, there are no ’stinking badges,’  its commercial potential will have severe limits. But bridges between vendors’ formats are afoot.

Lost amid the clamor at last month’s RSA Conference: The Novell-sponsored Bandit open source project and the Eclipse Foundation’s Higgins Project jointly announced a reference application that shows open source identity services that make Microsoft’s Windows CardSpace identity management system interoperable with Liberty Alliance-based identity federation via Novell Access Manager.

Higgins is a project that is developing an platform-independent, identity protocol-independent software framework. The reference application capitalizes on several parts of Higgins including an identity abstraction layer called the Identity Attribute Service (IdAS), and is available at: http://www.bandit-project.org/index.php/Reference_Application

The Messaging Way : MSMQ & JMS

By Daniel Rubio
[Posted by Jack Vaughan]
Messaging is a popular technique for applications requiring asynchronous communication, and its same architecture which introduces an additional broker between client and server, also lends itself to support interoperability between Java and .NET applications, via a messaging provider.

A messaging provider adheres pretty strictly to the definition of middleware, its role is to sit between client and server hosts to support additional software services, one of which can be bridging platform disparities. Messaging providers come in many flavors and are produced by many vendors, strictly speaking in Java and .NET terms, in the Java camp there are a series of products designed around JMS(Java Messaging Service), while in the Microsoft-centric product line there is MSMQ.

Choosing between a messaging provider can be an elaborate process, but generally speaking all of them support a plethora of client/server platforms to bridge communication disparities, ranging from Java, .NET to others like C++ and C. In all cases, any messaging platform requires a concerted effort to install, configure and use, so with that said, we will concentrate our efforts on a what I have personally experienced to be the easiest to set up : MSMQ. This is not to say MSMQ is superior to other messaging platforms, but simply more ubiquitous than others, given its already included in Windows 2000, Windows XP, Windows Server 2003 and Windows Vista, contrary to many other products which require more elaborate steps to install.

In any of the aforementioned operating systems, first ensure you have MSMQ enabled going to the control panel and selecting the Add or Remove Programs icon, followed by Add/Remove Components, in the emerging window you will see a list, make sure Message Queuing is selected. You now have MSMQ ready for action on your system.

The next step is to create a queue, in messaging speak this is where the communications token — message — you wish to transfer between a Java and or .NET application is stored. The actual message can be varied in nature, it can have distinct formats — text, XML, binary — or have different behaviors — guaranteed delivery, transactional properties — in this particular case, I wont delve in the finer details of incorporating any elaborate messaging behaviors, but rather focus on storing a vanilla type message in MSMQ through either Java or .NET.

In .NET the process is very straightforward, since two of the many .NET classes are designed for just this purpose, one is named System.Messaging.MessageQueue and the other System.Messaging.Message. The following snippet shows the sequence:

Listing 1.1 Creating MSMQ queue and sending message from .NET

// Check if queue exists, if not create
if(MessageQueue.Exists(@”.\Private$\InteropQueue”))
      // Creates an instance MessageQueue, which points to existing InteropQueue
      mq = new System.Messaging.MessageQueue(@”.\Private$\InteropQueue”);
else
      // Creates a new queue called InteropQueue
      mq = MessageQueue.Create(@”.\Private$\InteropQueue”);

// Create a message to send, with text and label
System.Messaging.Message msg = new System.Messaging.Message();
// InteropMsg variable contains payload, assign to body
msg.Body = InteropMsg.Text;
msg.Label = “InteropMsgJavaNET”;
// Send it to the queue.
mq.Send(msg);
[End Listing 1.1]

In Java, the process is a little more elaborate since it requires connecting to MSMQ via a supporting library/mechanism, among them : COM, C++ or C. This means that your Java class would need to communicate through either one of these technologies to get through to MSMQ, since MSMQ does not support native Java or JMS calls.

So what you are left with when trying to create MSMQ queues from Java is using a separate API. Currently, there are a series of commercial offerings — sometimes referred to as bridges — to ease Java communication to COM(and hence MSMQ), but since this would take us down the avenue of proprietary API’s and product selection I won’t discuss it here.

An alternate route for those looking for non-commercial — read free — communication from Java to MSMQ would be using JNI(Java Native Interface), which is Java’s way of tapping C++ or C libraries, but we will leave JNI’s interoperability details for a later entry. An excellent write-up on this process by Dino Chiesa is found on his All About Interop blog.

Returning to the task at hand, once a message sits in an MSMQ queue, it can easily be consumed by either a Java or .NET client using a similar sequence to the one used for creating it. In .NET you once again use MessageQueue class for this purpose:

Listing 1.2 Consuming message from MSMQ queue in .NET

      // Creates a new queue called InteropQueue
      mq = MessageQueue.Create(@”.\Private$\InteropQueue”);
try
{
      // Call receive on queue
      msg = mq.Receive(new TimeSpan(0, 0, 5)); // 5 is wait time in seconds
      // Assign to variable
      msgInterop = msg.Body.ToString();
}
catch
{
      msgInterop = “No Message”;
}
[End Listing 1.2]In Java, the message consuming code would again entail using a communications bridge to COM or some other form JNI library to tap MSMQ’s C or C++ interfaces.

There you have it, a quick run-through on using messaging to achieve interoperability between Java and .NET applications. In the next entry, we will take a look at another non-web service alternative to achieving application interoperability: CORBA.

Daniel Rubio is a software consultant with over 10 years of experience in enterprise software development, having recently founded Mashup Soft, a startup specializing in the use Web services for Mashups. He is a technology enthusiast in all areas related to software platforms and maintains a blog on these topics at webforefront.com.

 

Related MQ/MSMQ messaging link
Dino Chiesa blog

 

The Messaging Way : MSMQ & JMS

By Daniel Rubio
[Posted by Jack Vaughan]
Messaging is a popular technique for applications requiring asynchronous communication, and its same architecture which introduces an additional broker between client and server, also lends itself to support interoperability between Java and .NET applications, via a messaging provider.

A messaging provider adheres pretty strictly to the definition of middleware, its role is to sit between client and server hosts to support additional software services, one of which can be bridging platform disparities. Messaging providers come in many flavors and are produced by many vendors, strictly speaking in Java and .NET terms, in the Java camp there are a series of products designed around JMS(Java Messaging Service), while in the Microsoft-centric product line there is MSMQ.

Choosing between a messaging provider can be an elaborate process, but generally speaking all of them support a plethora of client/server platforms to bridge communication disparities, ranging from Java, .NET to others like C++ and C. In all cases, any messaging platform requires a concerted effort to install, configure and use, so with that said, we will concentrate our efforts on a what I have personally experienced to be the easiest to set up : MSMQ. This is not to say MSMQ is superior to other messaging platforms, but simply more ubiquitous than others, given its already included in Windows 2000, Windows XP, Windows Server 2003 and Windows Vista, contrary to many other products which require more elaborate steps to install.

In any of the aforementioned operating systems, first ensure you have MSMQ enabled going to the control panel and selecting the Add or Remove Programs icon, followed by Add/Remove Components, in the emerging window you will see a list, make sure Message Queuing is selected. You now have MSMQ ready for action on your system.

The next step is to create a queue, in messaging speak this is where the communications token — message — you wish to transfer between a Java and or .NET application is stored. The actual message can be varied in nature, it can have distinct formats — text, XML, binary — or have different behaviors — guaranteed delivery, transactional properties — in this particular case, I wont delve in the finer details of incorporating any elaborate messaging behaviors, but rather focus on storing a vanilla type message in MSMQ through either Java or .NET.

In .NET the process is very straightforward, since two of the many .NET classes are designed for just this purpose, one is named System.Messaging.MessageQueue and the other System.Messaging.Message. The following snippet shows the sequence:

Listing 1.1 Creating MSMQ queue and sending message from .NET

// Check if queue exists, if not create
if(MessageQueue.Exists(@”.\Private$\InteropQueue”))
      // Creates an instance MessageQueue, which points to existing InteropQueue
      mq = new System.Messaging.MessageQueue(@”.\Private$\InteropQueue”);
else
      // Creates a new queue called InteropQueue
      mq = MessageQueue.Create(@”.\Private$\InteropQueue”);

// Create a message to send, with text and label
System.Messaging.Message msg = new System.Messaging.Message();
// InteropMsg variable contains payload, assign to body
msg.Body = InteropMsg.Text;
msg.Label = “InteropMsgJavaNET”;
// Send it to the queue.
mq.Send(msg);
[End Listing 1.1]

In Java, the process is a little more elaborate since it requires connecting to MSMQ via a supporting library/mechanism, among them : COM, C++ or C. This means that your Java class would need to communicate through either one of these technologies to get through to MSMQ, since MSMQ does not support native Java or JMS calls.

So what you are left with when trying to create MSMQ queues from Java is using a separate API. Currently, there are a series of commercial offerings — sometimes referred to as bridges — to ease Java communication to COM(and hence MSMQ), but since this would take us down the avenue of proprietary API’s and product selection I won’t discuss it here.

An alternate route for those looking for non-commercial — read free — communication from Java to MSMQ would be using JNI(Java Native Interface), which is Java’s way of tapping C++ or C libraries, but we will leave JNI’s interoperability details for a later entry. An excellent write-up on this process by Dino Chiesa is found on his All About Interop blog.

Returning to the task at hand, once a message sits in an MSMQ queue, it can easily be consumed by either a Java or .NET client using a similar sequence to the one used for creating it. In .NET you once again use MessageQueue class for this purpose:

Listing 1.2 Consuming message from MSMQ queue in .NET

      // Creates a new queue called InteropQueue
      mq = MessageQueue.Create(@”.\Private$\InteropQueue”);
try
{
      // Call receive on queue
      msg = mq.Receive(new TimeSpan(0, 0, 5)); // 5 is wait time in seconds
      // Assign to variable
      msgInterop = msg.Body.ToString();
}
catch
{
      msgInterop = “No Message”;
}
[End Listing 1.2]In Java, the message consuming code would again entail using a communications bridge to COM or some other form JNI library to tap MSMQ’s C or C++ interfaces.

There you have it, a quick run-through on using messaging to achieve interoperability between Java and .NET applications. In the next entry, we will take a look at another non-web service alternative to achieving application interoperability: CORBA.

Daniel Rubio is a software consultant with over 10 years of experience in enterprise software development, having recently founded Mashup Soft, a startup specializing in the use Web services for Mashups. He is a technology enthusiast in all areas related to software platforms and maintains a blog on these topics at webforefront.com.

 

Related MQ/MSMQ messaging link
Dino Chiesa blog

 

AES Interop Between PHP and Java

Asked and answered on the Fun Things in Life blog:

How do you use AES in PHP to encrypt a message and decrypt it in Java?

And:

How do you do it the other way around?

In the end, as ever, the message is: “Hello World”.

AES Interop between PHP and Java - Fun Things in Life

Think small: Microformats

Funny but a lot of things that seemed obvious when XML first sprang on the scene are still just percolating. Take microformats, please.

Microformats are promoted as a practical way to solve a common interoperability problem: “How to add structured data to existing documents (typically HTML) without changing the underlying schema or breaking existing implementations.” This per Doug Mahugh, Open XML Technical Evangelist with Microsoft, writing on his blog..

The basic concept is that a microformat is a set of “class” attributes that can be added to spans in an HTML page to tag content with semantic meaning. There have been microformats defined for reviews (hReview), calendar items (hCalendar), business cards (hCard), and other applications, and microformat-tagged content is starting to appear on many web pages.

Greasemonkey and Mozilla lab folks have worked with microformats. In his post, Mahugh looks at microformats and OpenXML

Links on microformats:
More on the Microformat.org wiki
Microformats and Open XML