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

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.

Related

Accessing HBase REST API through Java Applet

I am currently writing a small Java applet to access HBase data using the REST API. Accessing the data using Java is not particularly difficult, I have done this successfully. When running on a machine in my HDP cluster, the results are perfect. However when running as an applet I get no results at all. (I have chosen an applet since distributing an executable JAR is something my boss wants to avoid)
Having finally found what I believe to be the underlying issue, I have found the following runtime exception: hbase-default.xml file seems to be for an older version of HBase (null), this version is 1.1.2.2.4.0.0-169. My assumption is that this is caused by the fact that my local machine does not have HBase at all. The intention is that users will be able to view their own data from a local machine, and so I cannot expect all users to have HBase (or anything other than a browser)
My question really has two parts:
Is there anyway to get an applet like this to work?
Is there a better alternative to an applet for this kind of work?
Posting my code in case I have made some significant mistake:
public class HBaseConnector extends JApplet
{
private Cluster cluster;
public void init()
{
System.out.println("Applet initialising");
cluster = new Cluster();
cluster.add("hbase_server", 9080);
}
public void start()
{
System.out.println("Applet starting");
Client client = new Client(cluster);
RemoteHTable table = new RemoteHTable(client, "table_name");
Get get = new Get(Bytes.toBytes("key"));
get.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("Record"));
try
{
Result result1 = table.get(get);
JOptionPane.showMessageDialog(null, Bytes.toString(result1.getValue(Bytes.toBytes("f1"), Bytes.toBytes("Record"))), "Result", JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
System.err.println("Exception occurred");
}
}
public void stop()
{
System.out.println("Applet stopping");
}
public void destroy()
{
System.out.println("Applet destroyed");
}
}
While I haven't been able to solve this problem for an applet itself, I managed to get the app working by moving over the a JNLP app (JNLP). Given this, I suspect the underlying problem was a permissions issue due to the fact that applets run in a sandbox. This is fine, since I am aware that most browsers are moving away from Java plugins.
Another possible cause I discovered: hbase-default.xml must be in the root folder of the jar.

Using external server restlet framework

I am using the Restlet Framework, but now I want to change to a proper server instead of using localhost.
I have already added my php files (they access the java files using the rest_server URL) to the server's folder and my java files as well, but I am not sure how to change the code so it identifies where the new location of the files is.
Here is the code from IdentiscopeServer (constructor empty):
public static void main(String[] args) throws Exception {
//setsup our security manager
if (System.getSecurityManager() == null){
System.setSecurityManager(new SecurityManager());
}
identiscopeServerApp = new IdentiscopeServerApplication();
IdentiscopeServer server = new IdentiscopeServer();
server.getServers().add(Protocol.HTTP,8888);
server.getDefaultHost().attach("", identiscopeServerApp);
server.start();
}
I guess that the correct line to change is the one with "Protocol.HTTP, 8888". If the address of my new server is http://devweb2013.co.uk/research/Identiscope, how exactly do I set this up? Is there anything else necessary for it to work apart from just moving the files to a folder in the server?
The IdensticopeServerApplication is the following:
public class IdentiscopeServerApplication extends Application {
public IdentiscopeServerApplication() {
}
public Restlet createInboundRoot() {
Router router = new Router(getContext());
//attaches the /tweet path to the TweetRest class
router.attach("/collectionPublic", CollectionPublicREST.class);
router.attach("/collectionPrivate", CollectionPrivateREST.class);
router.attach("/analysis", AnalysisREST.class);
return router;
}
}
Thank you in advance, it is my first time using this Framework.
If I understand you correctly, you just want to run your main() method as the server, correct? In this case, the code for main() needs to be in a location that -- when running -- can provide the service at http://devweb2013.co.uk/research/Identiscope. Since you haven't stated what kind of server you are putting the code, I can't say where the best place to put the code would be. I assume you have superuser privileges on your deployment server, since the URL you provided implies port 80 will be serving your Identiscope web service (port 80 is a privileged port on most OS's). So as an answer, I can only provide general information.
On your deployment server, port 80 must be free (i.e. nothing else should be acting as a web server on port 80 on that machine) and the IdentiscopeApplication must be running on port 80. To do that, you need only change the line:
server.getServers().add(Protocol.HTTP,8888);
to:
server.getServers().add(Protocol.HTTP, 80);
then run the application as a user that is allowed to start servers on port 80 (preferably NOT the superuser). If you haven't already, you will need to get Java running on your deployment server and make sure all Restlet libraries are in the classpath where you plan to run your application.
If I understand what you are trying to do, then this should do the trick.

