Can I call Java from Node.js via JNI and how? - java

can I call Java from Node.js via JNI? Are there any examples?

You should try the node-java npm module which is a well-written wrapper over JNI.
node-jave doesn't appear to (yet) have broad adoption, but playing with it, I've been impressed with how straightforward and robust it has been.
It's as simple as:
var list = java.newInstanceSync("java.util.ArrayList");
list.addSync("item1");
list.addSync("item2");
console.log(list.getSync(1)); // prints "item2"
You can do just about anything with your embedded JVM - create objects, call methods, access fields, etc.
There is a slight impedance mismatch between Node and Java, so if you are going to interact with something complicated, I'd recommend writing most of your interactions in Java and exposing a simpler interface across the Node/Java barrier. It just makes for easier debugging that way.
--- Dave
p.s., RealWorldUseCase(tm): I worked at a place that had a pretty complex (and spaghetti-coded) protocol between multiple browser clients and a Java-based service. I wrote a pretty sweet test-harness which used jsdom to host N simulated browsers and used node-java as a wrapper around the Java service code. It was trivial to shim out the transport interfaces, both in JS for the clients, and in Java for the service, so whenever any of these things sends a message, I capture that and stick it in a queue for probabilistic delivery to the intended target (ie, I virtualized the network). In this way, I could run a full-on simulation of multiple clients interacting with and through a Java service, and run the whole thing inside a single process without any wire communication. And then I could do fun stuff like deliberately reorder message deliveries to make sure the code was resilient to timing bugs. And when a bug was discovered, I had the message orderings logged and could reproduce them to repro the bug. Oh, and the whole thing set up and ran a pretty complex scenario with a few thousand lines of logging and finished in under 1 second per run. 2-weeks well spent. Fun stuff.
RealWorld Use Case #2: selenium-inproc - a module that wraps the SeleniumRC JAR file providing a node interface to browser automation testing w/ Selenium without having to run yet another localhost service.

That looks tricky. Node.JS runs on the Google Chrome JavaScript engine V8. What you will have to do is to create a V8 C++ binding (v8 c++ Crash Course shows an example) that starts a JVM and does all the JNI handling.
I think you might be better off letting a JavaServer and Node.js communicate via the network (someone wrote an example for using RabbitMQ for Java/Node.js message based communication). Here, JSON would be a great data exchange format (if you trust your Java server produces proper JSON you can just eval() it in Node).

I think what you are looking for is a native extension to use as a bridge. Although I don't have an example of what you are saying, I do have an example on how to call a C++ extension using Node.JS
https://github.com/jrgleason/NodeJSArduinoLEDController

I am not aware of all the details of Node.js but i am assuming that your mentioning of JNI is actually the Java Native Interface. One can only use JNI from Java, so imho it does not make sense to access Java from JNI if you are not already in java.
It would appear that this is the wrong approach, and you need to search the Node.js doco for their integration chapter...

I wonder if it is possible at all. but even if it is possible I imagine it is hard to implement and I am certain that nobody has done that yet.
how about using a named pipe to communicate between processes(java and node.js) ?

Related

How to write a script that's parseable in both Java and C++

We've got Java and C++ implementations of our product, which is a distributed messaging system.
I'm writing a framework to run a system test across multiple servers. I need our "test coordinator" process to send instructions to each server telling it what to do (e.g. send 100 sample messages, or wait for a message, etc).
I'd really like to implement this by sending a script to each server containing its instructions. This allows me to create dumb test servers, with all the intelligence embedded in the test instructions.
If all my servers were Java I'd write this in Groovy or a similar language. But I'd like our C++ implementation to parse the same script. I'm wondering if I could execute Javascript to call Java/C++ classes to send messages etc.
Is there a neat way of doing this?
If all else fails I'll create an XML format to declaratively contain the test parameters (rather than imperatively containing the test instructions). But this would require the test servers to contain more test-specific intelligence than I'd like.
Any advice gratefully received.
Maybe have a look at LUA. It is well supported in C++ and it seems like there is support for Java as well (see this question)
There are JavaScript parsers for C++ and Java available, so that's definitely something you could use; I don't think that it's a good idea however: the Javascript code can of course interact with your Java code and your C++ code; the problem is, if you want your Javascript code to be ignorant of whether it runs on the C++ or Java basis, it doesn't actually make much sense to call Java/C++ from it, since these calls are again language- (and even engine-)specific.
The simpler solution might be to use a declarative format as you say, but I wouldn't go for XML unless the data needs to be exchanged with a broader audience; instead I'd use e.g. JSON, which is supported very nicely on Java and C++
The best solution (albeit probably also the one involving the highest effort to develop) is probably to develop your own DSL (domain specific language), and parsers for it in both C++ and Java.
This is the kind of inter-operability WSDL was originally designed to facilitate. I'm not sure why you'd want to invent an XML format to do what SOAP already does. I mean, you could, but it'd be a maintenance nightmare for the next guy. Plus, introducing another programming language (which is client side, unless you want to add NodeJS into the mix) to act as a glue layer between the two increases the complexity of the system.
What I would do is:
define a high level language agnostic interface
create implementations for the interface in Java and C++
If you're sending commands to the servers, it may be appropriate to look into using the Command pattern to encapsulate the set of known commands (which I assume is enumerated in your requirements). You can use Batch Commands using Composite.
Then your "Test Coordinator" would build a batch command, send it to the server of choice using the declared service, and your implementations could process those commands in language specific ways. Depending on the types of commands your system has, it may be appropriate to have each implementation delegate to Ant or Make.
You could consider using CORBA too... :)

