Calling a node.js script from inside java - java

How can I call a node.js inside java and save the console.log values in a String variable?

Check these projects which allow you to run node.js scripts inside the jvm
https://github.com/apigee/trireme (Apigee)
http://nodyn.io/ (Redhat)
https://avatar-js.java.net/ (Oracle)

It is possible for a Java application to communicate with a running Node.JS application. For instance, you can have a Node.JS app running on an available port and the Java app can communicate with it via tcp sockets.
http://nodejs.org/api/net.html
Or you can create an http server and expose a rest service which your Java app can consume.
http://nodejs.org/api/http.html
Or as md_5 says, you can use Runtime.exec and then call getInputStream on the resulting process.
http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
The ways you can communicate between node.js and Java are no different from other cross application communication that can be done.
It is also possible to invoke Java code from your Node.JS application using something like node-java.
https://github.com/nearinfinity/node-java

Yes, It is very eassy to execute and node.js file using java.
import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class RunScriptFileDemo {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
try {
FileReader reader = new FileReader("yourFile.js");
engine.eval(reader);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Check out https://github.com/caoccao/Javet, you can embed a node.js runtime inside a java
application and share variables between both.

Cant be done. For normal JS you can use Rhino, but for Node you will need to make sure it is in the PATH then call Runtine.exec or a ProcessBuilder with ByteArrayOutputsreams that can later be cinverted to strings. The node code cannot access Java and vice versa.

Related

Call to Reader.Capture() in DigitalPersona U.are.U SDK does not return

I am developing an application for a DigitalPersona U.are.U 4500 fingerprint reader and using the U.are.U 2.2.3 SDK Java API.
The sample Java application that ships with the SDK works flawlessly.
However, when I try to do the same thing in my own sample application, the call to the Reader.Capture() method never returns, even though I can see the reader flashing when recording my fingerprint.
Below is a variation on the sample code I have tried with.
Other things I have tried:
Running the capture code in an instance of the class (i.e. not in a static context)
Running the capture operation in its own thread as well, but the results are the same.
Using the CaptureThread class from the demo application
The only difference I can see between my sample and the SDK sample app is that the latter is a graphical application. But why would that make a difference?
Unplugging the device causes the call to fail with an exception. That is about the only way I can get it to return.
import com.digitalpersona.uareu.*;
public class Main{
static Reader r;
public static void main(String[] args) {
try {
// Pick first available reader
ReaderCollection rc = UareUGlobal.GetReaderCollection();
rc.GetReaders();
r = rc.get(0);
if (r==null)
return;
// Open Reader
r.Open(Reader.Priority.COOPERATIVE);
System.out.println(r.GetStatus().status); // Outputs READY
// The following call just hangs and never returns...
Reader.CaptureResult
cr = r.Capture(Fid.Format.ISO_19794_4_2005, Reader.ImageProcessing.IMG_PROC_DEFAULT, 500, -1);
System.out.println(cr.quality.name()); // Just to test
} catch (UareUException e) {
e.printStackTrace();
}
}
}
The last two parameters, the two ints, passed to the Capture method are the resolution and the timeout respectively; passing -1 for the timeout blocks indefinitely. This is taken from the sample application as well.
I finally managed to get an example working.
Strange as it may seem, it only works in the context of a Java GUI application.
So, simply extending a JFrame and starting the reader capture on a separate thread seems to be sufficient.
This requirement is not specified anywhere in the SDK documentation that I can see.
UPDATE
It seems the problem is worse than I initially thought. Not only must the API be called in the context of a Java GUI application, but the GUI must also be in focus, otherwise the capture call simply does not return.
I have verified this with the example SDK applications. The Capture() method does not return if the apps are not in focus. This also applies to the C# examples, where the windows must be in focus, which suggests that this is built into the DLLs that ship with the solution.
This is terrible for our scenario, where we want to develop a local service that a browser can communicate with because, while the browser is in focus, obviously the Java application is not.
I faced the similar issue and it can be fixed by opening a reader in exclusive mode as below,
m_reader.Open(Reader.Priority.EXCLUSIVE);
Refer to below lines from documents,
public static final Reader.Priority COOPERATIVE
Client uses this priority to open reader in cooperative mode. Multiple clients with this priority are allowed. Client receives captured images if it has window with focus.
public static final Reader.Priority EXCLUSIVE
Client uses this priority to open reader exclusively. Only one client with this priority is allowed.

PHP/Java Bridge. How to connect from php server to desktop App

I'm testing PHP/Java Bridge connection. And I have a simple example yet.
The php file is:
require_once("http://localhost:8087/JavaBridge/java/Java.inc");
$world = new java("HelloWorld");
echo $world->hello(array("from PHP"));
And the java file:
import javax.swing.JOptionPane;
public class HelloWorld {
public static final String JAVABRIDGE_PORT="8087";
static final php.java.bridge.JavaBridgeRunner runner =
php.java.bridge.JavaBridgeRunner.getInstance(JAVABRIDGE_PORT);
public static void main(String args[]) throws Exception {
runner.waitFor();
System.exit(0);
}
public void hello(String args[]) throws Exception {
JOptionPane.showMessageDialog(null, "hello " + args[0]);
}
}
Everything works fine on one pc. But I have to implement connection from PHP server to java desktop application which is on the another server not on localhost, so "localhost:8087/JavaBridge/java/Java.inc" won't work. In future this java app will print on printer some data from php website.
So I need to call java function remotely. It should be a desktop App because I will write usb connection in future. Please help me, thanks.
You can't use require_once to include files from another host.
If this option is available, a lot of websites will be at risk.
Why don't you use it from another way, Here are some points that may help:
make java calls PHP.
write your result to some file in the destination server.
Make server reads that file.
If you don't like that, please read about web service, it may have what you need.

How to use android-json-rpc for Android(client)/Java(server) setup?

I am trying to use https://code.google.com/p/android-json-rpc/ for android and use https://github.com/RitwikSaikia/jsonrpc on the java server.
I have followed the examples for android-json-rpc client and jsonrpc server setup.
When using android-json-rpc in my Android app I do the following.
JSONRPCClient client = JSONRPCClient.create("http://service/uri",JSONRPCParams.Versions.VERSION_2);
client.setConnectionTimeout(2000);
client.setSoTimeout(2000);
try
{
client.callString("SimpleCalculatorImpl");
double i = client.callDouble("add", 56, 25);
}
catch (JSONRPCException e)
{
e.printStackTrace();
}
For the Java server I have followed the sample at https://github.com/RitwikSaikia/jsonrpc#defining-interfaces and at https://github.com/RitwikSaikia/jsonrpc#hosting-the-service
When I call the method
String string = client.callString("SimpleCalculatorImpl");
It throws a JSONRPCException: Cannot convert result to String which comes from inside the callString method.
Has anyone encountered this error before or know of better a library to use for an Android client to a Java server for JSON?
i haven't tried the library but i know that this exception happens when the json is not parsed correctly, try to copy the result and run it through a json validator like JSONLint
hope this helps.
I actually just used https://github.com/FasterXML/jackson on both Android client side and Java server side and created my own servlet with reflection to handle making calls to methods on the Java server and getting back the results on the Android client
I haven't used either of the libraries, but from looking at it briefly, it seems like the jsonrpc server library registers a prefix handler with executor.addHandler("calc", calcImpl, Calculator.class);, so the fully qualified name of the "add" method would be "calc.add". So just try following in your code:
double i = client.callDouble("calc.add", 56, 25);
No need to call client.callString("SimpleCalculatorImpl");, as callString() should be used for RPC calls that return String result.

comunication between Web browser and java

I Am developing a private web site in PHP-html / Ajax and a client program in Java.
I have just seen that apple can, by Firefox or other, open iTunes to load content.
I want to do the same or better:
I try to make a program which can “talk” to javascript or just write a lockFile (tempfile) and so get data through this one, i try to get at least a communication Web browser - > java, but i'd rather if possible a bi-directional communication.
So if somebody have any solution, it’s will be great cause I googlised it, i tried local Storage in html5, File access in javascript … nothing really works and I don’t want the program to ask the server Avery time.
You can do this in a number of ways but you must have in mind the cross-domain restrictions. I've been doing this with sockets.
1 - You need a bridge to comunicate your web with your server this could be done with a java applet or a flash socket bridge so that you can call your server and your javascript client code.
2 - You need url-redirect rule in your server so that when your client makes a request it always makes it in the same domain but gets where your socket server finally is. You client can't go to a different domain but your server can. This is needed to skip the cross-domain restriction.
I hope this helps.
You can take a look at JxBrowser library that allows embedding Google Chromium engine into Java Swing applications. You can use this library to embed Browser component into your client Java application and load your PHP web page, like iTunes loads App Store.
It provides API for two-way communication Java-to-JavaScript-to-Java: http://www.teamdev.com/downloads/jxbrowser/docs/JxBrowser-PGuide.html#javascript-java-bridge
The following code demonstrates how to embed Browser component, load URL, invoke JavaScript code on the loaded web page and register Java function on JavaScript side that will be invoked every time when JavaScript invokes it:
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.BrowserFunction;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
/**
* The sample demonstrates how to register a new JavaScript function and
* map it to a Java method that will be invoked every time when the JavaScript
* function is invoked.
*/
public class JavaScriptJavaSample {
public static void main(String[] args) {
Browser browser = BrowserFactory.create();
// Register "MyFunction" JavaScript function and associate Java callback with it
browser.registerFunction("MyFunction", new BrowserFunction() {
public JSValue invoke(JSValue... args) {
for (JSValue arg : args) {
System.out.println("arg = " + arg);
}
return JSValue.create("Hello!");
}
});
// Create JFrame and embed Browser component to display web pages
JFrame frame = new JFrame();
frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// Register Load listener to get notification when web page is loaded completely
browser.addLoadListener(new LoadAdapter() {
#Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
if (event.isMainFrame()) {
Browser browser = event.getBrowser();
// Invoke our registered JavaScript function
JSValue returnValue = browser.executeJavaScriptAndReturnValue(
"MyFunction('Hello JxBrowser!', 1, 2, 3, true);");
System.out.println("return value = " + returnValue);
}
}
});
browser.loadURL("about:blank");
}
}

Communication between two Machines using java

I have Gui Application written which running on windows,and i want to connect to remote unix machine and perform actions there such like API's ,go over the log file in the machines and send back to the application the last log file or others API that i want to perform on the remote machine.
In the remote machine i don;t have application server i just have Java which installed there.
I want to use Java in order to perform remote API over the remote machine;
what is the advice ,can i use web services ,can any one please advise.
Thanks in advance.
If Java can perform the actions you're talking about, I would use Sockets to communicate with the UNIX-Machine (over TCP/IP).
Your Windows-PC would be the client sending commands to the Unix-PC.
Web services would be a bit heavy handed option, esp if you opt for the SOAP ones. If you don't have a problem with the client and server always being Java, RMI seems to be the simplest solution to this problem since it's communication between two different JVM's using the normal method calling mechanism (with some additional interfaces and rules to be followed to please the RMI specification).
The Spring Framework ships with a number of remoting options that are all very easy to setup. You can use their classes for simpler configuration of something standard like RMI or JMS, or use a lightweight web services protocol such as Spring's HTTP invoker or Hessian.
For analyzing log files of remote machines you can always use Apache Commons sftp programmatically to FTP a copy of the remote log file to your PC.
If you configure the log files to be rotatable or to rotate each time they reach a specific size, you can avoid reloading the same information over and over.
You can use Ganymed SSH-2 for Java to ssh to the remote host from Client Java App and run the commands. No need to run any additional components on remote server. You can do password based authentication or key based authentication to login to remote host. We had successfully used it to administer (start/stop/grep log files, etc.) applications running on remote UNIX hosts. You can capture output of the remote command using the StreamGobbler class provided in the package. You can pass multiple commands separated by semi-colon in one remote call.
Basic Example included in the package:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class Basic
{
public static void main(String[] args)
{
String hostname = "127.0.0.1";
String username = "joe";
String password = "joespass";
try
{
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* Now connect */
conn.connect();
/* Authenticate.
* If you get an IOException saying something like
* "Authentication method password not supported by the server at this stage."
* then please check the FAQ.
*/
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* Create a session */
Session sess = conn.openSession();
sess.execCommand("uname -a && date && uptime && who");
System.out.println("Here is some information about the remote host:");
/*
* This basic example does not handle stderr, which is sometimes dangerous
* (please read the FAQ).
*/
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
System.exit(2);
}
}
}

Categories

Resources