Calling a node.js script from inside 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.

WebSockets, GlassFish, Grizzly -- can't connect

I am trying to get started with WebSockets, and trying to write a simple application to send messages back and forth via a websoket.
However, it looks like the socket that I am trying to create never gets connected. Why can that be?
Below is the code of my WebSockets class. When .onConnect() is called, it logs:
I am socket, I was connected. Am i connected? - false
Update: in JavaScript, where I create the socket in question, the readyState is 1, which means "socket open, communication is possble".
import a.b.Misc; //writes logs.
import com.sun.grizzly.websockets.BaseServerWebSocket;
import com.sun.grizzly.websockets.DataFrame;
import com.sun.grizzly.websockets.WebSocketListener;
public class ChatWebSocket_v2 extends BaseServerWebSocket {
private String user;
public ChatWebSocket_v2(WebSocketListener... listeners) {
super(listeners);
}
public String getUser() {
if (user == null) {
Misc.print("User is null in ChatWebSocket");
throw new NullPointerException("+=The user is null in chat web socket");
}
return user;
}
public void setUser(String user) {
Misc.print("Just set user: " + user);
this.user = user;
}
#Override
public void onMessage(String message) {
Misc.print(message +"\n");
}
#Override
public void onMessage(byte[] message) {
Misc.print(new String(message) +" << Bytes\n");
}
#Override
public void onConnect() {
Misc.print("I am socket, i was connected. Am i connected? - " + this.isConnected());
}
#Override
public void onClose(DataFrame df) {
Misc.print("I am socket, i was closed");
}
}
If you're just trying to make a connection somewhere, you might want to try this instead. There is a live working demo and you can download the javascript code and play with it yourself. Note that the javascript code only works if you have it installed on a server (due to browser security because it's 'fancy'.) There is also a step by step browser-based client tutorial in the works that I will post as soon as it's ready. Most proxy servers haven't been upgraded to handle websockets so they will screw up connection request and most people won't be able to connect to websocket servers from work. Firefox 7 (release) or Google Chrome 14 or later support the latest version of the websocket protocol that the demo server runs.
If you want to try to get the grizzly demo working, you might have some debugging to do and maybe I'll help with that. Note that in comments below the article, other people said they couldn't get it working either and I haven't found any follow up. At this point it seems no better than the echo app above even if we do get it running and is possibly overly complicated and underly documented if you're just trying to get started. But if you want to try to get it running, you should 'git' the latest version of the code here, which was at least committed recently and may be fixed.
Then make sure that app.url in the application javascript file is set to your installation directory. His is hard-coded as:
url: 'ws://localhost:8080/grizzly-websockets-chat/chat',
If you're using Firefox 7, the javascript needs to be modified to use the Moz prefix, for example:
if (typeof MozWebSocket != "undefined") { // window.MozWebSocket or "MozWebSocket" in window
ok
} else if (window.WebSocket) { // he uses if ("WebSocket" in window)
ok
} else {
do your print "browser doesn't support websockets"
}
.... then if the browser supports websockets
websocket = new WebSocket(app.url); or
websocket = new MozWebSocket(app.url);
// depending on which it is.
The HLL websocket server demo code has this all sorted out.
(another) UPDATE: As I work through grizzly myself, I found on the Quick Start in the glassfish admin console, there's a hello sample that's pretty easy to set up and run. You'll find instructions there. The sample directory also contains a war file named: websocket-mozilla; so I guess its supposed to use websockets. Someone who's familiar with jsp should review the source code. All I can see is that it's using an http session. No mention of a websocket at all. It's a lot like the hello sample.

How can I emulate a COM port, write data to it and read data from it?