Make calls to a Java object running in a existing JVM with PHP

I am getting into an existing project which implies lots of remote objects communicating together to compute and transfer data.
My goal is to create a web application allowing enduser to input some data and get the results after treatment through the existing distributed application.
Regarding that, I looked for a way to make calls to existing Java objects with PHP, but in most of cases it was about how to create a JVM and instanciate objects directly in PHP, but not accessing to an existing and running JVM.
So, what could be the better way to do that ? I also heard about creating a servlet, but I have no real knowledge about this for the moment, so I am sending a S.O.S in a bottle to the StackOverflow community, hoping someone (and I am sure there is) would have a good answer to that problem :-)
Thank you for your time !
You need to modify the java application. You have to add some kind of remote interface to that app, which can then be used by PHP. If you are inexperienced in java, you're out of luck.
One of the options described above is the servlet, which basically means exposing your java app through a REST or SOAP interface. That may or may not be the simplest solution, depending on your java app. If it is a webapp, you're in luck. You can try using JAX-WS to do that. The downside is that such communication comes with an overhead. If your java app is a command line program, you could use an embedded servlet container such as Jetty or try using WSpublish (built into java 6).
You can give Hessian a try. It is a binary web service protocol that supports both PHP and java. I have used it extensively on java-only environments, but it may work in php-java scenario as well. http://hessian.caucho.com/
As you can see, there are plenty of options, but all of them require knowledge and experience in JAVA and cannot be described in one sentence or two.
The easiest java WS example I have seen can be found here:
http://java.dzone.com/articles/jax-ws-hello-world?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+javalobby/frontpage+(Javalobby+/+Java+Zone)
maybe you could try the PHP/Java Bridge project : http://php-java-bridge.sourceforge.net/pjb/
There's one door into a running java virtual machine: the java management extensions. The door has to be unlocked from the inside, so the application has to offer some managed beans and the jvm has to be started with some parameters.
But once this is setup up properly, then you have an open port where you can read and set data from/on instances or execute methods.
I can't tell exactly how difficult it is to use this connection to the jvm from "other languages", maybe you just have to be able to emulate javas object serialization with php. But it might be offer a solution for your actual problem.

Any better options than porting from C# to Java?