I'm trying to test my code that reads from a USB port (COM25 when the device is connected) that is created when a device is connected to my computer and to a boat. I cannot power the USB device when not on the boat so testing is difficult. Can someone let me know how to simulate a COM port and write data to it so my test program is able to connect to that simulated COM port and read that data?
I'm reading this from a Java program but the simulation doesn't need to be in Java or any specific language. Just a program that will simulate the COM port and allow me to connect to it. I downloaded a COM port emulator from AGG Software and it appears that it's writing to what I deem COM25 but I'm not able to connect to it from my Java test.
The general answer for this kind of problem is to wrap the code that talks to the COM port in a class that implements an interface. If you do this as a Facade (pattern) then you can also make the COM methods you call sensible from your end.
The interface can then be mocked or faked for the test. (There is a great article on test objects, but I haven't been able to find it yet.) One advantage here is that you can create a fake version that throws exceptions or otherwise does things that are possible for the port to do but hard to get it to do in practice.
Where I work, we solved a similar issue by having our emulator not spoof a COM port at all. Here's how you can do it:
Define an interface for talking with your COM port, something like IUsbCommService
Implement your real COM-communcation service, using the standard Java Comm API
For your emulator, simply kick of a thread that spits out the same sort of data you can expect from your USB device at regular intervals.
Use your IOC framework of choice (e.g., Spring) to wire up either the emulator or the real service.
As long as you hide your implementation logic appropriately, and as long as you code to your interface, your service-consumer code won't care whether it's talking to the real USB device or to the emulator.
For example:
import yourpackage.InaccessibleDeviceException;
import yourpackage.NoDataAvailableException;
public interface IUsbProviderService {
public void initDevice() throws InaccessibleDeviceException;
public UsbData getUsbData()
throws InaccessibleDeviceException, NoDataAvailableException;
}
// The real service
import javax.comm.SerialPort; //....and the rest of the java comm API
public class UsbService implements IUsbProviderService {
.
.
.
}
// The emulator
public class UsbServiceEmulator implements IUsbProviderService {
private Thread listenerThread;
private static final Long WAITTIMEMS = 10L;
private String usbData;
public UsbServiceEmulator(long maxWaitTime) throws InaccessibleDeviceException{
initialize();
boolean success = false;
long slept = 0;
while (!success && slept < maxWaitTime) {
Thread.sleep(WAITTIMEMS);
slept += WAITTIMEMS;
}
}
private void initialize() throws InaccessibleDeviceException{
listenerThread = new Thread();
listenerThread.start();
}
private class UsbRunner implements Runnable {
private String[] lines = {"Data line 1", "Data line 2", "Data line 3"};
public void run() {
int line = 0;
while(true) {
serialEvent(lines[line]);
if(line == 3) {
line = 0;
} else {
line++;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
//handle the error
}
}
private void serialEvent(String line) {
if(/*you have detected you have enough data */) {
synchronized(this) {
usbData = parser.getUsbData();
}
}
}
}
Hope this helps!
Thanks to all the answers so far! Here's what I ended up doing as a result of recommendations from someone at work.
Downloaded the COM Port Data Emulator (CPDE) from AGG Software
Downloaded the Virtual Serial Port Driver (VSPD) from Eltima Software
(I just randomly picked a free data emulator and virtual serial port package. There are plenty of alternatives out there)
Using VSPD, created virtual serial ports 24 and 25 and connected them via a virtual null modem cable. This effectively creates a write port at 24 and a read port at 25.
Ran the CPDE, connected to 24 and started writing my test data.
Ran my test program, connected to 25 and was able to read the test data from it
There are plenty of relevant answers in this section. But as for me, I personally use Virtual Serial Port Driver, which works perfect for me. But I must admit that there are plenty alternatives when it comes to creating virtual ports: freevirtualserialports.com; comOcom to name a few. But I haven't got a chance to use them, so my recommendation for solving this problem is Virtual Serial Port Driver.
I recommend fabulatech's virtual modem.
Get it at http://www.virtual-modem.com
You might also want to get a COM port monitor for your tests - You can find it at
http://www.serial-port-monitor.com
Good luck with the boat! :)
I use com0com and it works great for what I need.
In addition all others, I would like to added this nice, free emulator https://sites.google.com/site/terminalbpp/ I do use. I do also use AGG Com port data emulator.

Categories

Resources