I have an existing library written in C# which wraps a much lower-level TCP/IP API and exposes messages coming down the wire from a server (proprietary binary protocol) as .NET events. I also provide method calls on an object which handles the complexities of marshalling convenient .NET types (like System.DateTime) down to the binary encodings and fixed-length structures that the API requires (for outgoing messages to the server). There are a fair number of existing applications (both internally and used by third parties) built on top of this .NET library.
Recently, we've been approached by someone who doesn't want to do all the legwork of abstracting the TCP/IP themselves, but their environment is strictly non-Windows (I assume *nix, but I'm not 100% sure), and they've intimated that their ideal would be something callable from Java.
What's the best way to support their requirements, without me having to:
Port the code to Java now (including an unmanaged DLL that we currently P/Invoke into for decompression)
Have to maintain two separate code-bases going forwards (i.e. making the same bug-fixes and feature enhancements twice)
One thing I've considered is to re-write most of the core TCP/IP functionality once into something more cross-platform (C / C++) and then change my .NET library to be a thin layer on top of this (P/Invoke?), and then write a similarly thin Java layer on top of it too (JNI?).
Pros:
I mostly spend my time writing things only once.
Cons:
Most of the code would now be unmanaged - not the end of the world, but not ideal from a productivity point of view (for me).
Longer development time (can't port C# sockets code to C / C++ as quickly as just porting to Java) [How true is this?]
At this point, the underlying API is mostly wrapped and the library is very stable, so there's probably not a lot of new development - it might not be that bad to just port the current code to Java and then have to make occasional bug-fixes or expose new fields twice in the future.
Potential instability for my existing client applications while the version they're running on changes drastically underneath them. (Off the top of my head I can think of 32/64 bit issues, endianness issues, and general bugs that may crop up during the port, etc.)
Another option I've briefly considered is somehow rigging Mono up to Java, so that I can leverage all of the existing C# code I already have. I'm not too clued up though on how smooth the developer experience will be for the Java developers who have to consume it though. I'm pretty sure that most of the code should run without trouble under Mono (bar the decompression P/Invoke which should probably just be ported to C# anyway).
I'd ideally not like to add another layer of TCP/IP, pipes, etc. between my code and the client Java app if I can help it (so WCF to Java-side WS-DeathStar is probably out). I've never done any serious development with Java, but I take some pride in the fact that the library is currently a piece of cake for a third-party developer to integrate into his application (as long as he's running .NET of course :)), and I'd like to be able to keep that same ease-of-use for any Java developers who want the same experience.
So if anyone has opinions on the 3 options I've proposed (port to Java & maintain twice, port to C and write thin language bindings for .NET and Java or, try and integrate Java and Mono), or any other suggestions I'd love to hear them.
Thanks
Edit: After speaking directly with the developer at the client (i.e. removal of broken telephone AKA Sales Department) the requirements have changed enough that this question no longer applies very well to my immediate situation. However, I'll leave the question open in the hopes that we can generate some more good suggestions.
In my particular case, the client actually runs Windows machines in addition to Solaris (who doesn't these days?) and is happy for us to write an application (Windows Service) on top of the library and provide a much more simplified and smaller TCP/IP API for them to code against. We will translate their simple messages into the format that the downstream system understands, and translate incoming responses back for them to consume, so that they can continue to interface with this downstream system via their Java application.
Getting back to the original scenario after thinking about this for a couple of weeks, I do have a few more comments:
A portable C-based library with different language bindings on top would probably be the way to go if you knew up front that you'd need to support multiple languages / platforms.
On *nix, can a single process host both a Java runtime and a Mono runtime simultaneously? I know in earlier versions of .NET you couldn't have two different .NET runtimes in the same process, but I believe they've fixed this with .NET 4? If this is possible, how would one communicate between the two? Ideally you'd want something as simple as a static method call and a delegate to raise responses with.
If there's no easy direct interface support between Java & Mono (methods & delegates, etc.), one might consider using something like ZeroMQ with Protocol Buffers or Apache Thrift as the message format. This would work in-process, inter-process and over the network because of ZeroMQ's support for different transports.
Spend more time getting the requirements nailed down before deciding on an implementation. Until you know what is required, you don't have any criteria for choosing between designs.
If it's a non-windows environment, it doesn't make sense to have .NET anywhere in there, for example.
If you need something that runs on the Java Virtual Machine but looks a lot like C#, you should check out Stab. This will not help you with P/Invoke and the like but you may find it less work to port your C# code to Java and maintain it.
You should look into Mono though. I expect that all your C# code would run unmodified (except the parts that touch the unmanaged DLL).
I have not used it but jni4net is supposed to allow calling .NET code from Java. If your clients want a Java interface, this may be a solution.
I use Mono on Linux and the Mac all the time even when .NET compatibility is not a priority. I like C# and the .NET libraries and prefer the CLR to the JVM. Mono is MIT/X11 licensed which means that you can use it commercially if you like. Unlike some others, I see no reason to avoid technology championed by Microsoft while favouring technology championed by Oracle and IBM.
Using Mono will not help you with the unmanaged bits, although you can still P/Invoke into a native DLL. You will just have to port that DLL yourself or find some equivalent.
You may also want to look into Mono Ahead of Time compilation.
Have you considered mono? It would most likely support your existing code in the non-windows environment. The trick would be calling it from java, but the mono folks might have something to help you out there, too.
This probably isn't the right solution in your case, but for completeness:
There are a few languages that can target both the JVM and .NET, in particular Ruby (JRuby and IronRuby) and Python (Jython and IronPython). Scala might eventually get there too, although right now the .NET version is a long way behind the JVM version.
Anyway, you could potentially rewrite your library in Ruby or Python and target both runtimes.
If what you really, really want is to be able to code in .NET and have it run on the JVM, you could check out Grasshopper (2015-09: link possibly dead). That is what it is designed to do.
I know the Mainsoft guys have been contributors to Mono over the years. If I remember correctly, they wrote the Visual Basic compiler for Mono.
There is also the C# to Java converter from Tangible. I have heard good things but I have never used it myself.
Also, it does not help your situation much but I should point out Mono for Android.
Mono for Android runs the CLR and the Dalvik VM in parallel. In other words, the C# code you wrote for Android can be calling into Java libraries (like the Android UI for example) and executing as a single app. You had asked about the ability to run .NET and Java code in the same process. Clearly, it can be done.
One thing I've considered is to re-write most of the core TCP/IP functionality once into something more cross-platform (C / C++) and then change my .NET library to be a thin layer on top of this (P/Invoke?), and then write a similarly thin Java layer on top of it too (JNI?).
That's a possibility. On the Java side, you should consider using JNA rather than JNI. (If you use JNI, the C / C++ code needs to be written to use JNI-specific signatures.)
Another possibility is to replace the proprietary binary protocol with something that "just works" with multiple programming languages. This is the kind of problem space where CORBA and similar technologies provide a good solution.

Using a Java function/class from Delphi

In delphi, I am trying to call a function from an external Java program. Is there any way to do it ?
The standard process to call native code is via JNI. A search on JNI and Delphi will reveal multiple pages that detail how this is done, like this and this
What is more desirable (setting up some out of process server (like Peter already detailed, so I skipped that) or using JNI to call a library depends on how often (and how realtime) you need this to be, and on allowable installation/configuration complexity
If it is a running Java application you will need to expose access to that function. There are a myriad of solutions possible.
If it is only 1 function or very limited functionality, then listening on the humble socket or named pipe is a solution which is currently undervalued and kind of forgotten.
On the next step of integration I would look at asynchronous message passing. It is easy to embed an activemq server or similar or start it in a separate process. This has a number of advantages like that the request are easily synchronized in the Java process by simply using one listening thread, that the behavior is well defined when the Java program is not available or the Delphi one. It is very easy to manage and you get the instrumentation for free.
An embedded Jetty webserver is an easy, reliable solution and implement a servlet to do your bidding. Again a lot of the complexity is now handled by using ubiquitous and standard protocols.
Then there are the synchronous RPC methods like COM, Corba, SOAP which I personally find much too complex, error-prone and maintenance unfriendly to use for ad-hoc communication between processes. If you want to build a complete infrastructure of stuff talking to each other it might be worth it, but not to get 2 programs talking.

PHP Communicating w/ Java program

We're come across a problem here at my company and I'm trying to find the best solution.
Software was recently purchased that utilizes a Java program to get the tax for a certain shipment. The site that needs this was written in PHP4. How can I communicate between the two?
It was suggested to use files to communicate but that was horribly slow since the Java program needed to be recompiled every time. So, what is the best solutions to this:
Create a mutli-threaded Java server and use PHP to send/receive the info.
Some other type of file-writing method
Something cool that I dont even know about.
Thanks in advance!
Edit:
I understand the importance of web services but why would this be more efficient that using a mutli-threaded socket-based java server? The only thing connecting to this web services will be my PHP program, no one else. It seems like it might be overkill for my simple task. Am I mistaken? If so, why? Thanks.
Wrap the Java program in a Web Service, and invoke it from PHP. You can even use caching in the Web Service, to optimize performance.
Why not dump the info into a database and have some sort of schedualed job read from it once and a while?
You can always use Quercus which allows you to run PHP in a Tomcat Servlet container.
Web Services is the elegant solution. But in many cases I found much practical to go for a quick-and-dirty solution: start a Java server that communicates using a lightweight communication protocol (none of the heavyweight stuff like XML from Web Services) - example: Apache Thrift. The write a very light client, that takes parameters from command line and writes the output to the console. The client can be in Java or even in other languages, like C++ (Apache Thrift supports that). Then you call the client with system() or with exec() from PHP.
This is not a solution I would ever recommend for production, but it's great for prototyping. Quick and dirty and flexible and extremely modest learning curve (if you already use light-weight communication between your Java processes).
Since you are using PHP4, you may want to just set up a tomcat server that is on a closed network, or just local on the machine of interest, and have it communicate with a servlet, that way you don't have to write a multi-threaded server and deal with creating a communication interface.
If you can upgrade, this page has two other options that may of interest:
http://us3.php.net/manual/en/intro.java.php
Give a look at Quercus
Quercus is Caucho Technology's fast, open-source, 100% Java implementation of the PHP language
I never used it though,
Web Services is the answer. Here's a nice intro link. Your problem is the very reason web services came to the forefront - communication between systems that couldn't ordinarily communicate.
What a web service is essentially going to do is send XML between the PHP and the Java systems. You're going to have to establish an interface for the two, which might be more difficult at the upstart, but you'll reap the benefits later on. In either case, it will be much faster than reading and writing files on the server. Disk I/O are the major bottlenecks on any server.
I may miss something, but if your java program output the needed values, can't you just start the java program from php using exec (http://dk.php.net/manual/en/function.exec.php)
Use the PHP/Java Bridge from sourceforge.net. It is mature, fast and easy to install.

Categories